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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from copy import deepcopy
  2. from typing import Union
  3. from ...core.tensor.dtype import QuantDtypeMeta
  4. from ...quantization.fake_quant import QParamsModuleMixin, _FakeQuantize
  5. from ...quantization.utils import QParams, QuantMode, fake_quant_tensor
  6. class FakeQuantize(_FakeQuantize, QParamsModuleMixin):
  7. def __init__(
  8. self, dtype: Union[str, QuantDtypeMeta], enable: bool = True, **kwargs
  9. ):
  10. super().__init__(dtype, enable, **kwargs)
  11. self.qparams = None
  12. def fake_quant_forward(self, inp, qparams: QParams = None):
  13. if qparams is None:
  14. qparams = self.get_qparams()
  15. assert (
  16. qparams.dtype_meta is self.dtype
  17. ), "input qparams' dtype is not equal to self.dtype.\nqparams.dtype_meta={}\nself.dtype={}".format(
  18. qparams.dtype_meta, self.dtype
  19. )
  20. return fake_quant_tensor(inp, qparams)
  21. def get_qparams(self):
  22. return self.qparams
  23. def set_qparams(self, qparams: QParams):
  24. """
  25. :param qparams: used to set initial scale.
  26. """
  27. if qparams.scale is None:
  28. raise AssertionError("Can not get an initialized scale")
  29. scale = qparams.scale
  30. if qparams.dtype_meta is None:
  31. qparams.dtype_meta = self.dtype
  32. else:
  33. assert (
  34. qparams.dtype_meta is self.dtype
  35. ), "input qparams' dtype is not equal to self.dtype.\nqparams.dtype_meta={}\nself.dtype={}".format(
  36. qparams.dtype_meta, self.dtype
  37. )
  38. dtype_meta = qparams.dtype_meta
  39. zero_point = qparams.zero_point
  40. mode = qparams.mode
  41. self.qparams = QParams(mode, dtype_meta, scale, zero_point)

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