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

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