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

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