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

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

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