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.

elemwise.py 2.3 kB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 ... import _internal as mgb
  9. from ... import module as Float
  10. from ...core import Tensor, wrap_io_tensor
  11. from ...core.graph import _use_default_if_none
  12. from ...quantization.utils import register_method_to_class
  13. from ..module import Module
  14. @wrap_io_tensor
  15. def _elemwise_multi_type(mode, *inputs, **kwargs) -> Tensor:
  16. if all(isinstance(i, (int, float)) for i in inputs):
  17. device, comp_graph = _use_default_if_none(None, None)
  18. ret = mgb.opr.elemwise_multi_type(
  19. *inputs, mode=mode, comp_node=device, comp_graph=comp_graph, **kwargs,
  20. )
  21. return ret.inferred_value[0]
  22. return mgb.opr.elemwise_multi_type(*inputs, mode=mode, **kwargs)
  23. class Elemwise(Module):
  24. r"""
  25. quantized module for elemwise operator, inference only.
  26. :param method: the elemwise method, supported string refer to :class:`~.module.elemwise.Elemwise`.
  27. it will do quantized operator with specified output quantized dtype.
  28. """
  29. _elemwise_multi_type_mode = mgb.opr_param_defs.ElemwiseMultiType.Mode
  30. def __init__(self, method):
  31. super().__init__()
  32. self.method = self._elemwise_multi_type_mode.convert("Q" + method)
  33. self.scale = 1.0
  34. self.zero_point = 0.0
  35. self.output_dtype = mgb.dtype.qint8(self.scale)
  36. def forward(self, *inps):
  37. if self.training:
  38. raise ValueError("quantized module only support inference.")
  39. return _elemwise_multi_type(self.method, *inps, dtype=self.output_dtype)
  40. @register_method_to_class(Float.Elemwise)
  41. def to_quantized(float_module):
  42. r"""
  43. Replace :class:`~.module.QATModule`'s ``to_quantized`` method.
  44. implemented here to avoid circular import.
  45. """
  46. qmod = Elemwise(float_module.method.name)
  47. qmod.output_dtype = float_module.act_observer.get_dtype()
  48. qmod.scale, qmod.zero_point = float_module.act_observer.get_qparams()
  49. return qmod

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