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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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. """
  36. Quantization mode enumerate class.
  37. """
  38. SYMMERTIC = 1
  39. ASYMMERTIC = 2
  40. TQT = 3
  41. qparam_dict = {
  42. QuantMode.SYMMERTIC: {"mode": QuantMode.SYMMERTIC, "scale": None,},
  43. QuantMode.ASYMMERTIC: {
  44. "mode": QuantMode.ASYMMERTIC,
  45. "scale": None,
  46. "zero_point": None,
  47. },
  48. QuantMode.TQT: {"mode": QuantMode.TQT, "scale": None,},
  49. }
  50. def get_qparam_dict(mode: QuantMode):
  51. """
  52. Return the quantization parameters dictionary according to the mode.
  53. """
  54. return qparam_dict.get(mode, None)
  55. def fake_quant_tensor(inp: Tensor, qmin: int, qmax: int, q_dict: Dict) -> Tensor:
  56. """
  57. Apply fake quantization to the inp tensor.
  58. :param inp: the input tensor which need to be faked.
  59. :param qmin: the minimum value which the integer limit to.
  60. :param qmax: the maximum value which the integer limit to.
  61. :param q_dict: the quantization parameter dict.
  62. """
  63. scale = q_dict["scale"]
  64. zero_point = 0
  65. if q_dict["mode"] == QuantMode.ASYMMERTIC:
  66. zero_point = q_dict["zero_point"]
  67. # Quant
  68. oup = Round()(inp / scale) + zero_point
  69. # Clip
  70. oup = F.minimum(F.maximum(oup, qmin), qmax)
  71. # Dequant
  72. oup = (oup - zero_point) * scale
  73. return oup
  74. def fake_quant_bias(bias: Tensor, inp: Tensor, w_qat: Tensor) -> Tensor:
  75. """
  76. Apply fake quantization to bias, with the special scale from input tensor
  77. and weight tensor, the quantized type set to qint32 also.
  78. :param bias: the bias tensor which need to be faked.
  79. :param inp: the input tensor which contain the quantization parameters.
  80. :param qmax: the weight tensor which contain the quantization parameters.
  81. .. warning::
  82. Only work for symmetric quantization method now.
  83. """
  84. b_qat = bias
  85. if hasattr(inp, "q_dict") and b_qat is not None:
  86. if inp.q_dict["scale"] is not None and w_qat.q_dict["scale"] is not None:
  87. # use the same mode with weight.
  88. b_dict = get_qparam_dict(w_qat.q_dict["mode"])
  89. b_dict["scale"] = inp.q_dict["scale"] * w_qat.q_dict["scale"]
  90. # TODO: add zero_point for ASYMMERTIC mode.
  91. qmax = _metadata_dict["qint32"].qmax
  92. qmin = _metadata_dict["qint32"].qmin
  93. b_qat = fake_quant_tensor(b_qat, qmin, qmax, b_dict)
  94. return b_qat

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