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.2 kB

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

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