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.

conv_bn.py 2.1 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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 ...tensor import Parameter
  9. from ..qat import conv_bn as QAT
  10. from .conv import Conv2d
  11. class _ConvBnActivation2d(Conv2d):
  12. r"""
  13. Applies a 2D convolution over a quantized input tensor, used for inference only.
  14. The parameter is same with :class: `~.module.Conv2d`.
  15. """
  16. @classmethod
  17. def from_qat_module(cls, qat_module: QAT._ConvBnActivation2d):
  18. r"""
  19. Return a :class:`~.QuantizedModule` instance converted from a
  20. :class:`~.QATModule` instance.
  21. """
  22. output_dtype = qat_module.get_activation_dtype()
  23. qconv = cls(
  24. qat_module.conv.in_channels,
  25. qat_module.conv.out_channels,
  26. qat_module.conv.kernel_size,
  27. qat_module.conv.stride,
  28. qat_module.conv.padding,
  29. qat_module.conv.dilation,
  30. qat_module.conv.groups,
  31. dtype=output_dtype,
  32. name=qat_module.name,
  33. )
  34. w_fold, b_fold = qat_module.fold_weight_bias(
  35. qat_module.bn.running_mean, qat_module.bn.running_var
  36. )
  37. weight = w_fold.astype(qat_module.get_weight_dtype())
  38. qconv.weight = Parameter(weight.numpy(), name=qat_module.conv.weight.name)
  39. qconv.bias = Parameter(b_fold.numpy())
  40. if qat_module.conv.bias is not None:
  41. qconv.bias.name = qat_module.conv.bias.name
  42. return qconv
  43. class ConvBn2d(_ConvBnActivation2d):
  44. r"""Quantized version of :class:`~.qat.ConvBn2d`."""
  45. def forward(self, inp):
  46. return self.calc_conv_quantized(inp, nonlinear_mode="identity")
  47. class ConvBnRelu2d(_ConvBnActivation2d):
  48. r"""Quantized version of :class:`~.qat.ConvBnRelu2d`."""
  49. def forward(self, inp):
  50. return self.calc_conv_quantized(inp, nonlinear_mode="relu")

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