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,
)
| 82 | |
| 83 | |
| 84 | def 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 | |
| 138 | def reset_qconfig(module: Module, qconfig: QConfig, inplace: bool = True): |