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.py 3.4 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 typing import Tuple, Union
  9. import numpy as np
  10. from ... import module as Float
  11. from ...core.tensor import dtype
  12. from ...functional.nn import conv_bias_activation
  13. from ...tensor import Parameter
  14. from ..qat import conv as QAT
  15. from .module import QuantizedModule
  16. class Conv2d(Float.Conv2d, QuantizedModule):
  17. r"""Quantized version of :class:`~.qat.conv.Conv2d`."""
  18. r"""Applies a 2D convolution over a quantized input tensor, used for inference only.
  19. The parameter is same with :class: `~.Conv2d`.
  20. """
  21. def __init__(
  22. self,
  23. in_channels: int,
  24. out_channels: int,
  25. kernel_size: Union[int, Tuple[int, int]],
  26. stride: Union[int, Tuple[int, int]] = 1,
  27. padding: Union[int, Tuple[int, int]] = 0,
  28. dilation: Union[int, Tuple[int, int]] = 1,
  29. groups: int = 1,
  30. conv_mode: str = "CROSS_CORRELATION",
  31. compute_mode: str = "DEFAULT",
  32. dtype=None,
  33. ):
  34. super().__init__(
  35. in_channels,
  36. out_channels,
  37. kernel_size,
  38. stride,
  39. padding,
  40. dilation,
  41. groups,
  42. True,
  43. conv_mode,
  44. compute_mode,
  45. )
  46. self.output_dtype = dtype
  47. def calc_conv_quantized(self, inp, nonlinear_mode="IDENTITY"):
  48. inp_scale = dtype.get_scale(inp.dtype)
  49. w_scale = dtype.get_scale(self.weight.dtype)
  50. bias_scale = inp_scale * w_scale
  51. return conv_bias_activation(
  52. inp,
  53. self.weight,
  54. self.bias.astype(dtype.qint32(bias_scale)),
  55. self.output_dtype,
  56. self.stride,
  57. self.padding,
  58. self.dilation,
  59. self.groups,
  60. conv_mode=self.conv_mode,
  61. compute_mode=self.compute_mode,
  62. nonlinear_mode=nonlinear_mode,
  63. )
  64. @classmethod
  65. def from_qat_module(cls, qat_module: QAT.Conv2d):
  66. r"""
  67. return a :class:`~.QuantizedModule` instance converted from a
  68. :class:`~.QATModule` instance.
  69. """
  70. output_dtype = qat_module.get_activation_dtype()
  71. qconv = cls(
  72. qat_module.in_channels,
  73. qat_module.out_channels,
  74. qat_module.kernel_size,
  75. qat_module.stride,
  76. qat_module.padding,
  77. qat_module.dilation,
  78. qat_module.groups,
  79. dtype=output_dtype,
  80. )
  81. weight = qat_module.weight.astype(qat_module.get_weight_dtype())
  82. qconv.weight = Parameter(weight.numpy())
  83. if qat_module.bias is not None:
  84. qconv.bias = Parameter(qat_module.bias.numpy())
  85. else:
  86. qconv.bias = Parameter(
  87. np.zeros(qat_module._infer_bias_shape(), dtype=np.float32)
  88. )
  89. return qconv
  90. def forward(self, inp):
  91. return self.calc_conv_quantized(inp, nonlinear_mode="IDENTITY")
  92. class ConvRelu2d(Conv2d):
  93. r"""Quantized version of :class:`~.qat.conv.ConvRelu2d`."""
  94. def forward(self, inp):
  95. return self.calc_conv_quantized(inp, nonlinear_mode="RELU")

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