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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. """
  32. :param qparams: used to set initial scale.
  33. """
  34. if qparams.scale is None:
  35. raise AssertionError("Can not get an initialized scale")
  36. scale = qparams.scale
  37. if qparams.dtype_meta is None:
  38. qparams.dtype_meta = self.dtype
  39. else:
  40. assert (
  41. qparams.dtype_meta is self.dtype
  42. ), "input qparams' dtype is not equal to self.dtype.\nqparams.dtype_meta={}\nself.dtype={}".format(
  43. qparams.dtype_meta, self.dtype
  44. )
  45. dtype_meta = qparams.dtype_meta
  46. zero_point = qparams.zero_point
  47. mode = qparams.mode
  48. self.qparams = QParams(mode, dtype_meta, scale, zero_point)

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