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.

fake_quant.py 5.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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. import copy
  9. import math
  10. import numpy as np
  11. from .. import functional as F
  12. from .._internal.dtype import _metadata_dict, get_quantized_dtype
  13. from ..core import Buffer, Function, Parameter
  14. from ..jit import sideeffect
  15. from ..module import Module
  16. from .observer import ObserverMode, Round
  17. class _FakeQuantize(Module):
  18. def __init__(self, dtype: str, narrow_range: bool = False, enable: bool = True):
  19. super().__init__()
  20. if not dtype in _metadata_dict.keys():
  21. raise ValueError(
  22. "unknown dtype: {}, only support {}".format(
  23. dtype, _metadata_dict.keys()
  24. )
  25. )
  26. self.dtype = dtype
  27. self.narrow_range = narrow_range
  28. self.qmin = (
  29. -_metadata_dict[dtype].qmax if narrow_range else _metadata_dict[dtype].qmin
  30. )
  31. self.qmax = _metadata_dict[dtype].qmax
  32. self.enabled = enable
  33. def enable(self):
  34. self.enabled = True
  35. def disable(self):
  36. self.enabled = False
  37. def fake_quant_forward(self, inp, q_dict):
  38. return inp
  39. def normal_foward(self, inp, q_dict):
  40. return inp
  41. def forward(self, inp, q_dict):
  42. if self.enabled:
  43. return self.fake_quant_forward(inp, q_dict)
  44. else:
  45. return self.normal_foward(inp, q_dict)
  46. class TQT_Function(Function):
  47. def __init__(self, lowerbound, upperbound):
  48. super().__init__()
  49. self.lowerbound = lowerbound
  50. self.upperbound = upperbound
  51. def forward(self, inp, scale):
  52. t = 2 ** scale
  53. # t = F.maximum(t, 1e-4)
  54. inp_scaled = inp / t
  55. inp_clipped = F.maximum(F.minimum(inp_scaled, self.upperbound), self.lowerbound)
  56. inp_rounded = F.round(inp_clipped)
  57. inp_flq = inp_rounded * t
  58. self.save_for_backward(inp_scaled, inp_rounded, t)
  59. return inp_flq
  60. def backward(self, grad_inp_flq):
  61. (inp_scaled, inp_rounded, t) = self.saved_tensors
  62. mask_clip = (inp_scaled < -0.5 + self.lowerbound) + (
  63. inp_scaled > self.upperbound + 0.5
  64. ) # mask for accumulating the gradients of |data_scaled|>L
  65. mask_quant = F.abs(
  66. mask_clip - 1
  67. ) # mask for accumulating the gradients with |data_scaled|<=L
  68. grad_quant = (
  69. grad_inp_flq * mask_quant * (inp_rounded - inp_scaled)
  70. ) # gradient within |data_scaled|<=L
  71. grad_clip = (
  72. grad_inp_flq * mask_clip * inp_rounded
  73. ) # gradient with | data_scaled|>L
  74. grad_s = grad_clip.sum() + grad_quant.sum()
  75. # dL/ds = dL/dt * t * ln(2)
  76. grad_s = grad_s * t * math.log(2)
  77. grad_inp = grad_inp_flq * mask_quant
  78. return grad_inp, grad_s
  79. class TQT(_FakeQuantize):
  80. """
  81. TQT: https://arxiv.org/abs/1903.08066 Trained Quantization Thresholds
  82. for Accurate and Efficient Fixed-Point Inference of Deep Neural Networks
  83. """
  84. def __init__(self, dtype: str, narrow_range: bool = False, enable: bool = True):
  85. super().__init__(dtype, narrow_range, enable)
  86. self.scale = Parameter(0.0, dtype=np.float32)
  87. def fake_quant_forward(self, inp, q_dict):
  88. # when enable, TQT will do fakequant forward, finetune the scale
  89. return TQT_Function(self.qmin, self.qmax)(inp, self.scale)
  90. def normal_foward(self, inp, q_dict):
  91. # when disable, TQT will do normal forward, initialize scale weight
  92. tmp_scale = F.maximum(F.abs(q_dict["min_val"]), F.abs(q_dict["max_val"]))
  93. tmp_scale = F.log(tmp_scale / 127) / F.log(2)
  94. F.add_update(self.scale, tmp_scale, alpha=0.0, beta=1.0, bias=0.0)
  95. return inp
  96. def get_dtype(self):
  97. return get_quantized_dtype(self.dtype, 2 ** self.scale.numpy()[0], None)
  98. class FakeQuantize(_FakeQuantize):
  99. r"""
  100. A module to do quant and dequant according to observer's scale and zero_point.
  101. :param dtype: A string indicating the target quantization type of input.
  102. :param narrow_range: Whether the absolute value of ``qmin`` is the same as ``qmax``,
  103. instead of 1 greater. Usually True for weight and False for activation.
  104. :param enable: Whether do ``normal_forward`` or ``fake_quant_forward``.
  105. """
  106. def fake_quant_forward(self, inp, q_dict):
  107. if q_dict["mode"] == ObserverMode.SYMMERTIC:
  108. scale = q_dict["scale"]
  109. # Quant
  110. oup = Round()(inp / scale)
  111. # clip
  112. oup = F.minimum(F.maximum(oup, self.qmin), self.qmax)
  113. # DeQuant
  114. oup = (oup) * scale
  115. return oup
  116. else:
  117. scale = q_dict["scale"]
  118. zero_point = q_dict["zero_point"]
  119. # Quant
  120. oup = Round()(inp / scale) + zero_point
  121. # clip
  122. oup = F.minimum(F.maximum(oup, self.qmin), self.qmax)
  123. # DeQuant
  124. oup = (oup - zero_point) * scale
  125. return oup

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