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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
  2. #
  3. # Copyright (c) 2014-2021 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 copy import deepcopy
  9. from typing import Union
  10. from ..core.tensor.dtype import QuantDtypeMeta
  11. from ..quantization.fake_quant import QParamsModuleMixin, _FakeQuantize
  12. from ..quantization.utils import QParams, QuantMode, fake_quant_tensor
  13. class FakeQuantize(_FakeQuantize, QParamsModuleMixin):
  14. def __init__(
  15. self, dtype: Union[str, QuantDtypeMeta], enable: bool = True, **kwargs
  16. ):
  17. super().__init__(dtype, enable, **kwargs)
  18. self.qparams = None
  19. def fake_quant_forward(self, inp, qparams: QParams = None):
  20. if qparams is None:
  21. qparams = self.get_qparams()
  22. assert (
  23. qparams.dtype_meta is self.dtype
  24. ), "input qparams' dtype is not equal to self.dtype.\nqparams.dtype_meta={}\nself.dtype={}".format(
  25. qparams.dtype_meta, self.dtype
  26. )
  27. return fake_quant_tensor(inp, qparams)
  28. def get_qparams(self):
  29. return self.qparams
  30. def set_qparams(self, qparams: QParams):
  31. r"""
  32. Args:
  33. qparams: used to set initial scale.
  34. """
  35. if qparams.scale is None:
  36. raise AssertionError("Can not get an initialized scale")
  37. scale = qparams.scale
  38. if qparams.dtype_meta is None:
  39. qparams.dtype_meta = self.dtype
  40. else:
  41. assert (
  42. qparams.dtype_meta is self.dtype
  43. ), "input qparams' dtype is not equal to self.dtype.\nqparams.dtype_meta={}\nself.dtype={}".format(
  44. qparams.dtype_meta, self.dtype
  45. )
  46. dtype_meta = qparams.dtype_meta
  47. zero_point = qparams.zero_point
  48. mode = qparams.mode
  49. self.qparams = QParams(mode, dtype_meta, scale, zero_point)

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