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.

quantized.py 7.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. # pylint: disable=too-many-lines
  9. from typing import Tuple, Union
  10. from ..core import _config
  11. from ..core._imperative_rt.core2 import apply
  12. from ..core.ops import builtin
  13. from ..tensor import Tensor
  14. from ..utils.tuple_function import _pair, _pair_nonzero
  15. from .debug_param import get_execution_strategy
  16. def conv_bias_activation(
  17. inp: Tensor,
  18. weight: Tensor,
  19. bias: Tensor,
  20. dtype=None,
  21. stride: Union[int, Tuple[int, int]] = 1,
  22. padding: Union[int, Tuple[int, int]] = 0,
  23. dilation: Union[int, Tuple[int, int]] = 1,
  24. groups: int = 1,
  25. nonlinear_mode="identity",
  26. conv_mode="cross_correlation",
  27. compute_mode="default",
  28. ) -> Tensor:
  29. r"""Convolution bias with activation operation, only for inference.
  30. Args:
  31. inp: feature map of the convolution operation.
  32. weight: convolution kernel.
  33. bias: bias added to the result of convolution
  34. stride: stride of the 2D convolution operation. Default: 1
  35. padding: size of the paddings added to the input on both sides
  36. of its spatial dimensions. Only zero-padding is supported. Default: 0
  37. dilation: dilation of the 2D convolution operation. Default: 1
  38. groups: number of groups into which the input and output channels are divided,
  39. so as to perform a "grouped convolution". When ``groups`` is not 1,
  40. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  41. and the shape of weight should be `(groups, out_channel // groups,
  42. in_channels // groups, height, width)`.
  43. conv_mode: supports 'cross_correlation' or 'convolution'. Default:
  44. 'cross_correlation'
  45. dtype: support for ``np.dtype``, Default: np.int8
  46. compute_mode: when set to "default", no special requirements will be
  47. placed on the precision of intermediate results. When set to "float32",
  48. "float32" would be used for accumulator and intermediate result,
  49. but only effective when input and output are of float16 dtype.
  50. """
  51. ph, pw = _pair(padding)
  52. sh, sw = _pair_nonzero(stride)
  53. dh, dw = _pair_nonzero(dilation)
  54. sparse_type = "dense" if groups == 1 else "group"
  55. compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
  56. conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)
  57. op = builtin.ConvBias(
  58. stride_h=sh,
  59. stride_w=sw,
  60. pad_h=ph,
  61. pad_w=pw,
  62. dilate_h=dh,
  63. dilate_w=dw,
  64. dtype=dtype,
  65. format=conv_format,
  66. strategy=get_execution_strategy(),
  67. nonlineMode=nonlinear_mode,
  68. mode=conv_mode,
  69. compute_mode=compute_mode,
  70. sparse=sparse_type,
  71. )
  72. (outputs,) = apply(op, inp, weight, bias)
  73. return outputs
  74. def batch_conv_bias_activation(
  75. inp: Tensor,
  76. weight: Tensor,
  77. bias: Tensor,
  78. dtype=None,
  79. stride: Union[int, Tuple[int, int]] = 1,
  80. padding: Union[int, Tuple[int, int]] = 0,
  81. dilation: Union[int, Tuple[int, int]] = 1,
  82. groups: int = 1,
  83. nonlinear_mode="identity",
  84. conv_mode="cross_correlation",
  85. compute_mode="default",
  86. ) -> Tensor:
  87. r"""Batch convolution bias with activation operation, only for inference.
  88. Args:
  89. inp: feature map of the convolution operation.
  90. weight: convolution kernel in batched way.
  91. bias: bias added to the result of convolution
  92. stride: stride of the 2D convolution operation. Default: 1
  93. padding: size of the paddings added to the input on both sides
  94. of its spatial dimensions. Only zero-padding is supported. Default: 0
  95. dilation: dilation of the 2D convolution operation. Default: 1
  96. groups: number of groups into which the input and output channels are divided,
  97. so as to perform a "grouped convolution". When ``groups`` is not 1,
  98. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  99. and the shape of weight should be `(groups, out_channel // groups,
  100. in_channels // groups, height, width)`.
  101. conv_mode: supports 'cross_correlation' or 'convolution'. Default:
  102. 'cross_correlation'
  103. dtype: support for ``np.dtype``, Default: np.int8
  104. compute_mode: when set to "default", no special requirements will be
  105. placed on the precision of intermediate results. When set to "float32",
  106. "float32" would be used for accumulator and intermediate result,
  107. but only effective when input and output are of float16 dtype.
  108. """
  109. ph, pw = _pair(padding)
  110. sh, sw = _pair_nonzero(stride)
  111. dh, dw = _pair_nonzero(dilation)
  112. sparse_type = "dense" if groups == 1 else "group"
  113. compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
  114. conv_format = _config._get_actual_op_param("NCHW", _config.__conv_format)
  115. op = builtin.BatchConvBias(
  116. stride_h=sh,
  117. stride_w=sw,
  118. pad_h=ph,
  119. pad_w=pw,
  120. dilate_h=dh,
  121. dilate_w=dw,
  122. dtype=dtype,
  123. format=conv_format,
  124. strategy=get_execution_strategy(),
  125. nonlineMode=nonlinear_mode,
  126. mode=conv_mode,
  127. compute_mode=compute_mode,
  128. sparse=sparse_type,
  129. )
  130. (outputs,) = apply(op, inp, weight, bias)
  131. return outputs
  132. def conv_transpose2d(
  133. inp: Tensor,
  134. weight: Tensor,
  135. bias: Tensor = None,
  136. dtype=None,
  137. stride: Union[int, Tuple[int, int]] = 1,
  138. padding: Union[int, Tuple[int, int]] = 0,
  139. dilation: Union[int, Tuple[int, int]] = 1,
  140. groups: int = 1,
  141. conv_mode="cross_correlation",
  142. compute_mode="default",
  143. ) -> Tensor:
  144. assert (
  145. conv_mode.lower() == "cross_correlation"
  146. or conv_mode.name == "CROSS_CORRELATION"
  147. )
  148. assert compute_mode.lower() == "default" or compute_mode.name == "DEFAULT"
  149. if groups != 1:
  150. raise NotImplementedError(
  151. "group quantized transposed conv2d is not supported yet."
  152. )
  153. if bias is not None:
  154. raise NotImplementedError(
  155. "bias of quantized transposed conv2d is not supported yet."
  156. )
  157. pad_h, pad_w = _pair(padding)
  158. stride_h, stride_w = _pair_nonzero(stride)
  159. dilate_h, dilate_w = _pair_nonzero(dilation)
  160. compute_mode = _config._get_actual_op_param(compute_mode, _config.__compute_mode)
  161. # should be replaced by Op with bias such as ConvolutionBackwardDataBias
  162. op = builtin.ConvolutionBackwardData(
  163. stride_h=stride_h,
  164. stride_w=stride_w,
  165. pad_h=pad_h,
  166. pad_w=pad_w,
  167. dilate_h=dilate_h,
  168. dilate_w=dilate_w,
  169. strategy=get_execution_strategy(),
  170. dtype=dtype,
  171. compute_mode=compute_mode,
  172. mode=conv_mode,
  173. )
  174. (output,) = apply(op, weight, inp)
  175. return output

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