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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917
  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 abc import abstractmethod
  9. from typing import Tuple, Union
  10. import numpy as np
  11. from ..functional import (
  12. conv1d,
  13. conv2d,
  14. conv3d,
  15. conv_transpose2d,
  16. conv_transpose3d,
  17. deformable_conv2d,
  18. local_conv2d,
  19. relu,
  20. )
  21. from ..tensor import Parameter
  22. from ..utils.tuple_function import _pair, _pair_nonzero, _triple, _triple_nonzero
  23. from . import init
  24. from .module import Module
  25. class _ConvNd(Module):
  26. """base class for convolution modules, including transposed conv"""
  27. def __init__(
  28. self,
  29. in_channels: int,
  30. out_channels: int,
  31. kernel_size: Union[int, Tuple[int, int]],
  32. stride: Union[int, Tuple[int, int]],
  33. padding: Union[int, Tuple[int, int]],
  34. dilation: Union[int, Tuple[int, int]],
  35. groups: int,
  36. bias: bool = True,
  37. **kwargs
  38. ):
  39. super().__init__(**kwargs)
  40. if in_channels % groups != 0:
  41. raise ValueError("in_channels must be divisible by groups")
  42. if out_channels % groups != 0:
  43. raise ValueError("out_channels must be divisible by groups")
  44. self.in_channels = in_channels
  45. self.out_channels = out_channels
  46. self.kernel_size = kernel_size
  47. self.stride = stride
  48. self.padding = padding
  49. self.dilation = dilation
  50. self.groups = groups
  51. self.weight = Parameter(np.zeros(self._infer_weight_shape(), dtype=np.float32))
  52. self.bias = None
  53. if bias:
  54. self.bias = Parameter(np.zeros(self._infer_bias_shape(), dtype=np.float32))
  55. self.reset_parameters()
  56. @abstractmethod
  57. def _get_fanin(self):
  58. pass
  59. def reset_parameters(self) -> None:
  60. fanin = self._get_fanin()
  61. std = np.sqrt(1 / fanin)
  62. init.normal_(self.weight, 0.0, std)
  63. if self.bias is not None:
  64. init.zeros_(self.bias)
  65. @abstractmethod
  66. def _infer_weight_shape(self):
  67. pass
  68. @abstractmethod
  69. def _infer_bias_shape(self):
  70. pass
  71. def _module_info_string(self):
  72. s = "{in_channels}, {out_channels}, kernel_size={kernel_size}"
  73. if self.stride != (1,) * len(self.stride):
  74. s += ", stride={stride}"
  75. if self.padding != (0,) * len(self.padding):
  76. s += ", padding={padding}"
  77. if self.dilation != (1,) * len(self.dilation):
  78. s += ", dilation={dilation}"
  79. if self.groups != 1:
  80. s += ", groups={groups}"
  81. if self.bias is None:
  82. s += ", bias=False"
  83. return s.format(**self.__dict__)
  84. class Conv1d(_ConvNd):
  85. r"""
  86. Applies a 1D convolution over an input tensor.
  87. For instance, given an input of the size :math:`(N, C_{\text{in}}, H)`,
  88. this layer generates an output of the size
  89. :math:`(N, C_{\text{out}}, H_{\text{out}})` through the
  90. process described as below:
  91. .. math::
  92. \text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) +
  93. \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)
  94. where :math:`\star` is the valid 1D cross-correlation operator,
  95. :math:`N` is batch size, :math:`C` denotes number of channels, and
  96. :math:`H` is length of 1D data element.
  97. When `groups == in_channels` and `out_channels == K * in_channels`,
  98. where K is a positive integer, this operation is also known as depthwise
  99. convolution.
  100. In other words, for an input of size :math:`(N, C_{in}, H_{in})`,
  101. a depthwise convolution with a depthwise multiplier `K`, can be constructed
  102. by arguments :math:`(in\_channels=C_{in}, out\_channels=C_{in} \times K, ..., groups=C_{in})`.
  103. :param in_channels: number of input channels.
  104. :param out_channels: number of output channels.
  105. :param kernel_size: size of weight on spatial dimensions. If kernel_size is
  106. an :class:`int`, the actual kernel size would be
  107. `(kernel_size, kernel_size)`. Default: 1
  108. :param stride: stride of the 1D convolution operation. Default: 1
  109. :param padding: size of the paddings added to the input on both sides of its
  110. spatial dimensions. Only zero-padding is supported. Default: 0
  111. :param dilation: dilation of the 1D convolution operation. Default: 1
  112. :param groups: number of groups into which the input and output channels are divided,
  113. so as to perform a "grouped convolution". When ``groups`` is not 1,
  114. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  115. and there would be an extra dimension at the beginning of the weight's
  116. shape. Specifically, the shape of weight would be `(groups,
  117. out_channel // groups, in_channels // groups, *kernel_size)`.
  118. :param bias: whether to add a bias onto the result of convolution. Default:
  119. True
  120. :param conv_mode: Supports `cross_correlation`. Default:
  121. `cross_correlation`
  122. :param compute_mode: When set to "default", no special requirements will be
  123. placed on the precision of intermediate results. When set to "float32",
  124. "float32" would be used for accumulator and intermediate result, but only
  125. effective when input and output are of float16 dtype.
  126. Examples:
  127. .. testcode::
  128. import numpy as np
  129. import megengine as mge
  130. import megengine.module as M
  131. m = M.Conv1d(in_channels=3, out_channels=1, kernel_size=3)
  132. inp = mge.tensor(np.arange(0, 24).astype("float32").reshape(2, 3, 4))
  133. oup = m(inp)
  134. print(oup.numpy().shape)
  135. Outputs:
  136. .. testoutput::
  137. (2, 1, 2)
  138. """
  139. def __init__(
  140. self,
  141. in_channels: int,
  142. out_channels: int,
  143. kernel_size: int,
  144. stride: int = 1,
  145. padding: int = 0,
  146. dilation: int = 1,
  147. groups: int = 1,
  148. bias: bool = True,
  149. conv_mode: str = "cross_correlation",
  150. compute_mode: str = "default",
  151. **kwargs
  152. ):
  153. kernel_size = kernel_size
  154. stride = stride
  155. padding = padding
  156. dilation = dilation
  157. self.conv_mode = conv_mode
  158. self.compute_mode = compute_mode
  159. super().__init__(
  160. in_channels,
  161. out_channels,
  162. kernel_size,
  163. stride,
  164. padding,
  165. dilation,
  166. groups,
  167. bias,
  168. **kwargs,
  169. )
  170. def _get_fanin(self):
  171. kh = self.kernel_size
  172. ic = self.in_channels
  173. return kh * ic
  174. def _infer_weight_shape(self):
  175. group = self.groups
  176. ichl = self.in_channels
  177. ochl = self.out_channels
  178. kh = self.kernel_size
  179. if group == 1:
  180. # Assume format is NCH(W=1)
  181. return (ochl, ichl, kh)
  182. assert (
  183. ichl % group == 0 and ochl % group == 0
  184. ), "invalid config: input_channels={} output_channels={} group={}".format(
  185. ichl, ochl, group
  186. )
  187. # Assume format is NCH(W=1)
  188. return (group, ochl // group, ichl // group, kh)
  189. def _infer_bias_shape(self):
  190. # Assume format is NCH(W=1)
  191. return (1, self.out_channels, 1)
  192. def calc_conv(self, inp, weight, bias):
  193. return conv1d(
  194. inp,
  195. weight,
  196. bias,
  197. self.stride,
  198. self.padding,
  199. self.dilation,
  200. self.groups,
  201. self.conv_mode,
  202. self.compute_mode,
  203. )
  204. def forward(self, inp):
  205. return self.calc_conv(inp, self.weight, self.bias)
  206. class Conv2d(_ConvNd):
  207. r"""
  208. Applies a 2D convolution over an input tensor.
  209. For instance, given an input of the size :math:`(N, C_{\text{in}}, H, W)`,
  210. this layer generates an output of the size
  211. :math:`(N, C_{\text{out}}, H_{\text{out}}, W_{\text{out}})` through the
  212. process described as below:
  213. .. math::
  214. \text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) +
  215. \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)
  216. where :math:`\star` is the valid 2D cross-correlation operator,
  217. :math:`N` is batch size, :math:`C` denotes number of channels,
  218. :math:`H` is height of input planes in pixels, and :math:`W` is
  219. width in pixels.
  220. In general, output feature maps' shapes can be inferred as follows:
  221. input: :math:`(N, C_{\text{in}}, H_{\text{in}}, W_{\text{in}})`
  222. output: :math:`(N, C_{\text{out}}, H_{\text{out}}, W_{\text{out}})` where
  223. .. math::
  224. \text{H}_{out} = \lfloor \frac{\text{H}_{in} + 2 * \text{padding[0]} -
  225. \text{dilation[0]} * (\text{kernel_size[0]} - 1) - 1}{\text{stride[0]}} + 1 \rfloor
  226. .. math::
  227. \text{W}_{out} = \lfloor \frac{\text{W}_{in} + 2 * \text{padding[1]} -
  228. \text{dilation[1]} * (\text{kernel_size[1]} - 1) - 1}{\text{stride[1]}} + 1 \rfloor
  229. When `groups == in_channels` and `out_channels == K * in_channels`,
  230. where K is a positive integer, this operation is also known as depthwise
  231. convolution.
  232. In other words, for an input of size :math:`(N, C_{in}, H_{in}, W_{in})`,
  233. a depthwise convolution with a depthwise multiplier `K`, can be constructed
  234. by arguments :math:`(in\_channels=C_{in}, out\_channels=C_{in} \times K, ..., groups=C_{in})`.
  235. :param in_channels: number of input channels.
  236. :param out_channels: number of output channels.
  237. :param kernel_size: size of weight on spatial dimensions. If kernel_size is
  238. an :class:`int`, the actual kernel size would be
  239. `(kernel_size, kernel_size)`. Default: 1
  240. :param stride: stride of the 2D convolution operation. Default: 1
  241. :param padding: size of the paddings added to the input on both sides of its
  242. spatial dimensions. Only zero-padding is supported. Default: 0
  243. :param dilation: dilation of the 2D convolution operation. Default: 1
  244. :param groups: number of groups into which the input and output channels are divided,
  245. so as to perform a "grouped convolution". When ``groups`` is not 1,
  246. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  247. and there would be an extra dimension at the beginning of the weight's
  248. shape. Specifically, the shape of weight would be `(groups,
  249. out_channel // groups, in_channels // groups, *kernel_size)`.
  250. :param bias: whether to add a bias onto the result of convolution. Default:
  251. True
  252. :param conv_mode: Supports `cross_correlation`. Default:
  253. `cross_correlation`
  254. :param compute_mode: When set to "default", no special requirements will be
  255. placed on the precision of intermediate results. When set to "float32",
  256. "float32" would be used for accumulator and intermediate result, but only
  257. effective when input and output are of float16 dtype.
  258. Examples:
  259. .. testcode::
  260. import numpy as np
  261. import megengine as mge
  262. import megengine.module as M
  263. m = M.Conv2d(in_channels=3, out_channels=1, kernel_size=3)
  264. inp = mge.tensor(np.arange(0, 96).astype("float32").reshape(2, 3, 4, 4))
  265. oup = m(inp)
  266. print(oup.numpy().shape)
  267. Outputs:
  268. .. testoutput::
  269. (2, 1, 2, 2)
  270. """
  271. def __init__(
  272. self,
  273. in_channels: int,
  274. out_channels: int,
  275. kernel_size: Union[int, Tuple[int, int]],
  276. stride: Union[int, Tuple[int, int]] = 1,
  277. padding: Union[int, Tuple[int, int]] = 0,
  278. dilation: Union[int, Tuple[int, int]] = 1,
  279. groups: int = 1,
  280. bias: bool = True,
  281. conv_mode: str = "cross_correlation",
  282. compute_mode: str = "default",
  283. **kwargs
  284. ):
  285. kernel_size = _pair_nonzero(kernel_size)
  286. stride = _pair_nonzero(stride)
  287. padding = _pair(padding)
  288. dilation = _pair_nonzero(dilation)
  289. self.conv_mode = conv_mode
  290. self.compute_mode = compute_mode
  291. super().__init__(
  292. in_channels,
  293. out_channels,
  294. kernel_size,
  295. stride,
  296. padding,
  297. dilation,
  298. groups,
  299. bias,
  300. **kwargs,
  301. )
  302. def _get_fanin(self):
  303. kh, kw = self.kernel_size
  304. ic = self.in_channels
  305. return kh * kw * ic
  306. def _infer_weight_shape(self):
  307. group = self.groups
  308. ichl = self.in_channels
  309. ochl = self.out_channels
  310. kh, kw = self.kernel_size
  311. if group == 1:
  312. # Assume format is NCHW
  313. return (ochl, ichl, kh, kw)
  314. assert (
  315. ichl % group == 0 and ochl % group == 0
  316. ), "invalid config: input_channels={} output_channels={} group={}".format(
  317. ichl, ochl, group
  318. )
  319. # Assume format is NCHW
  320. return (group, ochl // group, ichl // group, kh, kw)
  321. def _infer_bias_shape(self):
  322. # Assume format is NCHW
  323. return (1, self.out_channels, 1, 1)
  324. def calc_conv(self, inp, weight, bias):
  325. return conv2d(
  326. inp,
  327. weight,
  328. bias,
  329. self.stride,
  330. self.padding,
  331. self.dilation,
  332. self.groups,
  333. self.conv_mode,
  334. self.compute_mode,
  335. )
  336. def forward(self, inp):
  337. return self.calc_conv(inp, self.weight, self.bias)
  338. class Conv3d(_ConvNd):
  339. r"""
  340. Applies a 3D convolution over an input tensor.
  341. For instance, given an input of the size :math:`(N, C_{\text{in}}, T, H, W)`,
  342. this layer generates an output of the size
  343. :math:`(N, C_{\text{out}}, T_{\text{out}}}, H_{\text{out}}}, W_{\text{out}}})` through the
  344. process described as below:
  345. .. math::
  346. \text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) +
  347. \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)
  348. where :math:`\star` is the valid 3D cross-correlation operator,
  349. :math:`N` is batch size, :math:`C` denotes number of channels
  350. When `groups == in_channels` and `out_channels == K * in_channels`,
  351. where K is a positive integer, this operation is also known as depthwise
  352. convolution.
  353. In other words, for an input of size :math:`(N, C_{in}, T_{int}, H_{in}, W_{in})`,
  354. a depthwise convolution with a depthwise multiplier `K`, can be constructed
  355. by arguments :math:`(in\_channels=C_{in}, out\_channels=C_{in} \times K, ..., groups=C_{in})`.
  356. :param in_channels: number of input channels.
  357. :param out_channels: number of output channels.
  358. :param kernel_size: size of weight on spatial dimensions. If kernel_size is
  359. an :class:`int`, the actual kernel size would be
  360. `(kernel_size, kernel_size, kernel_size)`. Default: 1
  361. :param stride: stride of the 3D convolution operation. Default: 1
  362. :param padding: size of the paddings added to the input on both sides of its
  363. spatial dimensions. Only zero-padding is supported. Default: 0
  364. :param dilation: dilation of the 3D convolution operation. Default: 1
  365. :param groups: number of groups into which the input and output channels are divided,
  366. so as to perform a "grouped convolution". When ``groups`` is not 1,
  367. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  368. and there would be an extra dimension at the beginning of the weight's
  369. shape. Specifically, the shape of weight would be `(groups,
  370. out_channel // groups, in_channels // groups, *kernel_size)`.
  371. :param bias: whether to add a bias onto the result of convolution. Default:
  372. True
  373. :param conv_mode: Supports `cross_correlation`. Default:
  374. `cross_correlation`
  375. Examples:
  376. .. testcode::
  377. import numpy as np
  378. import megengine as mge
  379. import megengine.module as M
  380. m = M.Conv3d(in_channels=3, out_channels=1, kernel_size=3)
  381. inp = mge.tensor(np.arange(0, 384).astype("float32").reshape(2, 3, 4, 4, 4))
  382. oup = m(inp)
  383. print(oup.numpy().shape)
  384. Outputs:
  385. .. testoutput::
  386. (2, 1, 2, 2, 2)
  387. """
  388. def __init__(
  389. self,
  390. in_channels: int,
  391. out_channels: int,
  392. kernel_size: Union[int, Tuple[int, int, int]],
  393. stride: Union[int, Tuple[int, int, int]] = 1,
  394. padding: Union[int, Tuple[int, int, int]] = 0,
  395. dilation: Union[int, Tuple[int, int, int]] = 1,
  396. groups: int = 1,
  397. bias: bool = True,
  398. conv_mode: str = "cross_correlation",
  399. ):
  400. kernel_size = _triple_nonzero(kernel_size)
  401. stride = _triple_nonzero(stride)
  402. padding = _triple(padding)
  403. dilation = _triple_nonzero(dilation)
  404. self.conv_mode = conv_mode
  405. super().__init__(
  406. in_channels,
  407. out_channels,
  408. kernel_size,
  409. stride,
  410. padding,
  411. dilation,
  412. groups,
  413. bias,
  414. )
  415. def _get_fanin(self):
  416. kt, kh, kw = self.kernel_size
  417. ic = self.in_channels
  418. return kt * kh * kw * ic
  419. def _infer_weight_shape(self):
  420. group = self.groups
  421. ichl = self.in_channels
  422. ochl = self.out_channels
  423. kt, kh, kw = self.kernel_size
  424. if group == 1:
  425. # Assume format is NCTHW
  426. return (ochl, ichl, kt, kh, kw)
  427. assert (
  428. ichl % group == 0 and ochl % group == 0
  429. ), "invalid config: input_channels={} output_channels={} group={}".format(
  430. ichl, ochl, group
  431. )
  432. # Assume format is NCTHW
  433. return (group, ochl // group, ichl // group, kt, kh, kw)
  434. def _infer_bias_shape(self):
  435. # Assume format is NCTHW
  436. return (1, self.out_channels, 1, 1, 1)
  437. def calc_conv(self, inp, weight, bias):
  438. return conv3d(
  439. inp,
  440. weight,
  441. bias,
  442. self.stride,
  443. self.padding,
  444. self.dilation,
  445. self.groups,
  446. self.conv_mode,
  447. )
  448. def forward(self, inp):
  449. return self.calc_conv(inp, self.weight, self.bias)
  450. class ConvTranspose2d(_ConvNd):
  451. r"""
  452. Applies a 2D transposed convolution over an input tensor.
  453. This module is also known as a deconvolution or a fractionally-strided convolution.
  454. :class:`ConvTranspose2d` can be seen as the gradient of :class:`Conv2d` operation
  455. with respect to its input.
  456. Convolution usually reduces the size of input, while transposed convolution works
  457. the opposite way, transforming a smaller input to a larger output while preserving the
  458. connectivity pattern.
  459. :param in_channels: number of input channels.
  460. :param out_channels: number of output channels.
  461. :param kernel_size: size of weight on spatial dimensions. If ``kernel_size`` is
  462. an :class:`int`, the actual kernel size would be
  463. ``(kernel_size, kernel_size)``. Default: 1
  464. :param stride: stride of the 2D convolution operation. Default: 1
  465. :param padding: size of the paddings added to the input on both sides of its
  466. spatial dimensions. Only zero-padding is supported. Default: 0
  467. :param dilation: dilation of the 2D convolution operation. Default: 1
  468. :param groups: number of groups into which the input and output channels are divided,
  469. so as to perform a "grouped convolution". When ``groups`` is not 1,
  470. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  471. and there would be an extra dimension at the beginning of the weight's
  472. shape. Specifically, the shape of weight would be ``(groups,
  473. out_channels // groups, in_channels // groups, *kernel_size)``. Default: 1
  474. :param bias: wether to add a bias onto the result of convolution. Default:
  475. True
  476. :param conv_mode: Supports `cross_correlation`. Default:
  477. `cross_correlation`
  478. :param compute_mode: When set to "default", no special requirements will be
  479. placed on the precision of intermediate results. When set to "float32",
  480. "float32" would be used for accumulator and intermediate result, but only
  481. effective when input and output are of float16 dtype.
  482. """
  483. def __init__(
  484. self,
  485. in_channels: int,
  486. out_channels: int,
  487. kernel_size: Union[int, Tuple[int, int]],
  488. stride: Union[int, Tuple[int, int]] = 1,
  489. padding: Union[int, Tuple[int, int]] = 0,
  490. dilation: Union[int, Tuple[int, int]] = 1,
  491. groups: int = 1,
  492. bias: bool = True,
  493. conv_mode: str = "cross_correlation",
  494. compute_mode: str = "default",
  495. **kwargs
  496. ):
  497. kernel_size = _pair_nonzero(kernel_size)
  498. stride = _pair_nonzero(stride)
  499. padding = _pair(padding)
  500. dilation = _pair_nonzero(dilation)
  501. self.conv_mode = conv_mode
  502. self.compute_mode = compute_mode
  503. super().__init__(
  504. in_channels,
  505. out_channels,
  506. kernel_size,
  507. stride,
  508. padding,
  509. dilation,
  510. groups,
  511. bias,
  512. **kwargs,
  513. )
  514. def _get_fanin(self):
  515. kh, kw = self.kernel_size
  516. oc = self.out_channels
  517. return kh * kw * oc
  518. def _infer_weight_shape(self):
  519. group = self.groups
  520. ichl = self.in_channels
  521. ochl = self.out_channels
  522. kh, kw = self.kernel_size
  523. if group == 1:
  524. # Assume format is NCHW
  525. return (ichl, ochl, kh, kw)
  526. assert (
  527. ichl % group == 0 and ochl % group == 0
  528. ), "invalid config: input_channels={} output_channels={} group={}".format(
  529. ichl, ochl, group
  530. )
  531. # Assume format is NCHW
  532. return (group, ichl // group, ochl // group, kh, kw)
  533. def _infer_bias_shape(self):
  534. # Assume format is NCHW
  535. return (1, self.out_channels, 1, 1)
  536. def forward(self, inp):
  537. return conv_transpose2d(
  538. inp,
  539. self.weight,
  540. self.bias,
  541. self.stride,
  542. self.padding,
  543. self.dilation,
  544. self.groups,
  545. self.conv_mode,
  546. self.compute_mode,
  547. )
  548. class LocalConv2d(Conv2d):
  549. r"""
  550. Applies a spatial convolution with untied kernels over an groupped channeled input 4D tensor.
  551. It is also known as the locally connected layer.
  552. :param in_channels: number of input channels.
  553. :param out_channels: number of output channels.
  554. :param input_height: the height of the input images.
  555. :param input_width: the width of the input images.
  556. :param kernel_size: size of weight on spatial dimensions. If kernel_size is
  557. an :class:`int`, the actual kernel size would be
  558. `(kernel_size, kernel_size)`. Default: 1
  559. :param stride: stride of the 2D convolution operation. Default: 1
  560. :param padding: size of the paddings added to the input on both sides of its
  561. spatial dimensions. Only zero-padding is supported. Default: 0
  562. :param groups: number of groups into which the input and output channels are divided,
  563. so as to perform a "grouped convolution". When ``groups`` is not 1,
  564. ``in_channels`` and ``out_channels`` must be divisible by ``groups``.
  565. The shape of weight is `(groups, output_height, output_width,
  566. in_channels // groups, *kernel_size, out_channels // groups)`.
  567. """
  568. def __init__(
  569. self,
  570. in_channels: int,
  571. out_channels: int,
  572. input_height: int,
  573. input_width: int,
  574. kernel_size: Union[int, Tuple[int, int]],
  575. stride: Union[int, Tuple[int, int]] = 1,
  576. padding: Union[int, Tuple[int, int]] = 0,
  577. dilation: Union[int, Tuple[int, int]] = 1,
  578. groups: int = 1,
  579. conv_mode: str = "cross_correlation",
  580. **kwargs
  581. ):
  582. self.input_height = input_height
  583. self.input_width = input_width
  584. super().__init__(
  585. in_channels,
  586. out_channels,
  587. kernel_size,
  588. stride,
  589. padding,
  590. dilation,
  591. groups,
  592. bias=False,
  593. **kwargs,
  594. )
  595. def _infer_weight_shape(self):
  596. group = self.groups
  597. output_height = (
  598. self.input_height + self.padding[0] * 2 - self.kernel_size[0]
  599. ) // self.stride[0] + 1
  600. output_width = (
  601. self.input_width + self.padding[1] * 2 - self.kernel_size[1]
  602. ) // self.stride[1] + 1
  603. # Assume format is NCHW
  604. return (
  605. group,
  606. output_height,
  607. output_width,
  608. self.in_channels // group,
  609. self.kernel_size[0],
  610. self.kernel_size[1],
  611. self.out_channels // group,
  612. )
  613. def forward(self, inp):
  614. return local_conv2d(
  615. inp,
  616. self.weight,
  617. None,
  618. self.stride,
  619. self.padding,
  620. self.dilation,
  621. self.conv_mode,
  622. )
  623. class ConvRelu2d(Conv2d):
  624. r"""
  625. A fused :class:`~.Module` including :class:`~.module.Conv2d` and :func:`~.relu`.
  626. Could be replaced with :class:`~.QATModule` version :class:`~.qat.ConvRelu2d` using :func:`~.quantize.quantize_qat`.
  627. """
  628. def forward(self, inp):
  629. return relu(self.calc_conv(inp, self.weight, self.bias))
  630. class DeformableConv2d(_ConvNd):
  631. """
  632. Deformable Convolution.
  633. :param in_channels: number of input channels.
  634. :param out_channels: number of output channels.
  635. :param kernel_size: size of weight on spatial dimensions. If kernel_size is
  636. an :class:`int`, the actual kernel size would be
  637. `(kernel_size, kernel_size)`. Default: 1
  638. :param stride: stride of the 2D convolution operation. Default: 1
  639. :param padding: size of the paddings added to the input on both sides of its
  640. spatial dimensions. Only zero-padding is supported. Default: 0
  641. :param dilation: dilation of the 2D convolution operation. Default: 1
  642. :param groups: number of groups into which the input and output channels are divided,
  643. so as to perform a "grouped convolution". When ``groups`` is not 1,
  644. ``in_channels`` and ``out_channels`` must be divisible by ``groups``,
  645. and there would be an extra dimension at the beginning of the weight's
  646. shape. Specifically, the shape of weight would be `(groups,
  647. out_channel // groups, in_channels // groups, *kernel_size)`.
  648. :param bias: whether to add a bias onto the result of convolution. Default:
  649. True
  650. :param conv_mode: Supports `cross_correlation`. Default:
  651. `cross_correlation`
  652. :param compute_mode: When set to "default", no special requirements will be
  653. placed on the precision of intermediate results. When set to "float32",
  654. "float32" would be used for accumulator and intermediate result, but only
  655. effective when input and output are of float16 dtype.
  656. """
  657. def __init__(
  658. self,
  659. in_channels: int,
  660. out_channels: int,
  661. kernel_size: Union[int, Tuple[int, int]],
  662. stride: Union[int, Tuple[int, int]] = 1,
  663. padding: Union[int, Tuple[int, int]] = 0,
  664. dilation: Union[int, Tuple[int, int]] = 1,
  665. groups: int = 1,
  666. bias: bool = True,
  667. conv_mode: str = "cross_correlation",
  668. compute_mode: str = "default",
  669. **kwargs
  670. ):
  671. kernel_size = _pair_nonzero(kernel_size)
  672. stride = _pair_nonzero(stride)
  673. padding = _pair(padding)
  674. dilation = _pair_nonzero(dilation)
  675. self.conv_mode = conv_mode
  676. self.compute_mode = compute_mode
  677. super().__init__(
  678. in_channels,
  679. out_channels,
  680. kernel_size,
  681. stride,
  682. padding,
  683. dilation,
  684. groups,
  685. bias,
  686. **kwargs,
  687. )
  688. def _get_fanin(self):
  689. kh, kw = self.kernel_size
  690. ic = self.in_channels
  691. return kh * kw * ic
  692. def _infer_weight_shape(self):
  693. group = self.groups
  694. ichl = self.in_channels
  695. ochl = self.out_channels
  696. kh, kw = self.kernel_size
  697. if group == 1:
  698. # Assume format is NCHW
  699. return (ochl, ichl, kh, kw)
  700. assert (
  701. ichl % group == 0 and ochl % group == 0
  702. ), "invalid config: input_channels={} output_channels={} group={}".format(
  703. ichl, ochl, group
  704. )
  705. # Assume format is NCHW
  706. return (group, ochl // group, ichl // group, kh, kw)
  707. def _infer_bias_shape(self):
  708. # Assume format is NCHW
  709. return (1, self.out_channels, 1, 1)
  710. def calc_conv(self, inp, weight, offset, mask, bias):
  711. return deformable_conv2d(
  712. inp,
  713. weight,
  714. offset,
  715. mask,
  716. bias,
  717. self.stride,
  718. self.padding,
  719. self.dilation,
  720. self.groups,
  721. self.conv_mode,
  722. self.compute_mode,
  723. )
  724. def forward(self, inp, offset, mask):
  725. return self.calc_conv(inp, self.weight, offset, mask, self.bias)
  726. class ConvTranspose3d(_ConvNd):
  727. r"""
  728. Applies a 3D transposed convolution over an input tensor.
  729. Only support the case that group = 1 and conv_mode = "cross_correlation".
  730. :class:`ConvTranspose3d` can be seen as the gradient of :class:`Conv3d` operation
  731. with respect to its input.
  732. Convolution3D usually reduces the size of input, while transposed convolution3d
  733. works the opposite way, transforming a smaller input to a larger output while
  734. preserving the connectivity pattern.
  735. :param in_channels: number of input channels.
  736. :param out_channels: number of output channels.
  737. :param kernel_size: size of weight on spatial dimensions. If ``kernel_size`` is
  738. an :class:`int`, the actual kernel size would be
  739. ``(kernel_size, kernel_size, kernel_size)``. Default: 1
  740. :param stride: stride of the 3D convolution operation. Default: 1
  741. :param padding: size of the paddings added to the input on all sides of its
  742. spatial dimensions. Only zero-padding is supported. Default: 0
  743. :param dilation: dilation of the 3D convolution operation. Default: 1
  744. :param bias: wether to add a bias onto the result of convolution. Default:
  745. True
  746. """
  747. def __init__(
  748. self,
  749. in_channels: int,
  750. out_channels: int,
  751. kernel_size: Union[int, Tuple[int, int, int]],
  752. stride: Union[int, Tuple[int, int, int]] = 1,
  753. padding: Union[int, Tuple[int, int, int]] = 0,
  754. dilation: Union[int, Tuple[int, int, int]] = 1,
  755. bias: bool = True,
  756. ):
  757. kernel_size = _triple_nonzero(kernel_size)
  758. stride = _triple_nonzero(stride)
  759. padding = _triple(padding)
  760. dilation = _triple_nonzero(dilation)
  761. super().__init__(
  762. in_channels=in_channels,
  763. out_channels=out_channels,
  764. kernel_size=kernel_size,
  765. stride=stride,
  766. padding=padding,
  767. dilation=dilation,
  768. groups=1,
  769. bias=bias,
  770. )
  771. def _get_fanin(self):
  772. kt, kh, kw = self.kernel_size
  773. ic = self.in_channels
  774. return kt * kh * kw * ic
  775. def _infer_weight_shape(self):
  776. ichl = self.in_channels
  777. ochl = self.out_channels
  778. kt, kh, kw = self.kernel_size
  779. return (ochl, ichl, kt, kh, kw)
  780. def _infer_bias_shape(self):
  781. # Assume format is NCTHW
  782. return (1, self.out_channels, 1, 1, 1)
  783. def forward(self, inp):
  784. return conv_transpose3d(
  785. inp, self.weight, self.bias, self.stride, self.padding, self.dilation,
  786. )

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