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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 abc import abstractmethod
  9. from typing import Tuple, Union
  10. import numpy as np
  11. import megengine._internal as mgb
  12. from .. import functional as F
  13. from ..core import Parameter
  14. from ..utils.types import _pair, _pair_nonzero
  15. from . import init
  16. from .module import Module
  17. class _ConvNd(Module):
  18. """base class for convolution modules, including transposed conv"""
  19. def __init__(
  20. self,
  21. in_channels: int,
  22. out_channels: int,
  23. kernel_size: Union[int, Tuple[int, int]],
  24. stride: Union[int, Tuple[int, int]],
  25. padding: Union[int, Tuple[int, int]],
  26. dilation: Union[int, Tuple[int, int]],
  27. groups: int,
  28. bias: bool = True,
  29. ):
  30. super().__init__()
  31. if in_channels % groups != 0:
  32. raise ValueError("in_channels must be divisible by groups")
  33. if out_channels % groups != 0:
  34. raise ValueError("out_channels must be divisible by groups")
  35. self.in_channels = in_channels
  36. self.out_channels = out_channels
  37. self.kernel_size = kernel_size
  38. self.stride = stride
  39. self.padding = padding
  40. self.dilation = dilation
  41. self.groups = groups
  42. self.weight = Parameter(np.zeros(self._infer_weight_shape(), dtype=np.float32))
  43. self.bias = None
  44. if bias:
  45. self.bias = Parameter(np.zeros(self._infer_bias_shape(), dtype=np.float32))
  46. self.reset_parameters()
  47. @abstractmethod
  48. def _get_fanin(self):
  49. pass
  50. def reset_parameters(self) -> None:
  51. fanin = self._get_fanin()
  52. std = np.sqrt(1 / fanin)
  53. init.normal_(self.weight, 0.0, std)
  54. if self.bias is not None:
  55. init.zeros_(self.bias)
  56. @abstractmethod
  57. def _infer_weight_shape(self):
  58. pass
  59. @abstractmethod
  60. def _infer_bias_shape(self):
  61. pass
  62. class Conv2d(_ConvNd):
  63. r"""Applies a 2D convolution over an input tensor.
  64. For instance, given an input of the size :math:`(N, C_{\text{in}}, H, W)`,
  65. this layer generates an output of the size
  66. :math:`(N, C_{\text{out}}, H_{\text{out}}, W_{\text{out}})` through the
  67. process described as below:
  68. .. math::
  69. \text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) +
  70. \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)
  71. where :math:`\star` is the valid 2D cross-correlation operator,
  72. :math:`N` is a batch size, :math:`C` denotes a number of channels,
  73. :math:`H` is a height of input planes in pixels, and :math:`W` is
  74. width in pixels.
  75. When ``groups == in_channels`` and ``out_channels == K * in_channels``,
  76. where `K` is a positive integer, this operation is also known as depthwise
  77. convolution.
  78. In other words, for an input of size :math:`(N, C_{in}, H_{in}, W_{in})`,
  79. a depthwise convolution with a depthwise multiplier `K`, can be constructed
  80. by arguments :math:`(in\_channels=C_{in}, out\_channels=C_{in} \times K, ..., groups=C_{in})`.
  81. :param in_channels: number of input channels.
  82. :param out_channels: number of output channels.
  83. :param kernel_size: size of weight on spatial dimensions. If ``kernel_size`` is
  84. an :class:`int`, the actual kernel size would be
  85. ``(kernel_size, kernel_size)``. Default: 1
  86. :param stride: stride of the 2D convolution operation. Default: 1
  87. :param padding: size of the paddings added to the input on both sides of its
  88. spatial dimensions. Only zero-padding is supported. Default: 0
  89. :param dilation: dilation of the 2D convolution operation. Default: 1
  90. :param groups: number of groups to divide input and output channels into,
  91. so as to perform a "grouped convolution". When ``groups`` is not 1,
  92. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  93. and there would be an extra dimension at the beginning of the weight's
  94. shape. Specifically, the shape of weight would be ``(groups,
  95. out_channel // groups, in_channels // groups, *kernel_size)``.
  96. :param bias: whether to add a bias onto the result of convolution. Default:
  97. True
  98. :param conv_mode: Supports `CROSS_CORRELATION` or `CONVOLUTION`. Default:
  99. `CROSS_CORRELATION`.
  100. :param compute_mode: When set to `DEFAULT`, no special requirements will be
  101. placed on the precision of intermediate results. When set to `FLOAT32`,
  102. float32 would be used for accumulator and intermediate result, but only
  103. effective when input and output are of float16 dtype.
  104. """
  105. _conv_mode_type = mgb.opr_param_defs.Convolution.Mode
  106. _compute_mode_type = mgb.opr_param_defs.Convolution.ComputeMode
  107. def __init__(
  108. self,
  109. in_channels: int,
  110. out_channels: int,
  111. kernel_size: Union[int, Tuple[int, int]],
  112. stride: Union[int, Tuple[int, int]] = 1,
  113. padding: Union[int, Tuple[int, int]] = 0,
  114. dilation: Union[int, Tuple[int, int]] = 1,
  115. groups: int = 1,
  116. bias: bool = True,
  117. conv_mode: str = "CROSS_CORRELATION",
  118. compute_mode: str = "DEFAULT",
  119. ):
  120. kernel_size = _pair_nonzero(kernel_size)
  121. stride = _pair_nonzero(stride)
  122. padding = _pair(padding)
  123. dilation = _pair_nonzero(dilation)
  124. self.conv_mode = self._conv_mode_type.convert(conv_mode)
  125. self.compute_mode = self._compute_mode_type.convert(compute_mode)
  126. super().__init__(
  127. in_channels,
  128. out_channels,
  129. kernel_size,
  130. stride,
  131. padding,
  132. dilation,
  133. groups,
  134. bias,
  135. )
  136. def _get_fanin(self):
  137. kh, kw = self.kernel_size
  138. ic = self.in_channels
  139. return kh * kw * ic
  140. def _infer_weight_shape(self):
  141. group = self.groups
  142. ichl = self.in_channels
  143. ochl = self.out_channels
  144. kh, kw = self.kernel_size
  145. if group == 1:
  146. # Assume format is NCHW
  147. return (ochl, ichl, kh, kw)
  148. assert (
  149. ichl % group == 0 and ochl % group == 0
  150. ), "invalid config: input_channels={} output_channels={} group={}".format(
  151. ichl, ochl, group
  152. )
  153. # Assume format is NCHW
  154. return (group, ochl // group, ichl // group, kh, kw)
  155. def _infer_bias_shape(self):
  156. # Assume format is NCHW
  157. return (1, self.out_channels, 1, 1)
  158. def calc_conv(self, inp, weight, bias):
  159. return F.conv2d(
  160. inp,
  161. weight,
  162. bias,
  163. self.stride,
  164. self.padding,
  165. self.dilation,
  166. self.groups,
  167. self.conv_mode,
  168. self.compute_mode,
  169. )
  170. def forward(self, inp):
  171. return self.calc_conv(inp, self.weight, self.bias)
  172. class ConvTranspose2d(_ConvNd):
  173. r"""Applies a 2D transposed convolution over an input tensor.
  174. This module is also known as a deconvolution or a fractionally-strided convolution.
  175. :class:`ConvTranspose2d` can ben seen as the gradient of :class:`Conv2d` operation
  176. with respect to its input.
  177. Convolution usually reduces the size of input, while transposed convolution works
  178. the opposite way, transforming a smaller input to a larger output while preserving the
  179. connectivity pattern.
  180. :param in_channels: number of input channels.
  181. :param out_channels: number of output channels.
  182. :param kernel_size: size of weight on spatial dimensions. If ``kernel_size`` is
  183. an :class:`int`, the actual kernel size would be
  184. ``(kernel_size, kernel_size)``. Default: 1
  185. :param stride: stride of the 2D convolution operation. Default: 1
  186. :param padding: size of the paddings added to the input on both sides of its
  187. spatial dimensions. Only zero-padding is supported. Default: 0
  188. :param dilation: dilation of the 2D convolution operation. Default: 1
  189. :param groups: number of groups to divide input and output channels into,
  190. so as to perform a "grouped convolution". When ``groups`` is not 1,
  191. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  192. and there would be an extra dimension at the beginning of the weight's
  193. shape. Specifically, the shape of weight would be ``(groups,
  194. out_channels // groups, in_channels // groups, *kernel_size)``. Default: 1
  195. :param bias: wether to add a bias onto the result of convolution. Default:
  196. True
  197. :param conv_mode: Supports `CROSS_CORRELATION` or `CONVOLUTION`. Default:
  198. `CROSS_CORRELATION`.
  199. :param compute_mode: When set to `DEFAULT`, no special requirements will be
  200. placed on the precision of intermediate results. When set to `FLOAT32`,
  201. float32 would be used for accumulator and intermediate result, but only
  202. effective when input and output are of float16 dtype.
  203. """
  204. _conv_mode_type = mgb.opr_param_defs.Convolution.Mode
  205. _compute_mode_type = mgb.opr_param_defs.Convolution.ComputeMode
  206. def __init__(
  207. self,
  208. in_channels: int,
  209. out_channels: int,
  210. kernel_size: Union[int, Tuple[int, int]],
  211. stride: Union[int, Tuple[int, int]] = 1,
  212. padding: Union[int, Tuple[int, int]] = 0,
  213. dilation: Union[int, Tuple[int, int]] = 1,
  214. groups: int = 1,
  215. bias: bool = True,
  216. conv_mode: str = "CROSS_CORRELATION",
  217. compute_mode: str = "DEFAULT",
  218. ):
  219. kernel_size = _pair_nonzero(kernel_size)
  220. stride = _pair_nonzero(stride)
  221. padding = _pair(padding)
  222. dilation = _pair_nonzero(dilation)
  223. self.conv_mode = self._conv_mode_type.convert(conv_mode)
  224. self.compute_mode = self._compute_mode_type.convert(compute_mode)
  225. super().__init__(
  226. in_channels,
  227. out_channels,
  228. kernel_size,
  229. stride,
  230. padding,
  231. dilation,
  232. groups,
  233. bias,
  234. )
  235. def _get_fanin(self):
  236. kh, kw = self.kernel_size
  237. oc = self.out_channels
  238. return kh * kw * oc
  239. def _infer_weight_shape(self):
  240. group = self.groups
  241. ichl = self.in_channels
  242. ochl = self.out_channels
  243. kh, kw = self.kernel_size
  244. if group == 1:
  245. # Assume format is NCHW
  246. return (ichl, ochl, kh, kw)
  247. assert (
  248. ichl % group == 0 and ochl % group == 0
  249. ), "invalid config: input_channels={} output_channels={} group={}".format(
  250. ichl, ochl, group
  251. )
  252. # Assume format is NCHW
  253. return (group, ichl // group, ochl // group, kh, kw)
  254. def _infer_bias_shape(self):
  255. # Assume format is NCHW
  256. return (1, self.out_channels, 1, 1)
  257. def forward(self, inp):
  258. return F.conv_transpose2d(
  259. inp,
  260. self.weight,
  261. self.bias,
  262. self.stride,
  263. self.padding,
  264. self.dilation,
  265. self.groups,
  266. self.conv_mode,
  267. self.compute_mode,
  268. )
  269. class LocalConv2d(Conv2d):
  270. r"""Applies a spatial convolution with untied kernels over an input 4D tensor.
  271. It is also known as the locally connected layer.
  272. :param in_channels: number of input channels.
  273. :param out_channels: number of output channels.
  274. :param input_height: the height of the input images.
  275. :param input_width: the width of the input images.
  276. :param kernel_size: size of weight on spatial dimensions. If ``kernel_size`` is
  277. an :class:`int`, the actual kernel size would be
  278. ``(kernel_size, kernel_size)``. Default: 1
  279. :param stride: stride of the 2D convolution operation. Default: 1
  280. :param padding: size of the paddings added to the input on both sides of its
  281. spatial dimensions. Only zero-padding is supported. Default: 0
  282. :param groups: number of groups to divide input and output channels into,
  283. so as to perform a "grouped convolution". When ``groups`` is not 1,
  284. ``in_channels`` and ``out_channels`` must be divisible by ``groups``.
  285. The shape of weight is ``(groups, output_height, output_width,
  286. in_channels // groups, *kernel_size, out_channels // groups)``.
  287. """
  288. _conv_mode_type = mgb.opr_param_defs.Convolution.Mode
  289. def __init__(
  290. self,
  291. in_channels: int,
  292. out_channels: int,
  293. input_height: int,
  294. input_width: int,
  295. kernel_size: Union[int, Tuple[int, int]],
  296. stride: Union[int, Tuple[int, int]] = 1,
  297. padding: Union[int, Tuple[int, int]] = 0,
  298. dilation: Union[int, Tuple[int, int]] = 1,
  299. groups: int = 1,
  300. conv_mode: str = "CROSS_CORRELATION",
  301. ):
  302. self.input_height = input_height
  303. self.input_width = input_width
  304. super().__init__(
  305. in_channels,
  306. out_channels,
  307. kernel_size,
  308. stride,
  309. padding,
  310. dilation,
  311. groups,
  312. bias=False,
  313. )
  314. def _infer_weight_shape(self):
  315. group = self.groups
  316. output_height = (
  317. self.input_height + self.padding[0] * 2 - self.kernel_size[0]
  318. ) // self.stride[0] + 1
  319. output_width = (
  320. self.input_width + self.padding[1] * 2 - self.kernel_size[1]
  321. ) // self.stride[1] + 1
  322. # Assume format is NCHW
  323. return (
  324. group,
  325. output_height,
  326. output_width,
  327. self.in_channels // group,
  328. self.kernel_size[0],
  329. self.kernel_size[1],
  330. self.out_channels // group,
  331. )
  332. def forward(self, inp):
  333. return F.local_conv2d(
  334. inp, self.weight, self.stride, self.padding, self.dilation, self.conv_mode
  335. )
  336. class ConvRelu2d(Conv2d):
  337. r"""
  338. A fused :class:`~.Module` including Conv2d and relu. Could be replaced
  339. with :class:`~.QATModule` version :class:`~.qat.conv.ConvRelu2d` using
  340. :func:`~.quantize.quantize_qat`.
  341. """
  342. def forward(self, inp):
  343. return F.relu(self.calc_conv(inp, self.weight, self.bias))

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