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

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

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