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.

utils.py 3.6 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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 enum import Enum
  9. from functools import partial, update_wrapper, wraps
  10. from typing import Dict
  11. from .. import functional as F
  12. from ..core.tensor.dtype import _metadata_dict
  13. from ..core.tensor.function import Function
  14. from ..tensor import Tensor
  15. class Round(Function):
  16. """
  17. The functional round have no grad and can not use for quantization-aware-training.
  18. We use Function and STE(Straight-Through Estimator) to implement backward propagation.
  19. """
  20. def forward(self, x):
  21. return F.round(x)
  22. def backward(self, output_grads):
  23. return output_grads
  24. def register_method_to_class(cls):
  25. def decorator(func):
  26. @wraps(func)
  27. def wrapper(self, *args, **kwargs):
  28. return func(self, *args, **kwargs)
  29. if isinstance(func, partial):
  30. update_wrapper(func, func.func)
  31. setattr(cls, func.__name__, wrapper)
  32. return func
  33. return decorator
  34. class QuantMode(Enum):
  35. """Quantization mode enumerate class.
  36. """
  37. SYMMERTIC = 1
  38. ASYMMERTIC = 2
  39. TQT = 3
  40. qparam_dict = {
  41. QuantMode.SYMMERTIC: {"mode": QuantMode.SYMMERTIC, "scale": None,},
  42. QuantMode.ASYMMERTIC: {
  43. "mode": QuantMode.ASYMMERTIC,
  44. "scale": None,
  45. "zero_point": None,
  46. },
  47. QuantMode.TQT: {"mode": QuantMode.TQT, "scale": None,},
  48. }
  49. def get_qparam_dict(mode: QuantMode):
  50. """Return the quantization parameters dictionary according to the mode.
  51. """
  52. return qparam_dict.get(mode, None)
  53. def fake_quant_tensor(inp: Tensor, qmin: int, qmax: int, q_dict: Dict) -> Tensor:
  54. """Apply fake quantization to the inp tensor.
  55. :param inp: the input tensor which need to be faked.
  56. :param qmin: the minimum value which the integer limit to.
  57. :param qmax: the maximum value which the integer limit to.
  58. :param q_dict: the quantization parameter dict.
  59. """
  60. scale = q_dict["scale"]
  61. zero_point = 0
  62. if q_dict["mode"] == QuantMode.ASYMMERTIC:
  63. zero_point = q_dict["zero_point"]
  64. # Quant
  65. oup = Round()(inp / scale) + zero_point
  66. # Clip
  67. oup = F.minimum(F.maximum(oup, qmin), qmax)
  68. # Dequant
  69. oup = (oup - zero_point) * scale
  70. return oup
  71. def fake_quant_bias(bias: Tensor, inp: Tensor, w_qat: Tensor) -> Tensor:
  72. """Apply fake quantization to bias, with the special scale from input tensor
  73. and weight tensor, the quantized type set to qint32 also.
  74. :param bias: the bias tensor which need to be faked.
  75. :param inp: the input tensor which contain the quantization parameters.
  76. :param qmax: the weight tensor which contain the quantization parameters.
  77. .. warning::
  78. Only work for symmetric quantization method now.
  79. """
  80. b_qat = bias
  81. if hasattr(inp, "q_dict") and b_qat is not None:
  82. if inp.q_dict["scale"] is not None and w_qat.q_dict["scale"] is not None:
  83. # use the same mode with weight.
  84. b_dict = get_qparam_dict(w_qat.q_dict["mode"])
  85. b_dict["scale"] = inp.q_dict["scale"] * w_qat.q_dict["scale"]
  86. # TODO: add zero_point for ASYMMERTIC mode.
  87. qmax = _metadata_dict["qint32"].qmax
  88. qmin = _metadata_dict["qint32"].qmin
  89. b_qat = fake_quant_tensor(b_qat, qmin, qmax, b_dict)
  90. return b_qat

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