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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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. from ..core.ops._internal import param_defs as P
  12. from ..functional import conv2d, conv_transpose2d, local_conv2d, relu
  13. from ..functional.types import _pair, _pair_nonzero
  14. from ..tensor import Parameter
  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. Examples:
  105. .. testcode::
  106. import numpy as np
  107. import megengine as mge
  108. import megengine.module as M
  109. m = M.Conv2d(in_channels=3, out_channels=1, kernel_size=3)
  110. inp = mge.tensor(np.arange(0, 96).astype("float32").reshape(2, 3, 4, 4))
  111. oup = m(inp)
  112. print(oup.shape)
  113. Outputs:
  114. .. testoutput::
  115. (2, 1, 2, 2)
  116. """
  117. _conv_mode_type = P.Convolution.Mode
  118. _compute_mode_type = P.Convolution.ComputeMode
  119. def __init__(
  120. self,
  121. in_channels: int,
  122. out_channels: int,
  123. kernel_size: Union[int, Tuple[int, int]],
  124. stride: Union[int, Tuple[int, int]] = 1,
  125. padding: Union[int, Tuple[int, int]] = 0,
  126. dilation: Union[int, Tuple[int, int]] = 1,
  127. groups: int = 1,
  128. bias: bool = True,
  129. conv_mode: str = "CROSS_CORRELATION",
  130. compute_mode: str = "DEFAULT",
  131. ):
  132. kernel_size = _pair_nonzero(kernel_size)
  133. stride = _pair_nonzero(stride)
  134. padding = _pair(padding)
  135. dilation = _pair_nonzero(dilation)
  136. self.conv_mode = self._conv_mode_type.convert(conv_mode)
  137. self.compute_mode = self._compute_mode_type.convert(compute_mode)
  138. super().__init__(
  139. in_channels,
  140. out_channels,
  141. kernel_size,
  142. stride,
  143. padding,
  144. dilation,
  145. groups,
  146. bias,
  147. )
  148. def _get_fanin(self):
  149. kh, kw = self.kernel_size
  150. ic = self.in_channels
  151. return kh * kw * ic
  152. def _infer_weight_shape(self):
  153. group = self.groups
  154. ichl = self.in_channels
  155. ochl = self.out_channels
  156. kh, kw = self.kernel_size
  157. if group == 1:
  158. # Assume format is NCHW
  159. return (ochl, ichl, kh, kw)
  160. assert (
  161. ichl % group == 0 and ochl % group == 0
  162. ), "invalid config: input_channels={} output_channels={} group={}".format(
  163. ichl, ochl, group
  164. )
  165. # Assume format is NCHW
  166. return (group, ochl // group, ichl // group, kh, kw)
  167. def _infer_bias_shape(self):
  168. # Assume format is NCHW
  169. return (1, self.out_channels, 1, 1)
  170. def calc_conv(self, inp, weight, bias):
  171. return conv2d(
  172. inp,
  173. weight,
  174. bias,
  175. self.stride,
  176. self.padding,
  177. self.dilation,
  178. self.groups,
  179. self.conv_mode,
  180. self.compute_mode,
  181. )
  182. def forward(self, inp):
  183. return self.calc_conv(inp, self.weight, self.bias)
  184. class ConvTranspose2d(_ConvNd):
  185. r"""Applies a 2D transposed convolution over an input tensor.
  186. This module is also known as a deconvolution or a fractionally-strided convolution.
  187. :class:`ConvTranspose2d` can ben seen as the gradient of :class:`Conv2d` operation
  188. with respect to its input.
  189. Convolution usually reduces the size of input, while transposed convolution works
  190. the opposite way, transforming a smaller input to a larger output while preserving the
  191. connectivity pattern.
  192. :param in_channels: number of input channels.
  193. :param out_channels: number of output channels.
  194. :param kernel_size: size of weight on spatial dimensions. If ``kernel_size`` is
  195. an :class:`int`, the actual kernel size would be
  196. ``(kernel_size, kernel_size)``. Default: 1
  197. :param stride: stride of the 2D convolution operation. Default: 1
  198. :param padding: size of the paddings added to the input on both sides of its
  199. spatial dimensions. Only zero-padding is supported. Default: 0
  200. :param dilation: dilation of the 2D convolution operation. Default: 1
  201. :param groups: number of groups to divide input and output channels into,
  202. so as to perform a "grouped convolution". When ``groups`` is not 1,
  203. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  204. and there would be an extra dimension at the beginning of the weight's
  205. shape. Specifically, the shape of weight would be ``(groups,
  206. out_channels // groups, in_channels // groups, *kernel_size)``. Default: 1
  207. :param bias: wether to add a bias onto the result of convolution. Default:
  208. True
  209. :param conv_mode: Supports `CROSS_CORRELATION` or `CONVOLUTION`. Default:
  210. `CROSS_CORRELATION`
  211. :param compute_mode: When set to `DEFAULT`, no special requirements will be
  212. placed on the precision of intermediate results. When set to `FLOAT32`,
  213. float32 would be used for accumulator and intermediate result, but only
  214. effective when input and output are of float16 dtype.
  215. """
  216. _conv_mode_type = P.Convolution.Mode
  217. _compute_mode_type = P.Convolution.ComputeMode
  218. def __init__(
  219. self,
  220. in_channels: int,
  221. out_channels: int,
  222. kernel_size: Union[int, Tuple[int, int]],
  223. stride: Union[int, Tuple[int, int]] = 1,
  224. padding: Union[int, Tuple[int, int]] = 0,
  225. dilation: Union[int, Tuple[int, int]] = 1,
  226. groups: int = 1,
  227. bias: bool = True,
  228. conv_mode: str = "CROSS_CORRELATION",
  229. compute_mode: str = "DEFAULT",
  230. ):
  231. kernel_size = _pair_nonzero(kernel_size)
  232. stride = _pair_nonzero(stride)
  233. padding = _pair(padding)
  234. dilation = _pair_nonzero(dilation)
  235. self.conv_mode = self._conv_mode_type.convert(conv_mode)
  236. self.compute_mode = self._compute_mode_type.convert(compute_mode)
  237. super().__init__(
  238. in_channels,
  239. out_channels,
  240. kernel_size,
  241. stride,
  242. padding,
  243. dilation,
  244. groups,
  245. bias,
  246. )
  247. def _get_fanin(self):
  248. kh, kw = self.kernel_size
  249. oc = self.out_channels
  250. return kh * kw * oc
  251. def _infer_weight_shape(self):
  252. group = self.groups
  253. ichl = self.in_channels
  254. ochl = self.out_channels
  255. kh, kw = self.kernel_size
  256. if group == 1:
  257. # Assume format is NCHW
  258. return (ichl, ochl, kh, kw)
  259. assert (
  260. ichl % group == 0 and ochl % group == 0
  261. ), "invalid config: input_channels={} output_channels={} group={}".format(
  262. ichl, ochl, group
  263. )
  264. # Assume format is NCHW
  265. return (group, ichl // group, ochl // group, kh, kw)
  266. def _infer_bias_shape(self):
  267. # Assume format is NCHW
  268. return (1, self.out_channels, 1, 1)
  269. def forward(self, inp):
  270. return conv_transpose2d(
  271. inp,
  272. self.weight,
  273. self.bias,
  274. self.stride,
  275. self.padding,
  276. self.dilation,
  277. self.groups,
  278. self.conv_mode,
  279. self.compute_mode,
  280. )
  281. class LocalConv2d(Conv2d):
  282. r"""Applies a spatial convolution with untied kernels over an input 4D tensor.
  283. It is also known as the locally connected layer.
  284. :param in_channels: number of input channels.
  285. :param out_channels: number of output channels.
  286. :param input_height: the height of the input images.
  287. :param input_width: the width of the input images.
  288. :param kernel_size: size of weight on spatial dimensions. If kernel_size is
  289. an :class:`int`, the actual kernel size would be
  290. `(kernel_size, kernel_size)`. Default: 1
  291. :param stride: stride of the 2D convolution operation. Default: 1
  292. :param padding: size of the paddings added to the input on both sides of its
  293. spatial dimensions. Only zero-padding is supported. Default: 0
  294. :param groups: number of groups to divide input and output channels into,
  295. so as to perform a "grouped convolution". When groups is not 1,
  296. in_channels and out_channels must be divisible by groups.
  297. The shape of weight is `(groups, output_height, output_width,
  298. in_channels // groups, *kernel_size, out_channels // groups)`.
  299. """
  300. _conv_mode_type = P.Convolution.Mode
  301. def __init__(
  302. self,
  303. in_channels: int,
  304. out_channels: int,
  305. input_height: int,
  306. input_width: int,
  307. kernel_size: Union[int, Tuple[int, int]],
  308. stride: Union[int, Tuple[int, int]] = 1,
  309. padding: Union[int, Tuple[int, int]] = 0,
  310. dilation: Union[int, Tuple[int, int]] = 1,
  311. groups: int = 1,
  312. conv_mode: str = "CROSS_CORRELATION",
  313. ):
  314. self.input_height = input_height
  315. self.input_width = input_width
  316. super().__init__(
  317. in_channels,
  318. out_channels,
  319. kernel_size,
  320. stride,
  321. padding,
  322. dilation,
  323. groups,
  324. bias=False,
  325. )
  326. def _infer_weight_shape(self):
  327. group = self.groups
  328. output_height = (
  329. self.input_height + self.padding[0] * 2 - self.kernel_size[0]
  330. ) // self.stride[0] + 1
  331. output_width = (
  332. self.input_width + self.padding[1] * 2 - self.kernel_size[1]
  333. ) // self.stride[1] + 1
  334. # Assume format is NCHW
  335. return (
  336. group,
  337. output_height,
  338. output_width,
  339. self.in_channels // group,
  340. self.kernel_size[0],
  341. self.kernel_size[1],
  342. self.out_channels // group,
  343. )
  344. def forward(self, inp):
  345. return local_conv2d(
  346. inp,
  347. self.weight,
  348. None,
  349. self.stride,
  350. self.padding,
  351. self.dilation,
  352. self.conv_mode,
  353. )
  354. class ConvRelu2d(Conv2d):
  355. r"""
  356. A fused :class:`~.Module` including Conv2d and relu. Could be replaced
  357. with :class:`~.QATModule` version :class:`~.qat.conv.ConvRelu2d` using
  358. :func:`~.quantize.quantize_qat`.
  359. """
  360. def forward(self, inp):
  361. return relu(self.calc_conv(inp, self.weight, self.bias))

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