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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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 ..functional import conv1d, conv2d, conv_transpose2d, local_conv2d, relu
  12. from ..functional.types import _pair, _pair_nonzero
  13. from ..tensor import Parameter
  14. from . import init
  15. from .module import Module
  16. class _ConvNd(Module):
  17. """base class for convolution modules, including transposed conv"""
  18. def __init__(
  19. self,
  20. in_channels: int,
  21. out_channels: int,
  22. kernel_size: Union[int, Tuple[int, int]],
  23. stride: Union[int, Tuple[int, int]],
  24. padding: Union[int, Tuple[int, int]],
  25. dilation: Union[int, Tuple[int, int]],
  26. groups: int,
  27. bias: bool = True,
  28. ):
  29. super().__init__()
  30. if in_channels % groups != 0:
  31. raise ValueError("in_channels must be divisible by groups")
  32. if out_channels % groups != 0:
  33. raise ValueError("out_channels must be divisible by groups")
  34. self.in_channels = in_channels
  35. self.out_channels = out_channels
  36. self.kernel_size = kernel_size
  37. self.stride = stride
  38. self.padding = padding
  39. self.dilation = dilation
  40. self.groups = groups
  41. self.weight = Parameter(np.zeros(self._infer_weight_shape(), dtype=np.float32))
  42. self.bias = None
  43. if bias:
  44. self.bias = Parameter(np.zeros(self._infer_bias_shape(), dtype=np.float32))
  45. self.reset_parameters()
  46. @abstractmethod
  47. def _get_fanin(self):
  48. pass
  49. def reset_parameters(self) -> None:
  50. fanin = self._get_fanin()
  51. std = np.sqrt(1 / fanin)
  52. init.normal_(self.weight, 0.0, std)
  53. if self.bias is not None:
  54. init.zeros_(self.bias)
  55. @abstractmethod
  56. def _infer_weight_shape(self):
  57. pass
  58. @abstractmethod
  59. def _infer_bias_shape(self):
  60. pass
  61. def _module_info_string(self):
  62. s = "{in_channels}, {out_channels}, kernel_size={kernel_size}"
  63. if self.stride != (1,) * len(self.stride):
  64. s += ", stride={stride}"
  65. if self.padding != (0,) * len(self.padding):
  66. s += ", padding={padding}"
  67. if self.dilation != (1,) * len(self.dilation):
  68. s += ", dilation={dilation}"
  69. if self.groups != 1:
  70. s += ", groups={groups}"
  71. if self.bias is None:
  72. s += ", bias=False"
  73. return s.format(**self.__dict__)
  74. class Conv1d(_ConvNd):
  75. r"""
  76. Applies a 1D convolution over an input tensor.
  77. For instance, given an input of the size :math:`(N, C_{\text{in}}, H)`,
  78. this layer generates an output of the size
  79. :math:`(N, C_{\text{out}}, H_{\text{out}}})` through the
  80. process described as below:
  81. .. math::
  82. \text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) +
  83. \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)
  84. where :math:`\star` is the valid 1D cross-correlation operator,
  85. :math:`N` is batch size, :math:`C` denotes number of channels, and
  86. :math:`H` is length of 1D data element.
  87. When `groups == in_channels` and `out_channels == K * in_channels`,
  88. where K is a positive integer, this operation is also known as depthwise
  89. convolution.
  90. In other words, for an input of size :math:`(N, C_{in}, H_{in})`,
  91. a depthwise convolution with a depthwise multiplier `K`, can be constructed
  92. by arguments :math:`(in\_channels=C_{in}, out\_channels=C_{in} \times K, ..., groups=C_{in})`.
  93. :param in_channels: number of input channels.
  94. :param out_channels: number of output channels.
  95. :param kernel_size: size of weight on spatial dimensions. If kernel_size is
  96. an :class:`int`, the actual kernel size would be
  97. `(kernel_size, kernel_size)`. Default: 1
  98. :param stride: stride of the 1D convolution operation. Default: 1
  99. :param padding: size of the paddings added to the input on both sides of its
  100. spatial dimensions. Only zero-padding is supported. Default: 0
  101. :param dilation: dilation of the 1D convolution operation. Default: 1
  102. :param groups: number of groups into which the input and output channels are divided, so as to perform a "grouped convolution". When ``groups`` is not 1,
  103. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  104. and there would be an extra dimension at the beginning of the weight's
  105. shape. Specifically, the shape of weight would be `(groups,
  106. out_channel // groups, in_channels // groups, *kernel_size)`.
  107. :param bias: whether to add a bias onto the result of convolution. Default:
  108. True
  109. :param conv_mode: Supports `CROSS_CORRELATION`. Default:
  110. `CROSS_CORRELATION`
  111. :param compute_mode: When set to "DEFAULT", no special requirements will be
  112. placed on the precision of intermediate results. When set to "FLOAT32",
  113. "Float32" would be used for accumulator and intermediate result, but only
  114. effective when input and output are of float16 dtype.
  115. Examples:
  116. .. testcode::
  117. import numpy as np
  118. import megengine as mge
  119. import megengine.module as M
  120. m = M.Conv1d(in_channels=3, out_channels=1, kernel_size=3)
  121. inp = mge.tensor(np.arange(0, 24).astype("float32").reshape(2, 3, 4))
  122. oup = m(inp)
  123. print(oup.numpy().shape)
  124. Outputs:
  125. .. testoutput::
  126. (2, 1, 2)
  127. """
  128. def __init__(
  129. self,
  130. in_channels: int,
  131. out_channels: int,
  132. kernel_size: int,
  133. stride: int = 1,
  134. padding: int = 0,
  135. dilation: int = 1,
  136. groups: int = 1,
  137. bias: bool = True,
  138. conv_mode: str = "CROSS_CORRELATION",
  139. compute_mode: str = "DEFAULT",
  140. ):
  141. kernel_size = kernel_size
  142. stride = stride
  143. padding = padding
  144. dilation = dilation
  145. self.conv_mode = conv_mode
  146. self.compute_mode = compute_mode
  147. super().__init__(
  148. in_channels,
  149. out_channels,
  150. kernel_size,
  151. stride,
  152. padding,
  153. dilation,
  154. groups,
  155. bias,
  156. )
  157. def _get_fanin(self):
  158. kh = self.kernel_size
  159. ic = self.in_channels
  160. return kh * ic
  161. def _infer_weight_shape(self):
  162. group = self.groups
  163. ichl = self.in_channels
  164. ochl = self.out_channels
  165. kh = self.kernel_size
  166. if group == 1:
  167. # Assume format is NCH(W=1)
  168. return (ochl, ichl, kh)
  169. assert (
  170. ichl % group == 0 and ochl % group == 0
  171. ), "invalid config: input_channels={} output_channels={} group={}".format(
  172. ichl, ochl, group
  173. )
  174. # Assume format is NCH(W=1)
  175. return (group, ochl // group, ichl // group, kh)
  176. def _infer_bias_shape(self):
  177. # Assume format is NCH(W=1)
  178. return (1, self.out_channels, 1)
  179. def calc_conv(self, inp, weight, bias):
  180. return conv1d(
  181. inp,
  182. weight,
  183. bias,
  184. self.stride,
  185. self.padding,
  186. self.dilation,
  187. self.groups,
  188. self.conv_mode,
  189. self.compute_mode,
  190. )
  191. def forward(self, inp):
  192. return self.calc_conv(inp, self.weight, self.bias)
  193. class Conv2d(_ConvNd):
  194. r"""
  195. Applies a 2D convolution over an input tensor.
  196. For instance, given an input of the size :math:`(N, C_{\text{in}}, H, W)`,
  197. this layer generates an output of the size
  198. :math:`(N, C_{\text{out}}, H_{\text{out}}, W_{\text{out}})` through the
  199. process described as below:
  200. .. math::
  201. \text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) +
  202. \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)
  203. where :math:`\star` is the valid 2D cross-correlation operator,
  204. :math:`N` is batch size, :math:`C` denotes number of channels,
  205. :math:`H` is height of input planes in pixels, and :math:`W` is
  206. width in pixels.
  207. When `groups == in_channels` and `out_channels == K * in_channels`,
  208. where K is a positive integer, this operation is also known as depthwise
  209. convolution.
  210. In other words, for an input of size :math:`(N, C_{in}, H_{in}, W_{in})`,
  211. a depthwise convolution with a depthwise multiplier `K`, can be constructed
  212. by arguments :math:`(in\_channels=C_{in}, out\_channels=C_{in} \times K, ..., groups=C_{in})`.
  213. :param in_channels: number of input channels.
  214. :param out_channels: number of output channels.
  215. :param kernel_size: size of weight on spatial dimensions. If kernel_size is
  216. an :class:`int`, the actual kernel size would be
  217. `(kernel_size, kernel_size)`. Default: 1
  218. :param stride: stride of the 2D convolution operation. Default: 1
  219. :param padding: size of the paddings added to the input on both sides of its
  220. spatial dimensions. Only zero-padding is supported. Default: 0
  221. :param dilation: dilation of the 2D convolution operation. Default: 1
  222. :param groups: number of groups into which the input and output channels are divided, so as to perform a "grouped convolution". When ``groups`` is not 1,
  223. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  224. and there would be an extra dimension at the beginning of the weight's
  225. shape. Specifically, the shape of weight would be `(groups,
  226. out_channel // groups, in_channels // groups, *kernel_size)`.
  227. :param bias: whether to add a bias onto the result of convolution. Default:
  228. True
  229. :param conv_mode: Supports `CROSS_CORRELATION`. Default:
  230. `CROSS_CORRELATION`
  231. :param compute_mode: When set to "DEFAULT", no special requirements will be
  232. placed on the precision of intermediate results. When set to "FLOAT32",
  233. "Float32" would be used for accumulator and intermediate result, but only
  234. effective when input and output are of float16 dtype.
  235. Examples:
  236. .. testcode::
  237. import numpy as np
  238. import megengine as mge
  239. import megengine.module as M
  240. m = M.Conv2d(in_channels=3, out_channels=1, kernel_size=3)
  241. inp = mge.tensor(np.arange(0, 96).astype("float32").reshape(2, 3, 4, 4))
  242. oup = m(inp)
  243. print(oup.numpy().shape)
  244. Outputs:
  245. .. testoutput::
  246. (2, 1, 2, 2)
  247. """
  248. def __init__(
  249. self,
  250. in_channels: int,
  251. out_channels: int,
  252. kernel_size: Union[int, Tuple[int, int]],
  253. stride: Union[int, Tuple[int, int]] = 1,
  254. padding: Union[int, Tuple[int, int]] = 0,
  255. dilation: Union[int, Tuple[int, int]] = 1,
  256. groups: int = 1,
  257. bias: bool = True,
  258. conv_mode: str = "CROSS_CORRELATION",
  259. compute_mode: str = "DEFAULT",
  260. ):
  261. kernel_size = _pair_nonzero(kernel_size)
  262. stride = _pair_nonzero(stride)
  263. padding = _pair(padding)
  264. dilation = _pair_nonzero(dilation)
  265. self.conv_mode = conv_mode
  266. self.compute_mode = compute_mode
  267. super().__init__(
  268. in_channels,
  269. out_channels,
  270. kernel_size,
  271. stride,
  272. padding,
  273. dilation,
  274. groups,
  275. bias,
  276. )
  277. def _get_fanin(self):
  278. kh, kw = self.kernel_size
  279. ic = self.in_channels
  280. return kh * kw * ic
  281. def _infer_weight_shape(self):
  282. group = self.groups
  283. ichl = self.in_channels
  284. ochl = self.out_channels
  285. kh, kw = self.kernel_size
  286. if group == 1:
  287. # Assume format is NCHW
  288. return (ochl, ichl, kh, kw)
  289. assert (
  290. ichl % group == 0 and ochl % group == 0
  291. ), "invalid config: input_channels={} output_channels={} group={}".format(
  292. ichl, ochl, group
  293. )
  294. # Assume format is NCHW
  295. return (group, ochl // group, ichl // group, kh, kw)
  296. def _infer_bias_shape(self):
  297. # Assume format is NCHW
  298. return (1, self.out_channels, 1, 1)
  299. def calc_conv(self, inp, weight, bias):
  300. return conv2d(
  301. inp,
  302. weight,
  303. bias,
  304. self.stride,
  305. self.padding,
  306. self.dilation,
  307. self.groups,
  308. self.conv_mode,
  309. self.compute_mode,
  310. )
  311. def forward(self, inp):
  312. return self.calc_conv(inp, self.weight, self.bias)
  313. class ConvTranspose2d(_ConvNd):
  314. r"""
  315. Applies a 2D transposed convolution over an input tensor.
  316. This module is also known as a deconvolution or a fractionally-strided convolution.
  317. :class:`ConvTranspose2d` can be seen as the gradient of :class:`Conv2d` operation
  318. with respect to its input.
  319. Convolution usually reduces the size of input, while transposed convolution works
  320. the opposite way, transforming a smaller input to a larger output while preserving the
  321. connectivity pattern.
  322. :param in_channels: number of input channels.
  323. :param out_channels: number of output channels.
  324. :param kernel_size: size of weight on spatial dimensions. If ``kernel_size`` is
  325. an :class:`int`, the actual kernel size would be
  326. ``(kernel_size, kernel_size)``. Default: 1
  327. :param stride: stride of the 2D convolution operation. Default: 1
  328. :param padding: size of the paddings added to the input on both sides of its
  329. spatial dimensions. Only zero-padding is supported. Default: 0
  330. :param dilation: dilation of the 2D convolution operation. Default: 1
  331. :param groups: number of groups into which the input and output channels are divided, so as to perform a "grouped convolution". When ``groups`` is not 1,
  332. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  333. and there would be an extra dimension at the beginning of the weight's
  334. shape. Specifically, the shape of weight would be ``(groups,
  335. out_channels // groups, in_channels // groups, *kernel_size)``. Default: 1
  336. :param bias: wether to add a bias onto the result of convolution. Default:
  337. True
  338. :param conv_mode: Supports `CROSS_CORRELATION`. Default:
  339. `CROSS_CORRELATION`
  340. :param compute_mode: When set to "DEFAULT", no special requirements will be
  341. placed on the precision of intermediate results. When set to "FLOAT32",
  342. "Float32" would be used for accumulator and intermediate result, but only
  343. effective when input and output are of float16 dtype.
  344. """
  345. def __init__(
  346. self,
  347. in_channels: int,
  348. out_channels: int,
  349. kernel_size: Union[int, Tuple[int, int]],
  350. stride: Union[int, Tuple[int, int]] = 1,
  351. padding: Union[int, Tuple[int, int]] = 0,
  352. dilation: Union[int, Tuple[int, int]] = 1,
  353. groups: int = 1,
  354. bias: bool = True,
  355. conv_mode: str = "CROSS_CORRELATION",
  356. compute_mode: str = "DEFAULT",
  357. ):
  358. kernel_size = _pair_nonzero(kernel_size)
  359. stride = _pair_nonzero(stride)
  360. padding = _pair(padding)
  361. dilation = _pair_nonzero(dilation)
  362. self.conv_mode = conv_mode
  363. self.compute_mode = compute_mode
  364. super().__init__(
  365. in_channels,
  366. out_channels,
  367. kernel_size,
  368. stride,
  369. padding,
  370. dilation,
  371. groups,
  372. bias,
  373. )
  374. def _get_fanin(self):
  375. kh, kw = self.kernel_size
  376. oc = self.out_channels
  377. return kh * kw * oc
  378. def _infer_weight_shape(self):
  379. group = self.groups
  380. ichl = self.in_channels
  381. ochl = self.out_channels
  382. kh, kw = self.kernel_size
  383. if group == 1:
  384. # Assume format is NCHW
  385. return (ichl, ochl, kh, kw)
  386. assert (
  387. ichl % group == 0 and ochl % group == 0
  388. ), "invalid config: input_channels={} output_channels={} group={}".format(
  389. ichl, ochl, group
  390. )
  391. # Assume format is NCHW
  392. return (group, ichl // group, ochl // group, kh, kw)
  393. def _infer_bias_shape(self):
  394. # Assume format is NCHW
  395. return (1, self.out_channels, 1, 1)
  396. def forward(self, inp):
  397. return conv_transpose2d(
  398. inp,
  399. self.weight,
  400. self.bias,
  401. self.stride,
  402. self.padding,
  403. self.dilation,
  404. self.groups,
  405. self.conv_mode,
  406. self.compute_mode,
  407. )
  408. class LocalConv2d(Conv2d):
  409. r"""
  410. Applies a spatial convolution with untied kernels over an groupped channeled input 4D tensor.
  411. It is also known as the locally connected layer.
  412. :param in_channels: number of input channels.
  413. :param out_channels: number of output channels.
  414. :param input_height: the height of the input images.
  415. :param input_width: the width of the input images.
  416. :param kernel_size: size of weight on spatial dimensions. If kernel_size is
  417. an :class:`int`, the actual kernel size would be
  418. `(kernel_size, kernel_size)`. Default: 1
  419. :param stride: stride of the 2D convolution operation. Default: 1
  420. :param padding: size of the paddings added to the input on both sides of its
  421. spatial dimensions. Only zero-padding is supported. Default: 0
  422. :param groups: number of groups into which the input and output channels are divided,
  423. so as to perform a "grouped convolution". When ``groups`` is not 1,
  424. ``in_channels`` and ``out_channels`` must be divisible by ``groups``.
  425. The shape of weight is `(groups, output_height, output_width,
  426. in_channels // groups, *kernel_size, out_channels // groups)`.
  427. """
  428. def __init__(
  429. self,
  430. in_channels: int,
  431. out_channels: int,
  432. input_height: int,
  433. input_width: int,
  434. kernel_size: Union[int, Tuple[int, int]],
  435. stride: Union[int, Tuple[int, int]] = 1,
  436. padding: Union[int, Tuple[int, int]] = 0,
  437. dilation: Union[int, Tuple[int, int]] = 1,
  438. groups: int = 1,
  439. conv_mode: str = "CROSS_CORRELATION",
  440. ):
  441. self.input_height = input_height
  442. self.input_width = input_width
  443. super().__init__(
  444. in_channels,
  445. out_channels,
  446. kernel_size,
  447. stride,
  448. padding,
  449. dilation,
  450. groups,
  451. bias=False,
  452. )
  453. def _infer_weight_shape(self):
  454. group = self.groups
  455. output_height = (
  456. self.input_height + self.padding[0] * 2 - self.kernel_size[0]
  457. ) // self.stride[0] + 1
  458. output_width = (
  459. self.input_width + self.padding[1] * 2 - self.kernel_size[1]
  460. ) // self.stride[1] + 1
  461. # Assume format is NCHW
  462. return (
  463. group,
  464. output_height,
  465. output_width,
  466. self.in_channels // group,
  467. self.kernel_size[0],
  468. self.kernel_size[1],
  469. self.out_channels // group,
  470. )
  471. def forward(self, inp):
  472. return local_conv2d(
  473. inp,
  474. self.weight,
  475. None,
  476. self.stride,
  477. self.padding,
  478. self.dilation,
  479. self.conv_mode,
  480. )
  481. class ConvRelu2d(Conv2d):
  482. r"""
  483. A fused :class:`~.Module` including Conv2d and relu. Could be replaced
  484. with :class:`~.QATModule` version :class:`~.qat.conv.ConvRelu2d` using
  485. :func:`~.quantize.quantize_qat`.
  486. """
  487. def forward(self, inp):
  488. return relu(self.calc_conv(inp, self.weight, self.bias))

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