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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141
  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 ...core import Tensor
  10. from ...quantization import FakeQuantize, Observer, QConfig
  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:
  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. if observer is None:
  58. return target
  59. oup = observer(target)
  60. if fake_quant is None:
  61. return oup
  62. else:
  63. q_dict = observer.get_qparams()
  64. return fake_quant(oup, q_dict)
  65. def apply_quant_weight(self, target: Tensor):
  66. r"""
  67. Apply weight's observer and fake_quant from ``qconfig`` on ``target``.
  68. """
  69. return self._apply_fakequant_with_observer(
  70. target, self.weight_fake_quant, self.weight_observer
  71. )
  72. def apply_quant_activation(self, target: Tensor):
  73. r"""
  74. Apply weight's observer and fake_quant from ``qconfig`` on ``target``.
  75. """
  76. return self._apply_fakequant_with_observer(
  77. target, self.act_fake_quant, self.act_observer
  78. )
  79. def get_weight_dtype(self):
  80. r"""
  81. Get weight's quantization dtype as the method from ``qconfig``.
  82. """
  83. if hasattr(self.weight_fake_quant, "get_dtype"):
  84. return self.weight_fake_quant.get_dtype()
  85. else:
  86. return self.weight_observer.get_dtype()
  87. def get_activation_dtype(self):
  88. r"""
  89. Get activation's quantization dtype as the method from ``qconfig``.
  90. """
  91. if hasattr(self.act_fake_quant, "get_dtype"):
  92. return self.act_fake_quant.get_dtype()
  93. else:
  94. return self.act_observer.get_dtype()
  95. def _get_qparams(self, fake_quant: FakeQuantize, observer: Observer):
  96. if hasattr(fake_quant, "get_qparams"):
  97. return fake_quant.get_qparams()
  98. elif observer is not None:
  99. return observer.get_qparams()
  100. return None
  101. def get_weight_qparams(self):
  102. r"""
  103. Get weight's quantization parameters.
  104. """
  105. return self._get_qparams(self.weight_fake_quant, self.weight_observer)
  106. def get_activation_qparams(self):
  107. r"""
  108. Get activation's quantization parameters.
  109. """
  110. return self._get_qparams(self.act_fake_quant, self.act_observer)
  111. @classmethod
  112. @abstractmethod
  113. def from_float_module(cls, float_module: Module):
  114. r"""
  115. Return a :class:`~.QATModule` instance converted from
  116. a float :class:`~.Module` instance.
  117. """

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