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 6.5 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2020 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 typing import Callable, Dict, Tuple
  10. from .. import module as Float
  11. from ..module import Module
  12. from ..module import qat as QAT
  13. from ..module import quantized as Quantized
  14. from ..module.qat import QATModule
  15. from ..module.quantized import QuantizedModule
  16. from .fake_quant import TQT
  17. from .qconfig import QConfig, ema_fakequant_qconfig
  18. def _get_quantable_module_names():
  19. def is_quantable(key: str):
  20. value = getattr(Quantized, key)
  21. return (
  22. isinstance(value, type)
  23. and issubclass(value, QuantizedModule)
  24. and value != QuantizedModule
  25. )
  26. # source should have all quantable modules' names
  27. quantable_module_names = [key for key in dir(Quantized) if is_quantable(key)]
  28. return quantable_module_names
  29. def _get_convert_dict() -> Tuple[
  30. Dict[Module, QATModule], Dict[QATModule, QuantizedModule]
  31. ]:
  32. quantable_module_names = _get_quantable_module_names()
  33. quantable_modules = [getattr(Float, key) for key in quantable_module_names]
  34. qat_modules = [getattr(QAT, key) for key in quantable_module_names]
  35. quantized_modules = [getattr(Quantized, key) for key in quantable_module_names]
  36. float2qat_dict = dict(zip(quantable_modules, qat_modules))
  37. qat2quantized_dict = dict(zip(qat_modules, quantized_modules))
  38. return float2qat_dict, qat2quantized_dict
  39. _float2qat_dict, _qat2quantized_dict = _get_convert_dict()
  40. def quantize(module: Module, inplace: bool = True, mapping: dict = None):
  41. r"""
  42. Recursively convert :class:`~.QATModule` to :class:`~.QuantizedModule`
  43. through :meth:`~.Module.apply`.
  44. :param module: root module to do convert recursively.
  45. :param inplace: whether to convert submodules in-place.
  46. :param mapping: a dict indicating how to convert custom modules from QATModule to
  47. QuantizedModule. Will be combined with internal default convert mapping dict.
  48. """
  49. if not inplace:
  50. module = deepcopy(module)
  51. convert_dict = copy(_qat2quantized_dict)
  52. if mapping is not None:
  53. convert_dict.update(mapping)
  54. qat_modules = tuple(convert_dict.keys())
  55. def is_qat(mod: Module):
  56. return isinstance(mod, qat_modules)
  57. # must use list to avoid replacement influencing successor modules
  58. for key, submodule, parent in list(
  59. module._flatten(with_key=True, with_parent=True, predicate=is_qat)
  60. ):
  61. new_mod = convert_dict[type(submodule)].from_qat_module(submodule)
  62. if isinstance(parent, Float.Sequential):
  63. # cannnot use setattr to be compatible with Sequential's ``__setitem__``
  64. parent[int(key.split(".")[-1])] = new_mod
  65. else:
  66. setattr(parent, key.split(".")[-1], new_mod)
  67. return module
  68. def quantize_qat(
  69. module: Module,
  70. inplace: bool = True,
  71. qconfig: QConfig = ema_fakequant_qconfig,
  72. mapping: dict = None,
  73. ):
  74. r"""
  75. Recursively convert float :class:`~.Module` to :class:`~.QATModule`
  76. through :meth:`~.Module.apply` and set qconfig relatively.
  77. :param module: root module to do convert recursively.
  78. :param inplace: whether to convert submodules in-place.
  79. :param qconfig: an instance of :class:`~.QConfig` to be set as submodules' qconfig.
  80. default is ``ema_fakequant_qconfig``.
  81. :param mapping: a dict indicating how to convert custom modules from Module to QATModule.
  82. Will be combined with internal default convert mapping dict.
  83. """
  84. if not inplace:
  85. module = deepcopy(module)
  86. convert_dict = copy(_float2qat_dict)
  87. if mapping is not None:
  88. convert_dict.update(mapping)
  89. quantable_modules = tuple(convert_dict.keys())
  90. def is_quantable(mod: Module):
  91. return isinstance(mod, quantable_modules)
  92. # must use list to avoid replacement influencing successor modules
  93. for key, submodule, parent in list(
  94. module._flatten(with_key=True, with_parent=True, predicate=is_quantable)
  95. ):
  96. # only convert top quantable module.
  97. if is_quantable(parent) or submodule.quantize_disabled:
  98. continue
  99. new_mod = convert_dict[type(submodule)].from_float_module(submodule)
  100. if isinstance(parent, Float.Sequential):
  101. # cannnot use setattr to be compatible with Sequential's ``__setitem__``
  102. parent[int(key.split(".")[-1])] = new_mod
  103. else:
  104. setattr(parent, key.split(".")[-1], new_mod)
  105. propagate_qconfig(module, qconfig)
  106. return module
  107. def _propagate(module: Module, func_str: str, *args, **kargs):
  108. def fn(mod: Module):
  109. if isinstance(mod, QATModule):
  110. getattr(mod, func_str)(*args, **kargs)
  111. module.apply(fn)
  112. def propagate_qconfig(module: QATModule, qconfig: QConfig):
  113. r"""
  114. Recursively set ``module``'s qconfig through :meth:`~.Module.apply`.
  115. :param module: root module to traverse recursively.
  116. :param qconfig: a instance of :class:`~.QConfig` to be set as submodules' qconfig.
  117. """
  118. _propagate(module, "set_qconfig", qconfig)
  119. def disable_fake_quant(module: Module):
  120. r"""
  121. Recursively disable ``module`` fake quantization in QATModule through :meth:`~.Module.apply`
  122. :param module: root module to do disable fake quantization recursively.
  123. """
  124. _propagate(module, "set_fake_quant", False)
  125. def disable_observer(module: Module):
  126. r"""
  127. Recursively disable ``module`` observer in QATModule through :meth:`~.Module.apply`
  128. :param module: root module to do disable observer recursively.
  129. """
  130. _propagate(module, "set_observer", False)
  131. def enable_fake_quant(module: Module):
  132. r"""
  133. Recursively enable ``module`` fake quantization in QATModule through :meth:`~.Module.apply`
  134. :param module: root module to do enable fake quantization recursively.
  135. """
  136. _propagate(module, "set_fake_quant", True)
  137. def enable_observer(module: Module):
  138. r"""
  139. Recursively enable ``module`` observer in QATModule through :meth:`~.Module.apply`
  140. :param module: root module to do enable observer recursively.
  141. """
  142. _propagate(module, "set_observer", True)

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