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

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

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