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.0 kB

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

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