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.

module.py 6.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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 abc import abstractmethod
  9. # avoid circular reference
  10. from ...quantization.fake_quant import FakeQuantize
  11. from ...quantization.observer import Observer
  12. from ...quantization.qconfig import QConfig
  13. from ...quantization.utils import fake_quant_bias
  14. from ...tensor import Tensor
  15. from ..module import Module
  16. class QATModule(Module):
  17. r"""
  18. Base class of quantized-float related :class:`~.Module`, basically for QAT and Calibration.
  19. Use :meth:`from_float_module` to generate a instance from float :class:`~.Module`.
  20. Or use :func:`~.quantize.quantize_qat` to do it recursively and automatically.
  21. Can also be converted to :class:`~.QuantizedModule` for deployment using
  22. :func:`~.quantize.quantize` further.
  23. """
  24. with_weight = True
  25. with_act = True
  26. def __init__(self, **kwargs):
  27. super().__init__(**kwargs)
  28. self.weight_observer = None # type: Observer
  29. self.act_observer = None # type: Observer
  30. self.weight_fake_quant = None # type: FakeQuantize
  31. self.act_fake_quant = None # type: FakeQuantize
  32. def set_qconfig(self, qconfig: QConfig):
  33. r"""
  34. Set quantization related configs with ``qconfig``, including
  35. observer and fake_quant for weight and activation.
  36. """
  37. def safe_call(func):
  38. return func() if func is not None else None
  39. if self.with_act:
  40. self.act_observer = safe_call(qconfig.act_observer)
  41. self.act_fake_quant = safe_call(qconfig.act_fake_quant)
  42. if self.with_weight:
  43. self.weight_observer = safe_call(qconfig.weight_observer)
  44. self.weight_fake_quant = safe_call(qconfig.weight_fake_quant)
  45. def _enable_exec(self, with_module, func, enable):
  46. if not with_module or not func:
  47. return
  48. if enable:
  49. func.enable()
  50. else:
  51. func.disable()
  52. def set_fake_quant(self, enable):
  53. self._enable_exec(self.with_act, self.act_fake_quant, enable)
  54. self._enable_exec(self.with_weight, self.weight_fake_quant, enable)
  55. def set_observer(self, enable):
  56. self._enable_exec(self.with_act, self.act_observer, enable)
  57. self._enable_exec(self.with_weight, self.weight_observer, enable)
  58. def _apply_fakequant_with_observer(
  59. self, target: Tensor, fake_quant: FakeQuantize, observer: Observer
  60. ):
  61. # do observer
  62. if observer is None:
  63. oup = target
  64. qparams = None
  65. else:
  66. oup = observer(target)
  67. qparams = observer.get_qparams()
  68. # do fake quant
  69. if fake_quant is not None:
  70. oup = fake_quant(oup, qparams)
  71. # use qparams of fake_quant if have.
  72. if hasattr(fake_quant, "get_qparams"):
  73. qparams = fake_quant.get_qparams()
  74. # set to tensor qparams.
  75. if qparams is not None:
  76. oup.qparams.update(qparams)
  77. return oup
  78. def apply_quant_weight(self, target: Tensor):
  79. r"""
  80. Apply weight's observer and fake_quant from ``qconfig`` on ``target``.
  81. """
  82. return self._apply_fakequant_with_observer(
  83. target, self.weight_fake_quant, self.weight_observer
  84. )
  85. def apply_quant_activation(self, target: Tensor):
  86. r"""
  87. Apply weight's observer and fake_quant from ``qconfig`` on ``target``.
  88. """
  89. return self._apply_fakequant_with_observer(
  90. target, self.act_fake_quant, self.act_observer
  91. )
  92. def apply_quant_bias(self, target: Tensor, inp: Tensor, w_qat: Tensor):
  93. r"""
  94. Use :func:`~.fake_quant_bias` to process ``target``. Only valid when
  95. ``act_fake_quant`` and ``weight_fake_quant`` are both enabled.
  96. """
  97. # bias should have the same dtype as activation, so act_fake_quant can also
  98. # decide whether to do bias fakequant
  99. if (
  100. self.act_fake_quant
  101. and self.act_fake_quant.enabled
  102. and self.weight_fake_quant
  103. and self.weight_fake_quant.enabled
  104. ):
  105. b_qat = fake_quant_bias(target, inp, w_qat)
  106. else:
  107. b_qat = target
  108. return b_qat
  109. def _get_method_result(
  110. self, method: str, fake_quant: FakeQuantize, observer: Observer
  111. ):
  112. if hasattr(fake_quant, method):
  113. return getattr(fake_quant, method)()
  114. elif hasattr(observer, method):
  115. return getattr(observer, method)()
  116. return None
  117. def get_weight_dtype(self):
  118. r"""
  119. Get weight's quantization dtype as the method from ``qconfig``.
  120. """
  121. return self._get_method_result(
  122. "get_quantized_dtype", self.weight_fake_quant, self.weight_observer
  123. )
  124. def get_activation_dtype(self):
  125. r"""
  126. Get activation's quantization dtype as the method from ``qconfig``.
  127. """
  128. return self._get_method_result(
  129. "get_quantized_dtype", self.act_fake_quant, self.act_observer
  130. )
  131. def get_weight_qparams(self):
  132. r"""
  133. Get weight's quantization parameters.
  134. """
  135. return self._get_method_result(
  136. "get_qparams", self.weight_fake_quant, self.weight_observer
  137. )
  138. def get_activation_qparams(self):
  139. r"""
  140. Get activation's quantization parameters.
  141. """
  142. return self._get_method_result(
  143. "get_qparams", self.act_fake_quant, self.act_observer
  144. )
  145. @classmethod
  146. @abstractmethod
  147. def from_float_module(cls, float_module: Module):
  148. r"""
  149. Return a :class:`~.QATModule` instance converted from
  150. a float :class:`~.Module` instance.
  151. """

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