MCPcopy Create free account
hub / github.com/MegEngine/MegEngine / quantize_qat

Function quantize_qat

imperative/python/megengine/quantization/quantize.py:84–135  ·  view source on GitHub ↗

r"""Recursively convert float :class:`~.Module` to :class:`~.QATModule` through :meth:`~.Module.apply` and set qconfig relatively. Args: module: root module to do convert recursively. inplace: whether to convert submodules in-place. qconfig: an instance of :class:`~.

(
    module: Module,
    inplace: bool = True,
    qconfig: QConfig = ema_fakequant_qconfig,
    mapping: dict = None,
)

Source from the content-addressed store, hash-verified

82
83
84def quantize_qat(
85 module: Module,
86 inplace: bool = True,
87 qconfig: QConfig = ema_fakequant_qconfig,
88 mapping: dict = None,
89):
90 r"""Recursively convert float :class:`~.Module` to :class:`~.QATModule`
91 through :meth:`~.Module.apply` and set qconfig relatively.
92
93 Args:
94 module: root module to do convert recursively.
95 inplace: whether to convert submodules in-place.
96 qconfig: an instance of :class:`~.QConfig` to be set as submodules' quant config. Default: ``ema_fakequant_qconfig``.
97 mapping: a dict indicating how to convert custom modules from Module to QATModule.
98 Will be combined with internal default convert mapping dict.
99
100 Returns:
101 Return type: Module. Quantized module.
102
103 Examples:
104 >>> import megengine.quantization as Q
105 >>> model = Net() # doctest: +SKIP
106 >>> Q.quantize_qat(model, qconfig=Q.ema_fakequant_qconfig) # doctest: +SKIP
107 """
108 assert isinstance(inplace, bool) and isinstance(
109 qconfig, QConfig
110 ), "the type of input args(inplace and qconfig) is wrong, please check them."
111
112 if not inplace:
113 module = deepcopy(module)
114
115 convert_dict = copy(_float2qat_dict)
116 if mapping is not None:
117 convert_dict.update(mapping)
118 quantable_modules = tuple(convert_dict.keys())
119
120 def is_quantable(mod: Module):
121 return isinstance(mod, quantable_modules)
122
123 # must use list to avoid replacement influencing successor modules
124 for key, submodule, parent in list(
125 module._flatten(with_key=True, with_parent=True, predicate=is_quantable)
126 ):
127 # only convert top quantable module.
128 if is_quantable(parent) or submodule.quantize_disabled:
129 continue
130
131 new_mod = convert_dict[type(submodule)].from_float_module(submodule)
132 set_expand_structure(module, key, new_mod)
133
134 propagate_qconfig(module, qconfig)
135 return module
136
137
138def reset_qconfig(module: Module, qconfig: QConfig, inplace: bool = True):

Calls 9

listFunction · 0.85
is_quantableFunction · 0.85
set_expand_structureFunction · 0.85
propagate_qconfigFunction · 0.85
keysMethod · 0.80
_flattenMethod · 0.80
copyFunction · 0.50
updateMethod · 0.45
from_float_moduleMethod · 0.45