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 6.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 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 ...functional.quantized import conv_transpose2d
  14. from ...tensor import Parameter
  15. from ..qat import conv as QAT
  16. from .module import QuantizedModule
  17. class Conv2d(Float.Conv2d, QuantizedModule):
  18. r"""Quantized version of :class:`~.qat.Conv2d`.
  19. Applies a 2D convolution over a quantized input tensor, used for inference only.
  20. The parameter is same with :class:`~.module.Conv2d`.
  21. """
  22. def __init__(
  23. self,
  24. in_channels: int,
  25. out_channels: int,
  26. kernel_size: Union[int, Tuple[int, int]],
  27. stride: Union[int, Tuple[int, int]] = 1,
  28. padding: Union[int, Tuple[int, int]] = 0,
  29. dilation: Union[int, Tuple[int, int]] = 1,
  30. groups: int = 1,
  31. conv_mode: str = "cross_correlation",
  32. compute_mode: str = "default",
  33. dtype=None,
  34. **kwargs
  35. ):
  36. super().__init__(
  37. in_channels,
  38. out_channels,
  39. kernel_size,
  40. stride,
  41. padding,
  42. dilation,
  43. groups,
  44. True,
  45. conv_mode,
  46. compute_mode,
  47. )
  48. self.output_dtype = dtype
  49. def calc_conv_quantized(self, inp, nonlinear_mode="identity"):
  50. inp_scale = dtype.get_scale(inp.dtype)
  51. w_scale = dtype.get_scale(self.weight.dtype)
  52. bias_scale = inp_scale * w_scale
  53. return conv_bias_activation(
  54. inp,
  55. self.weight,
  56. self.bias.astype(dtype.qint32(bias_scale)),
  57. self.output_dtype,
  58. self.stride,
  59. self.padding,
  60. self.dilation,
  61. self.groups,
  62. conv_mode=self.conv_mode,
  63. compute_mode=self.compute_mode,
  64. nonlinear_mode=nonlinear_mode,
  65. )
  66. @classmethod
  67. def from_qat_module(cls, qat_module: QAT.Conv2d):
  68. r"""
  69. return a :class:`~.QuantizedModule` instance converted from a
  70. :class:`~.QATModule` instance.
  71. """
  72. output_dtype = qat_module.get_activation_dtype()
  73. qconv = cls(
  74. qat_module.in_channels,
  75. qat_module.out_channels,
  76. qat_module.kernel_size,
  77. qat_module.stride,
  78. qat_module.padding,
  79. qat_module.dilation,
  80. qat_module.groups,
  81. dtype=output_dtype,
  82. name=qat_module.name,
  83. )
  84. weight = qat_module.weight.astype(qat_module.get_weight_dtype())
  85. qconv.weight = Parameter(weight.numpy(), name=qat_module.weight.name)
  86. if qat_module.bias is not None:
  87. qconv.bias = Parameter(qat_module.bias.numpy(), name=qat_module.bias.name)
  88. else:
  89. qconv.bias = Parameter(
  90. np.zeros(qat_module._infer_bias_shape(), dtype=np.float32)
  91. )
  92. return qconv
  93. def forward(self, inp):
  94. return self.calc_conv_quantized(inp, nonlinear_mode="identity")
  95. class ConvRelu2d(Conv2d):
  96. r"""Quantized version of :class:`~.qat.ConvRelu2d`."""
  97. def forward(self, inp):
  98. return self.calc_conv_quantized(inp, nonlinear_mode="relu")
  99. class ConvTranspose2d(Float.ConvTranspose2d, QuantizedModule):
  100. r"""Quantized version of :class:`~.qat.ConvTranspose2d`.
  101. Applies a 2D transposed convolution over a quantized input tensor, used
  102. for inference only.
  103. The parameter is same with :class:`~.module.ConvTranspose2d` but dtype.
  104. :param dtype: data type of the output, should be qint8.
  105. """
  106. def __init__(
  107. self,
  108. in_channels: int,
  109. out_channels: int,
  110. kernel_size: Union[int, Tuple[int, int]],
  111. stride: Union[int, Tuple[int, int]] = 1,
  112. padding: Union[int, Tuple[int, int]] = 0,
  113. dilation: Union[int, Tuple[int, int]] = 1,
  114. groups: int = 1,
  115. bias: bool = True,
  116. conv_mode: str = "cross_correlation",
  117. compute_mode: str = "default",
  118. dtype=None,
  119. **kwargs
  120. ):
  121. super().__init__(
  122. in_channels=in_channels,
  123. out_channels=out_channels,
  124. kernel_size=kernel_size,
  125. stride=stride,
  126. padding=padding,
  127. dilation=dilation,
  128. groups=groups,
  129. bias=bias,
  130. conv_mode=conv_mode,
  131. compute_mode=compute_mode,
  132. )
  133. self.output_dtype = dtype
  134. @classmethod
  135. def from_qat_module(cls, qat_module: QAT.ConvTranspose2d):
  136. r"""
  137. return a :class:`~.QuantizedModule` instance converted from a
  138. :class:`~.QATModule` instance.
  139. """
  140. output_dtype = qat_module.get_activation_dtype()
  141. qconv = cls(
  142. qat_module.in_channels,
  143. qat_module.out_channels,
  144. qat_module.kernel_size,
  145. qat_module.stride,
  146. qat_module.padding,
  147. qat_module.dilation,
  148. qat_module.groups,
  149. qat_module.bias is not None,
  150. qat_module.conv_mode,
  151. qat_module.compute_mode,
  152. dtype=output_dtype,
  153. name=qat_module.name,
  154. )
  155. weight = qat_module.weight.astype(qat_module.get_weight_dtype())
  156. qconv.weight = Parameter(weight.numpy(), name=qat_module.weight.name)
  157. qconv.bias = (
  158. Parameter(qat_module.bias.numpy(), name=qat_module.bias.name)
  159. if qat_module.bias is not None
  160. else None
  161. )
  162. return qconv
  163. def calc_conv_transpose2d_quantized(self, inp):
  164. if self.bias is not None:
  165. inp_scale = dtype.get_scale(inp.dtype)
  166. w_scale = dtype.get_scale(self.weight.dtype)
  167. bias_scale = inp_scale * w_scale
  168. return conv_transpose2d(
  169. inp=inp,
  170. weight=self.weight,
  171. bias=self.bias.astype(dtype.qint32(bias_scale))
  172. if self.bias is not None
  173. else None,
  174. dtype=self.output_dtype,
  175. stride=self.stride,
  176. padding=self.padding,
  177. dilation=self.dilation,
  178. groups=self.groups,
  179. conv_mode=self.conv_mode,
  180. compute_mode=self.compute_mode,
  181. )
  182. def forward(self, inp):
  183. return self.calc_conv_transpose2d_quantized(inp)

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