You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

quantize.py 9.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
  4. #
  5. # Unless required by applicable law or agreed to in writing,
  6. # software distributed under the License is distributed on an
  7. # "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  8. from copy import copy, deepcopy
  9. from functools import partial
  10. from typing import Callable
  11. import numpy as np
  12. from .. import module as Float
  13. from ..functional import concat, norm
  14. from ..module import Module
  15. from ..module import qat as QAT
  16. from ..module import quantized as Quantized
  17. from ..module.qat import QATModule
  18. from ..module.quantized import QuantizedModule
  19. from ..tensor import Tensor
  20. from ..utils.module_utils import set_expand_structure
  21. from .qconfig import QConfig, ema_fakequant_qconfig
  22. def _get_quantable_module_names():
  23. def is_quantable(key: str):
  24. value = getattr(Quantized, key)
  25. return (
  26. isinstance(value, type)
  27. and issubclass(value, QuantizedModule)
  28. and value != QuantizedModule
  29. )
  30. # source should have all quantable modules' names
  31. quantable_module_names = [key for key in dir(Quantized) if is_quantable(key)]
  32. return quantable_module_names
  33. def _get_convert_dict():
  34. quantable_module_names = _get_quantable_module_names()
  35. quantable_modules = [getattr(Float, key) for key in quantable_module_names]
  36. qat_modules = [getattr(QAT, key) for key in quantable_module_names]
  37. quantized_modules = [getattr(Quantized, key) for key in quantable_module_names]
  38. float2qat_dict = dict(zip(quantable_modules, qat_modules))
  39. qat2quantized_dict = dict(zip(qat_modules, quantized_modules))
  40. return float2qat_dict, qat2quantized_dict
  41. _float2qat_dict, _qat2quantized_dict = _get_convert_dict()
  42. qat_modules = tuple(_qat2quantized_dict.keys())
  43. def quantize(module: Module, inplace: bool = True, mapping: dict = None):
  44. r"""
  45. Recursively convert :class:`~.QATModule` to :class:`~.QuantizedModule`
  46. through :meth:`~.Module.apply`.
  47. :param module: root module to do convert recursively.
  48. :param inplace: whether to convert submodules in-place.
  49. :param mapping: a dict indicating how to convert custom modules from QATModule to
  50. QuantizedModule. Will be combined with internal default convert mapping dict.
  51. """
  52. if not inplace:
  53. module = deepcopy(module)
  54. convert_dict = copy(_qat2quantized_dict)
  55. if mapping is not None:
  56. convert_dict.update(mapping)
  57. qat_modules = tuple(convert_dict.keys())
  58. def is_qat(mod: Module):
  59. return isinstance(mod, qat_modules)
  60. # must use list to avoid replacement influencing successor modules
  61. for key, submodule, parent in list(
  62. module._flatten(with_key=True, with_parent=True, predicate=is_qat)
  63. ):
  64. new_mod = convert_dict[type(submodule)].from_qat_module(submodule)
  65. set_expand_structure(module, key, new_mod)
  66. return module
  67. def quantize_qat(
  68. module: Module,
  69. inplace: bool = True,
  70. qconfig: QConfig = ema_fakequant_qconfig,
  71. mapping: dict = None,
  72. ):
  73. r"""
  74. Recursively convert float :class:`~.Module` to :class:`~.QATModule`
  75. through :meth:`~.Module.apply` and set qconfig relatively.
  76. :param module: root module to do convert recursively.
  77. :param inplace: whether to convert submodules in-place.
  78. :param qconfig: an instance of :class:`~.QConfig` to be set as submodules' qconfig.
  79. default is ``ema_fakequant_qconfig``.
  80. :param mapping: a dict indicating how to convert custom modules from Module to QATModule.
  81. Will be combined with internal default convert mapping dict.
  82. """
  83. if not inplace:
  84. module = deepcopy(module)
  85. convert_dict = copy(_float2qat_dict)
  86. if mapping is not None:
  87. convert_dict.update(mapping)
  88. quantable_modules = tuple(convert_dict.keys())
  89. def is_quantable(mod: Module):
  90. return isinstance(mod, quantable_modules)
  91. # must use list to avoid replacement influencing successor modules
  92. for key, submodule, parent in list(
  93. module._flatten(with_key=True, with_parent=True, predicate=is_quantable)
  94. ):
  95. # only convert top quantable module.
  96. if is_quantable(parent) or submodule.quantize_disabled:
  97. continue
  98. new_mod = convert_dict[type(submodule)].from_float_module(submodule)
  99. set_expand_structure(module, key, new_mod)
  100. propagate_qconfig(module, qconfig)
  101. return module
  102. def reset_qconfig(module: Module, qconfig: QConfig, inplace: bool = True):
  103. r"""
  104. Reset :class:`~._FakeQuantize` and :class:`~.Observer` according to ``qconfig``
  105. :param module: root module to reset recursively.
  106. :param qconfig: an instance of :class:`~.QConfig` to be set as submodules' qconfig.
  107. :param inplace: whether to reset submodules in-place.
  108. """
  109. if not inplace:
  110. module = deepcopy(module)
  111. def safe_call(func, qparams):
  112. inst = func() if func is not None else None
  113. if inst is not None and getattr(inst, "set_qparams", None) is not None:
  114. inst.set_qparams(qparams)
  115. return inst
  116. def is_qat(mod: Module):
  117. return isinstance(mod, QATModule)
  118. for m in list(module._flatten(predicate=is_qat)):
  119. if m.with_weight:
  120. weight_params = m.get_weight_qparams()
  121. m.weight_observer = safe_call(qconfig.weight_observer, weight_params)
  122. m.weight_fake_quant = safe_call(qconfig.weight_fake_quant, weight_params)
  123. if m.with_act:
  124. act_params = m.get_activation_qparams()
  125. m.act_observer = safe_call(qconfig.act_observer, act_params)
  126. m.act_fake_quant = safe_call(qconfig.act_fake_quant, act_params)
  127. return module
  128. def _propagate(module: Module, func_str: str, *args, **kargs):
  129. def fn(mod: Module):
  130. if isinstance(mod, QATModule):
  131. getattr(mod, func_str)(*args, **kargs)
  132. module.apply(fn)
  133. def propagate_qconfig(module: QATModule, qconfig: QConfig):
  134. r"""
  135. Recursively set ``module``'s qconfig through :meth:`~.Module.apply`.
  136. :param module: root module to traverse recursively.
  137. :param qconfig: a instance of :class:`~.QConfig` to be set as submodules' qconfig.
  138. """
  139. _propagate(module, "set_qconfig", qconfig)
  140. def hook_qat_module(module: Module, func: Callable):
  141. r"""
  142. Add hooks for all :class:`~.QATModule` submodule
  143. """
  144. def is_qat(mod: Module):
  145. return isinstance(mod, QATModule)
  146. hooks = []
  147. for submodule in list(module._flatten(predicate=is_qat)):
  148. hooks.append(submodule.register_forward_hook(func))
  149. return hooks
  150. def apply_easy_quant(
  151. module: Module, data: Tensor, start: float = 0.8, stop: float = 1.2, num: int = 40
  152. ):
  153. r"""
  154. Implementation of ``EasyQuant``: https://arxiv.org/pdf/2006.16669.
  155. Search for optimal scales.
  156. :param module: root module.
  157. :param data: input tensor used to search optimal scale.
  158. :param start: lower bound of the search interval.
  159. :param stop: upper bound of the search interval.
  160. :param num: number of samples to search.
  161. """
  162. batch_size = data.shape[0]
  163. def get_cosine(x, y):
  164. ndim = len(x.shape)
  165. axis = tuple(range(1, ndim))
  166. up = (x * y).sum(axis=axis)
  167. down = norm(x, axis=axis) * norm(y, axis=axis)
  168. sim = up / down
  169. return sim.mean(axis=0)
  170. def search(mod, inputs, outputs, where):
  171. mod._forward_hooks.clear()
  172. normal_in = [_[:batch_size] for _ in inputs]
  173. fakequant_in = [_[batch_size:] for _ in inputs]
  174. disable_fake_quant(mod)
  175. normal_out = mod(*normal_in)
  176. enable_fake_quant(mod)
  177. ob = getattr(mod, where)
  178. if ob is None:
  179. return
  180. orig_scale = ob.orig_scale
  181. distance = 0
  182. best_scale = 0
  183. for scale in np.linspace(start * orig_scale, stop * orig_scale, num):
  184. ob.scale = scale
  185. fakequant_out = mod(*fakequant_in)
  186. dis = get_cosine(normal_out, fakequant_out)
  187. if dis > distance:
  188. distance = dis
  189. best_scale = scale
  190. ob.scale = best_scale
  191. fakequant_out = outputs[batch_size:]
  192. return concat([normal_out, fakequant_out])
  193. data = concat([data, data])
  194. hook_qat_module(module, partial(search, where="weight_observer"))
  195. module(data)
  196. hook_qat_module(module, partial(search, where="act_observer"))
  197. module(data)
  198. return module
  199. def disable_fake_quant(module: Module):
  200. r"""
  201. Recursively disable ``module`` fake quantization in QATModule through :meth:`~.Module.apply`
  202. :param module: root module to do disable fake quantization recursively.
  203. """
  204. _propagate(module, "set_fake_quant", False)
  205. def disable_observer(module: Module):
  206. r"""
  207. Recursively disable ``module`` observer in QATModule through :meth:`~.Module.apply`
  208. :param module: root module to do disable observer recursively.
  209. """
  210. _propagate(module, "set_observer", False)
  211. def enable_fake_quant(module: Module):
  212. r"""
  213. Recursively enable ``module`` fake quantization in QATModule through :meth:`~.Module.apply`
  214. :param module: root module to do enable fake quantization recursively.
  215. """
  216. _propagate(module, "set_fake_quant", True)
  217. def enable_observer(module: Module):
  218. r"""
  219. Recursively enable ``module`` observer in QATModule through :meth:`~.Module.apply`
  220. :param module: root module to do enable observer recursively.
  221. """
  222. _propagate(module, "set_observer", True)

MegEngine 安装包中集成了使用 GPU 运行代码所需的 CUDA 环境,不用区分 CPU 和 GPU 版。 如果想要运行 GPU 程序,请确保机器本身配有 GPU 硬件设备并安装好驱动。 如果你想体验在云端 GPU 算力平台进行深度学习开发的感觉,欢迎访问 MegStudio 平台