conv.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # TODO: define classes of convolutional neural network
  15. import numpy as np
  16. from paddle import get_flags
  17. from ...device import (
  18. get_cudnn_version,
  19. is_compiled_with_cuda,
  20. is_compiled_with_rocm,
  21. )
  22. from ...utils import convert_to_list
  23. from .. import functional as F
  24. from ..functional.conv import _update_padding_nd
  25. from ..initializer import Normal
  26. from .layers import Layer
  27. __all__ = []
  28. def _get_default_param_initializer(num_channels, filter_size):
  29. filter_elem_num = num_channels * np.prod(filter_size)
  30. std = (2.0 / filter_elem_num) ** 0.5
  31. return Normal(0.0, std)
  32. def _reverse_repeat_list(t, n):
  33. """Reverse the order of `t` and repeat each element for `n` times.
  34. This can be used to translate padding arg used by Conv and Pooling modules
  35. to the ones used by `F.pad`.
  36. """
  37. return [x for x in reversed(t) for _ in range(n)]
  38. class _ConvNd(Layer):
  39. def __init__(
  40. self,
  41. in_channels,
  42. out_channels,
  43. kernel_size,
  44. transposed,
  45. dims,
  46. stride=1,
  47. padding=0,
  48. padding_mode='zeros',
  49. output_padding=0,
  50. dilation=1,
  51. groups=1,
  52. weight_attr=None,
  53. bias_attr=None,
  54. data_format="NCHW",
  55. ):
  56. super().__init__()
  57. assert (
  58. weight_attr is not False
  59. ), "weight_attr should not be False in Conv."
  60. self._param_attr = weight_attr
  61. self._bias_attr = bias_attr
  62. self._groups = groups
  63. self._in_channels = in_channels
  64. self._out_channels = out_channels
  65. self._data_format = data_format
  66. valid_padding_modes = {'zeros', 'reflect', 'replicate', 'circular'}
  67. if padding_mode not in valid_padding_modes:
  68. raise ValueError(
  69. f"padding_mode must be one of {valid_padding_modes}, but got padding_mode='{padding_mode}'"
  70. )
  71. if padding_mode in {
  72. 'reflect',
  73. 'replicate',
  74. 'circular',
  75. } and not isinstance(padding, int):
  76. raise TypeError(
  77. "when padding_mode in ['reflect', 'replicate', 'circular'], type of padding must be int"
  78. )
  79. valid_format = {'NHWC', 'NCHW', 'NDHWC', 'NCDHW', 'NLC', 'NCL'}
  80. if data_format not in valid_format:
  81. raise ValueError(
  82. f"data_format must be one of {valid_format}, but got data_format='{data_format}'"
  83. )
  84. channel_last = (
  85. (data_format == "NHWC")
  86. or (data_format == "NDHWC")
  87. or (data_format == "NLC")
  88. )
  89. if channel_last:
  90. self._channel_dim = len(data_format) - 1
  91. else:
  92. self._channel_dim = 1
  93. self._stride = convert_to_list(stride, dims, 'stride')
  94. self._dilation = convert_to_list(dilation, dims, 'dilation')
  95. self._kernel_size = convert_to_list(kernel_size, dims, 'kernel_size')
  96. self._padding = padding
  97. self._padding_mode = padding_mode
  98. self.output_padding = output_padding
  99. if dims != 1:
  100. self._updated_padding, self._padding_algorithm = _update_padding_nd(
  101. padding, channel_last, dims
  102. )
  103. if transposed:
  104. filter_shape = [
  105. self._in_channels,
  106. out_channels // groups,
  107. ] + self._kernel_size
  108. else:
  109. if in_channels % groups != 0:
  110. raise ValueError("in_channels must be divisible by groups.")
  111. if padding_mode in {'reflect', 'replicate', 'circular'}:
  112. _paired_padding = convert_to_list(padding, dims, 'padding')
  113. self._reversed_padding_repeated_twice = _reverse_repeat_list(
  114. _paired_padding, 2
  115. )
  116. (
  117. self._updated_padding,
  118. self._padding_algorithm,
  119. ) = _update_padding_nd(0, channel_last, dims)
  120. filter_shape = [
  121. out_channels,
  122. in_channels // groups,
  123. ] + self._kernel_size
  124. def _get_default_param_initializer():
  125. if transposed:
  126. return None
  127. filter_elem_num = np.prod(self._kernel_size) * self._in_channels
  128. std = (2.0 / filter_elem_num) ** 0.5
  129. return Normal(0.0, std)
  130. self.weight = self.create_parameter(
  131. shape=filter_shape,
  132. attr=self._param_attr,
  133. default_initializer=_get_default_param_initializer(),
  134. )
  135. self.bias = self.create_parameter(
  136. attr=self._bias_attr, shape=[self._out_channels], is_bias=True
  137. )
  138. cudnn_version = get_cudnn_version()
  139. self._use_cudnn = (
  140. True
  141. if (is_compiled_with_cuda() and cudnn_version is not None)
  142. else False
  143. )
  144. self._op_type = "conv" + str(dims) + 'd'
  145. if self._op_type == 'conv2d' and (
  146. in_channels == groups
  147. and in_channels != 1
  148. and out_channels % in_channels == 0
  149. ):
  150. self._op_type = 'depthwise_conv2d'
  151. if is_compiled_with_rocm():
  152. self._use_cudnn = True
  153. else:
  154. self._use_cudnn = False
  155. if (
  156. is_compiled_with_cuda()
  157. and get_flags("FLAGS_conv2d_disable_cudnn")[
  158. "FLAGS_conv2d_disable_cudnn"
  159. ]
  160. ):
  161. self._use_cudnn = False
  162. def extra_repr(self):
  163. main_str = '{_in_channels}, {_out_channels}, kernel_size={_kernel_size}'
  164. if self._stride != [1] * len(self._stride):
  165. main_str += ', stride={_stride}'
  166. if self._padding != 0:
  167. main_str += ', padding={_padding}'
  168. if self._padding_mode != 'zeros':
  169. main_str += ', padding_mode={_padding_mode}'
  170. if self.output_padding != 0:
  171. main_str += ', output_padding={output_padding}'
  172. if self._dilation != [1] * len(self._dilation):
  173. main_str += ', dilation={_dilation}'
  174. if self._groups != 1:
  175. main_str += ', groups={_groups}'
  176. main_str += ', data_format={_data_format}'
  177. return main_str.format(**self.__dict__)
  178. class Conv1D(_ConvNd):
  179. r"""
  180. This interface is used to construct a callable object of the ``Conv1D`` class.
  181. For more details, refer to code examples.
  182. The convolution1D layer calculates the output based on the input, filter
  183. and stride, padding, dilation, groups parameters. Input and
  184. Output are in NCL format or NLC format, where N is batch size, C is the number of
  185. the feature map, L is the length of the feature map.
  186. Filter's shape is [MCK] , where M is the number of output feature map,
  187. C is the number of input feature map, K is the size of the kernel.
  188. If the groups is greater than 1, C will equal the number of input feature map divided by the groups.
  189. If bias attribution and activation type are provided, bias is added to the
  190. output of the convolution, and the corresponding activation function is
  191. applied to the final result.
  192. For each input :math:`X` , the equation is:
  193. .. math::
  194. Out = \sigma (W \ast X + b)
  195. Where:
  196. * :math:`X`: Input value, a ``Tensor`` with 'NCL' format or 'NLC' format.
  197. * :math:`W`: Filter value, a ``Tensor`` with shape [MCK] .
  198. * :math:`\ast`: Convolution operation.
  199. * :math:`b`: Bias value, a 1-D ``Tensor`` with shape [M].
  200. * :math:`\sigma`: Activation function.
  201. * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
  202. Example:
  203. - Input:
  204. Input shape: :math:`(N, C_{in}, L_{in})`
  205. Kernel shape: :math:`(C_{out}, C_{in}, K)`
  206. - Output:
  207. Output shape: :math:`(N, C_{out}, L_{out})`
  208. Where
  209. .. math::
  210. L_{out}&= \frac{(L_{in} + 2 * padding - (dilation * (L_f - 1) + 1))}{stride} + 1
  211. Parameters:
  212. in_channels(int): The number of channels in the input image.
  213. out_channels(int): The number of filter. It is as same as the output
  214. feature map.
  215. kernel_size (int|tuple|list): The filter size. If kernel_size is a tuple/list,
  216. it must contain one integer, (kernel_size).
  217. stride (int|tuple|list, optional): The stride size. If stride is a tuple/list, it must
  218. contain one integer, (stride_size). Default: 1.
  219. padding(int|str|tuple|list, optional): The size of zeros to be padded. It must be in one of the following forms.
  220. 1. a string in ['valid', 'same'].
  221. 2. an int, which means the feature map is zero paded by size of `padding` on both sides.
  222. 3. a list[int] or tuple[int] whose length is 1, which means the feature map is zero paded by size of `padding[0]` on both sides.
  223. The default value is 0.
  224. dilation (int|tuple|list, optional): The dilation size. If dilation is a tuple/list, it must
  225. contain one integer, (dilation_size). Default: 1.
  226. groups (int, optional): The groups number of the conv2d Layer. According to grouped
  227. convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
  228. the first half of the filters is only connected to the first half
  229. of the input channels, while the second half of the filters is only
  230. connected to the second half of the input channels. Default: 1.
  231. padding_mode(str, optional): Four modes: 'zeros', 'reflect', 'replicate', 'circular'.
  232. When in 'zeros' mode, this op uses zeros to pad the input tensor.
  233. When in 'reflect' mode, uses reflection of the input boundaries to pad the input tensor.
  234. When in 'replicate' mode, uses input boundaries to pad the input tensor.
  235. When in 'circular' mode, uses circular input to pad the input tensor.
  236. Default is 'zeros'.
  237. weight_attr (ParamAttr, optional): The parameter attribute for learnable weights(Parameter)
  238. of conv1d. If it is set to None or one attribute of ParamAttr, conv1d
  239. will create ParamAttr as param_attr. If the Initializer of the param_attr
  240. is not set, the parameter is initialized with :math:`Normal(0.0, std)`,
  241. and the :math:`std` is :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. Default: None.
  242. bias_attr (ParamAttr or bool, optional): The attribute for the bias of conv1d.
  243. If it is set to False, no bias will be added to the output units.
  244. If it is set to None or one attribute of ParamAttr, conv1d
  245. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  246. is not set, the bias is initialized zero. Default: None.
  247. Attribute:
  248. **weight** (Parameter): the learnable weights of filter of this layer.
  249. **bias** (Parameter or None): the learnable bias of this layer.
  250. Shape:
  251. - x: 3-D tensor with shape: (batch, in_channels, length) or (batch, length, in_channels).
  252. - weight: 3-D tensor with shape: (out_channels, in_channels, kernel_size)
  253. - bias: 1-D tensor with shape: (out_channels)
  254. - output: 3-D tensor with same shape as input x.
  255. Examples:
  256. .. code-block:: python
  257. >>> import paddle
  258. >>> from paddle.nn import Conv1D
  259. >>> x = paddle.to_tensor([[[4, 8, 1, 9],
  260. ... [7, 2, 0, 9],
  261. ... [6, 9, 2, 6]]], dtype="float32")
  262. >>> w = paddle.to_tensor([[[9, 3, 4],
  263. ... [0, 0, 7],
  264. ... [2, 5, 6]],
  265. ... [[0, 3, 4],
  266. ... [2, 9, 7],
  267. ... [5, 6, 8]]], dtype="float32")
  268. >>> conv = Conv1D(3, 2, 3)
  269. >>> conv.weight.set_value(w)
  270. >>> y = conv(x)
  271. >>> print(y)
  272. Tensor(shape=[1, 2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
  273. [[[133., 238.],
  274. [160., 211.]]])
  275. """
  276. def __init__(
  277. self,
  278. in_channels,
  279. out_channels,
  280. kernel_size,
  281. stride=1,
  282. padding=0,
  283. dilation=1,
  284. groups=1,
  285. padding_mode='zeros',
  286. weight_attr=None,
  287. bias_attr=None,
  288. data_format="NCL",
  289. ):
  290. super().__init__(
  291. in_channels,
  292. out_channels,
  293. kernel_size,
  294. False,
  295. 1,
  296. stride=stride,
  297. padding=padding,
  298. padding_mode=padding_mode,
  299. dilation=dilation,
  300. groups=groups,
  301. weight_attr=weight_attr,
  302. bias_attr=bias_attr,
  303. data_format=data_format,
  304. )
  305. def forward(self, x):
  306. padding = 0
  307. if self._padding_mode != "zeros":
  308. x = F.pad(
  309. x,
  310. self._reversed_padding_repeated_twice,
  311. mode=self._padding_mode,
  312. data_format=self._data_format,
  313. )
  314. else:
  315. padding = self._padding
  316. out = F.conv1d(
  317. x,
  318. self.weight,
  319. bias=self.bias,
  320. padding=padding,
  321. stride=self._stride,
  322. dilation=self._dilation,
  323. groups=self._groups,
  324. data_format=self._data_format,
  325. )
  326. return out
  327. class Conv1DTranspose(_ConvNd):
  328. r"""
  329. This interface is used to construct a callable object of the ``Conv1DTranspose`` class.
  330. For more details, refer to code examples.
  331. The 1-D convolution transpose layer calculates the output based on the input,
  332. filter, and dilation, stride, padding. Input(Input) and output(Output)
  333. are in 'NCL' format or 'NLC' where N is batch size, C is the number of channels,
  334. L is the length of the feature. The details of convolution transpose
  335. layer, please refer to the following explanation and references
  336. `therein <https://arxiv.org/pdf/1603.07285.pdf>`_.
  337. If bias attribution and activation type are provided, bias is added to
  338. the output of the convolution, and the corresponding activation function
  339. is applied to the final result.
  340. For each input :math:`X`, the equation is:
  341. .. math::
  342. Out = \sigma (W \ast X + b)
  343. Where:
  344. * :math:`X`: Input value, a 3-D Tensor with 'NCL' format or 'NLC' format.
  345. * :math:`W`: Kernel value, a 3-D Tensor with 'MCK' format.
  346. * :math:`\ast`: Convolution operation.
  347. * :math:`b`: Bias value, a 2-D Tensor with shape [M, 1].
  348. * :math:`\sigma`: Activation function.
  349. * :math:`Out`: Output value, a 3-D Tensor with data format 'NCL' of 'NLC', the shape of :math:`Out` and :math:`X` may be different.
  350. Example:
  351. - Input:
  352. Input shape: :math:`(N, C_{in}, L_{in})`
  353. Filter shape: :math:`(C_{in}, C_{out}, L_f)`
  354. - Output:
  355. Output shape: :math:`(N, C_{out}, L_{out})`
  356. Where
  357. .. math::
  358. L^\prime_{out} &= (L_{in} - 1) * stride - 2 * padding + dilation * (L_f - 1) + 1 \\
  359. L_{out} &\in [ L^\prime_{out}, L^\prime_{out} + stride ]
  360. Note:
  361. The conv1d_transpose can be seen as the backward of the conv1d. For conv1d,
  362. when stride > 1, conv1d maps multiple input shape to the same output shape,
  363. so for conv1d_transpose, when stride > 1, input shape maps multiple output shape.
  364. If output_size is None, :math:`L_{out} = L^\prime_{out}`;
  365. else, the :math:`L_{out}` of the output size must between :math:`L^\prime_{out}`
  366. and :math:`L^\prime_{out} + stride`.
  367. Args:
  368. in_channels(int): The number of channels in the input image.
  369. out_channels(int): The number of the filter. It is as same as the output
  370. feature map.
  371. kernel_size(int|tuple|list): The filter size. If kernel_size is a tuple/list,
  372. it must contain one integers, (kernel_size). None if
  373. use output size to calculate kernel_size. Default: None. kernel_size and
  374. output_size should not be None at the same time.
  375. stride(int|tuple|list, optional): The stride size. It means the stride in transposed convolution.
  376. If stride is a tuple/list, it must contain one integer, (stride_size).
  377. Default: stride = 1.
  378. padding(int|list|str|tuple, optional): The padding size. The padding argument effectively adds
  379. `dilation * (kernel - 1)` amount of zero-padding on both sides of input. If `padding` is a
  380. string, either 'VALID' or 'SAME' supported, which is the padding algorithm.
  381. If `padding` is a tuple or list, it could be in two forms:
  382. `[pad]` or `[pad_left, pad_right]`. Default: padding = 0.
  383. output_padding(int|list|tuple, optional): The count of zeros to be added to tail of each dimension.
  384. If it is a tuple/list, it must contain one integer. Default: 0.
  385. groups(int, optional): The groups number of the Conv2D transpose layer. Inspired by
  386. grouped convolution in Alex Krizhevsky's Deep CNN paper, in which
  387. when group=2, the first half of the filters is only connected to the
  388. first half of the input channels, while the second half of the
  389. filters is only connected to the second half of the input channels.
  390. Default: groups = 1.
  391. bias(bool, optional): Whether to use bias. Default: True.
  392. dilation(int|tuple|list, optional): The dilation size. It means the spacing between the kernel points.
  393. If dilation is a tuple/list, it must contain one integer, (dilation_size).
  394. Default: dilation = 1.
  395. weight_attr (ParamAttr, optional): The parameter attribute for learnable parameters/weights
  396. of conv1d_transpose. If it is set to None or one attribute of ParamAttr, conv1d_transpose
  397. will create ParamAttr as param_attr. If the Initializer of the param_attr
  398. is not set, the parameter is initialized with Xavier. Default: None.
  399. bias_attr (ParamAttr|bool, optional): The parameter attribute for the bias of conv1d_transpose.
  400. If it is set to False, no bias will be added to the output units.
  401. If it is set to None or one attribute of ParamAttr, conv1d_transpose
  402. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  403. is not set, the bias is initialized zero. Default: None.
  404. Attribute:
  405. **weight** (Parameter): the learnable weights of filters of this layer.
  406. **bias** (Parameter or None): the learnable bias of this layer.
  407. Shape:
  408. - x(Tensor): 3-D tensor with shape (batch, in_channels, length) when data_format is "NCL" or shape (batch, length, in_channels) when data_format is "NLC".
  409. - weight(Tensor): 3-D tensor with shape (in_channels, out_channels, kernel_length).
  410. - bias(Tensor): 1-D tensor with shape (out_channels).
  411. - output_size(int|tuple|list, optional): The output image size. If output size is a tuple/list, it must contain one integer, (feature_length). None if use kernel_size, padding, output_padding and stride to calculate output_size. If output_size and kernel_size are specified at the same time, They should follow the formula above. Default: None. output_size and kernel_size should not be None at the same time.
  412. - output(Tensor): 3-D tensor with same shape as input x.
  413. Examples:
  414. .. code-block:: python
  415. >>> import paddle
  416. >>> from paddle.nn import Conv1DTranspose
  417. >>> # shape: (1, 2, 4)
  418. >>> x = paddle.to_tensor([[[4, 0, 9, 7],
  419. ... [8, 0, 9, 2]]], dtype="float32")
  420. >>> print(x.shape)
  421. [1, 2, 4]
  422. >>> # shape: (2, 1, 2)
  423. >>> w = paddle.to_tensor([[[7, 0]],
  424. ... [[4, 2]]], dtype="float32")
  425. >>> print(w.shape)
  426. [2, 1, 2]
  427. >>> conv = Conv1DTranspose(2, 1, 2)
  428. >>> conv.weight.set_value(w)
  429. >>> y = conv(x)
  430. >>> print(y)
  431. Tensor(shape=[1, 1, 5], dtype=float32, place=Place(cpu), stop_gradient=False,
  432. [[[60., 16., 99., 75., 4. ]]])
  433. """
  434. def __init__(
  435. self,
  436. in_channels,
  437. out_channels,
  438. kernel_size,
  439. stride=1,
  440. padding=0,
  441. output_padding=0,
  442. groups=1,
  443. dilation=1,
  444. weight_attr=None,
  445. bias_attr=None,
  446. data_format="NCL",
  447. ):
  448. super().__init__(
  449. in_channels,
  450. out_channels,
  451. kernel_size,
  452. True,
  453. 1,
  454. stride=stride,
  455. padding=padding,
  456. dilation=dilation,
  457. output_padding=output_padding,
  458. groups=groups,
  459. weight_attr=weight_attr,
  460. bias_attr=bias_attr,
  461. data_format=data_format,
  462. )
  463. def forward(self, x, output_size=None):
  464. out = F.conv1d_transpose(
  465. x,
  466. self.weight,
  467. bias=self.bias,
  468. output_size=output_size,
  469. output_padding=self.output_padding,
  470. padding=self._padding,
  471. stride=self._stride,
  472. dilation=self._dilation,
  473. groups=self._groups,
  474. data_format=self._data_format,
  475. )
  476. return out
  477. class Conv2D(_ConvNd):
  478. r"""
  479. This interface is used to construct a callable object of the ``Conv2D`` class.
  480. For more details, refer to code examples.
  481. The convolution2D layer calculates the output based on the input, filter
  482. and strides, paddings, dilations, groups parameters. Input and
  483. Output are in NCHW format, where N is batch size, C is the number of
  484. the feature map, H is the height of the feature map, and W is the width of the feature map.
  485. Filter's shape is [MCHW] , where M is the number of output feature map,
  486. C is the number of input feature map, H is the height of the filter,
  487. and W is the width of the filter. If the groups is greater than 1,
  488. C will equal the number of input feature map divided by the groups.
  489. Please refer to UFLDL's `convolution
  490. <http://ufldl.stanford.edu/tutorial/supervised/FeatureExtractionUsingConvolution/>`_
  491. for more details.
  492. If bias attribution and activation type are provided, bias is added to the
  493. output of the convolution, and the corresponding activation function is
  494. applied to the final result.
  495. For each input :math:`X`, the equation is:
  496. .. math::
  497. Out = \sigma (W \ast X + b)
  498. Where:
  499. * :math:`X`: Input value, a ``Tensor`` with NCHW format.
  500. * :math:`W`: Filter value, a ``Tensor`` with shape [MCHW] .
  501. * :math:`\ast`: Convolution operation.
  502. * :math:`b`: Bias value, a 1-D ``Tensor`` with shape [M].
  503. * :math:`\sigma`: Activation function.
  504. * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
  505. Parameters:
  506. in_channels(int): The number of input channels in the input image.
  507. out_channels(int): The number of output channels produced by the convolution.
  508. kernel_size(int|list|tuple): The size of the convolving kernel.
  509. stride(int|list|tuple, optional): The stride size. If stride is a list/tuple, it must
  510. contain two integers, (stride_H, stride_W). Otherwise, the
  511. stride_H = stride_W = stride. The default value is 1.
  512. padding(int|str|tuple|list, optional): The padding size. Padding coule be in one of the following forms.
  513. 1. a string in ['valid', 'same'].
  514. 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of `padding`
  515. 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, ...].
  516. 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, ...] for all spartial dimensions.
  517. 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0).
  518. The default value is 0.
  519. dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must
  520. contain two integers, (dilation_H, dilation_W). Otherwise, the
  521. dilation_H = dilation_W = dilation. The default value is 1.
  522. groups(int, optional): The groups number of the Conv2D Layer. According to grouped
  523. convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
  524. the first half of the filters is only connected to the first half
  525. of the input channels, while the second half of the filters is only
  526. connected to the second half of the input channels. The default value is 1.
  527. padding_mode(str, optional): ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'zeros'``.
  528. weight_attr(ParamAttr, optional): The parameter attribute for learnable parameters/weights
  529. of conv2d. If it is set to None or one attribute of ParamAttr, conv2d
  530. will create ParamAttr as param_attr. If it is set to None, the parameter
  531. is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is
  532. :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. The default value is None.
  533. bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of conv2d.
  534. If it is set to False, no bias will be added to the output units.
  535. If it is set to None or one attribute of ParamAttr, conv2d
  536. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  537. is not set, the bias is initialized zero. The default value is None.
  538. data_format(str, optional): Data format that specifies the layout of input.
  539. It can be "NCHW" or "NHWC". Default: "NCHW".
  540. Attribute:
  541. **weight** (Parameter): the learnable weights of filter of this layer.
  542. **bias** (Parameter or None): the learnable bias of this layer.
  543. Shape:
  544. - x: :math:`(N, C_{in}, H_{in}, W_{in})`
  545. - weight: :math:`(C_{out}, C_{in}, K_{h}, K_{w})`
  546. - bias: :math:`(C_{out})`
  547. - output: :math:`(N, C_{out}, H_{out}, W_{out})`
  548. Where
  549. .. math::
  550. H_{out}&= \frac{(H_{in} + 2 * paddings[0] - (dilations[0] * (kernel\_size[0] - 1) + 1))}{strides[0]} + 1
  551. W_{out}&= \frac{(W_{in} + 2 * paddings[1] - (dilations[1] * (kernel\_size[1] - 1) + 1))}{strides[1]} + 1
  552. Examples:
  553. .. code-block:: python
  554. >>> import paddle
  555. >>> import paddle.nn as nn
  556. >>> paddle.disable_static()
  557. >>> x_var = paddle.uniform((2, 4, 8, 8), dtype='float32', min=-1., max=1.)
  558. >>> conv = nn.Conv2D(4, 6, (3, 3))
  559. >>> y_var = conv(x_var)
  560. >>> print(y_var.shape)
  561. [2, 6, 6, 6]
  562. """
  563. def __init__(
  564. self,
  565. in_channels,
  566. out_channels,
  567. kernel_size,
  568. stride=1,
  569. padding=0,
  570. dilation=1,
  571. groups=1,
  572. padding_mode='zeros',
  573. weight_attr=None,
  574. bias_attr=None,
  575. data_format="NCHW",
  576. ):
  577. super().__init__(
  578. in_channels,
  579. out_channels,
  580. kernel_size,
  581. False,
  582. 2,
  583. stride=stride,
  584. padding=padding,
  585. padding_mode=padding_mode,
  586. dilation=dilation,
  587. groups=groups,
  588. weight_attr=weight_attr,
  589. bias_attr=bias_attr,
  590. data_format=data_format,
  591. )
  592. def forward(self, x):
  593. if self._padding_mode != 'zeros':
  594. x = F.pad(
  595. x,
  596. self._reversed_padding_repeated_twice,
  597. mode=self._padding_mode,
  598. data_format=self._data_format,
  599. )
  600. out = F.conv._conv_nd(
  601. x,
  602. self.weight,
  603. bias=self.bias,
  604. stride=self._stride,
  605. padding=self._updated_padding,
  606. padding_algorithm=self._padding_algorithm,
  607. dilation=self._dilation,
  608. groups=self._groups,
  609. data_format=self._data_format,
  610. channel_dim=self._channel_dim,
  611. op_type=self._op_type,
  612. use_cudnn=self._use_cudnn,
  613. )
  614. return out
  615. class Conv2DTranspose(_ConvNd):
  616. r"""
  617. This interface is used to construct a callable object of the ``Conv2DTranspose`` class.
  618. For more details, refer to code examples.
  619. The convolution2D transpose layer calculates the output based on the input,
  620. filter, and dilations, strides, paddings. Input and output
  621. are in NCHW format. Where N is batch size, C is the number of feature map,
  622. H is the height of the feature map, and W is the width of the feature map.
  623. Filter's shape is [CMHW] , where C is the number of input feature map,
  624. M is the number of output feature map, H is the height of the filter,
  625. and W is the width of the filter. If the groups is greater than 1,
  626. C will equal the number of input feature map divided by the groups.
  627. If bias attribution and activation type are provided, bias is added to
  628. the output of the convolution, and the corresponding activation function
  629. is applied to the final result.
  630. The details of convolution transpose layer, please refer to the following explanation and references
  631. `conv2dtranspose <https://arxiv.org/pdf/1603.07285.pdf>`_ .
  632. For each input :math:`X`, the equation is:
  633. .. math::
  634. Out = \sigma (W \ast X + b)
  635. Where:
  636. * :math:`X`: Input value, a ``Tensor`` with NCHW format.
  637. * :math:`W`: Filter value, a ``Tensor`` with shape [CMHW] .
  638. * :math:`\ast`: Convolution operation.
  639. * :math:`b`: Bias value, a 1-D ``Tensor`` with shape [M].
  640. * :math:`\sigma`: Activation function.
  641. * :math:`Out`: Output value, a 4-D ``Tensor`` with NCHW or NHWC format, the shape of :math:`Out` and :math:`X` may be different.
  642. Note:
  643. If output_size is None, :math:`H_{out}` = :math:`H^\prime_{out}` , :math:`W_{out}` = :math:`W^\prime_{out}`. Otherwise, the specified output_size_height (the height of the output feature layer) :math:`H_{out}` should be between :math:`H^\prime_{out}` and :math:`H^\prime_{out} + strides[0]` (excluding :math:`H^\prime_{out} + strides[0]` ).
  644. Parameters:
  645. in_channels(int): The number of channels in the input image.
  646. out_channels(int): The number of channels produced by the convolution.
  647. kernel_size(int|list|tuple): The kernel size. If kernel_size is a list/tuple,
  648. it must contain two integers, (kernel_size_H, kernel_size_W).
  649. Otherwise, the kernel will be a square.
  650. stride(int|list|tuple, optional): The stride size. If stride is a list/tuple, it must
  651. contain two integers, (stride_H, stride_W). Otherwise, the
  652. stride_H = stride_W = stride. Default: 1.
  653. padding(int|str|tuple|list, optional): The padding size. Padding coule be in one of the following forms.
  654. 1. a string in ['valid', 'same'].
  655. 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of `padding` on both sides
  656. 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, ...].
  657. 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, ...] for all spartial dimensions.
  658. 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0).
  659. The default value is 0.
  660. output_padding(int|list|tuple, optional): Additional size added to one side
  661. of each dimension in the output shape. Default: 0.
  662. dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must
  663. contain two integers, (dilation_H, dilation_W). Otherwise, the
  664. dilation_H = dilation_W = dilation. Default: 1.
  665. groups(int, optional): The groups number of the Conv2D transpose layer. Inspired by
  666. grouped convolution in Alex Krizhevsky's Deep CNN paper, in which
  667. when group=2, the first half of the filters is only connected to the
  668. first half of the input channels, while the second half of the
  669. filters is only connected to the second half of the input channels.
  670. Default: 1.
  671. weight_attr(ParamAttr, optional): The parameter attribute for learnable weights(Parameter)
  672. of conv2d_transpose. If it is set to None or one attribute of ParamAttr, conv2d_transpose
  673. will create ParamAttr as param_attr. If the Initializer of the param_attr
  674. is not set, the parameter is initialized with Xavier. Default: None.
  675. bias_attr(ParamAttr|bool, optional): The attribute for the bias of conv2d_transpose.
  676. If it is set to False, no bias will be added to the output units.
  677. If it is set to None or one attribute of ParamAttr, conv2d_transpose
  678. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  679. is not set, the bias is initialized zero. Default: None.
  680. data_format(str, optional): Data format that specifies the layout of input.
  681. It can be "NCHW" or "NHWC". Default: "NCHW".
  682. Attribute:
  683. **weight** (Parameter): the learnable weights of filters of this layer.
  684. **bias** (Parameter or None): the learnable bias of this layer.
  685. Shape:
  686. - x: :math:`(N, C_{in}, H_{in}, W_{in})`
  687. - weight: :math:`(C_{in}, C_{out}, K_{h}, K_{w})`
  688. - bias: :math:`(C_{out})`
  689. - output: :math:`(N, C_{out}, H_{out}, W_{out})`
  690. Where
  691. .. math::
  692. H^\prime_{out} &= (H_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (kernel\_size[0] - 1) + 1
  693. W^\prime_{out} &= (W_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (kernel\_size[1] - 1) + 1
  694. H_{out} &\in [ H^\prime_{out}, H^\prime_{out} + strides[0] )
  695. W_{out} &\in [ W^\prime_{out}, W^\prime_{out} + strides[1] )
  696. Examples:
  697. .. code-block:: python
  698. >>> import paddle
  699. >>> import paddle.nn as nn
  700. >>> paddle.disable_static()
  701. >>> x_var = paddle.uniform((2, 4, 8, 8), dtype='float32', min=-1., max=1.)
  702. >>> conv = nn.Conv2DTranspose(4, 6, (3, 3))
  703. >>> y_var = conv(x_var)
  704. >>> print(y_var.shape)
  705. [2, 6, 10, 10]
  706. """
  707. def __init__(
  708. self,
  709. in_channels,
  710. out_channels,
  711. kernel_size,
  712. stride=1,
  713. padding=0,
  714. output_padding=0,
  715. dilation=1,
  716. groups=1,
  717. weight_attr=None,
  718. bias_attr=None,
  719. data_format="NCHW",
  720. ):
  721. super().__init__(
  722. in_channels,
  723. out_channels,
  724. kernel_size,
  725. True,
  726. 2,
  727. stride=stride,
  728. padding=padding,
  729. dilation=dilation,
  730. output_padding=output_padding,
  731. groups=groups,
  732. weight_attr=weight_attr,
  733. bias_attr=bias_attr,
  734. data_format=data_format,
  735. )
  736. def forward(self, x, output_size=None):
  737. if output_size is None:
  738. output_padding = self.output_padding
  739. else:
  740. output_padding = 0
  741. out = F.conv2d_transpose(
  742. x,
  743. self.weight,
  744. bias=self.bias,
  745. padding=self._padding,
  746. output_padding=output_padding,
  747. stride=self._stride,
  748. dilation=self._dilation,
  749. groups=self._groups,
  750. output_size=output_size,
  751. data_format=self._data_format,
  752. )
  753. return out
  754. class Conv3D(_ConvNd):
  755. r"""
  756. **Convlution3d Layer**
  757. The convolution3d layer calculates the output based on the input, filter
  758. and strides, paddings, dilations, groups parameters. Input(Input) and
  759. Output(Output) are multidimensional tensors with a shape of
  760. :math:`[N, C, D, H, W]` . Where N is batch size, C is the number of
  761. channels, D is the depth of the feature, H is the height of the feature,
  762. and W is the width of the feature. Convlution3D is similar with Convlution2D
  763. but adds one dimension(depth). If bias attribution and activation type are
  764. provided, bias is added to the output of the convolution, and the
  765. corresponding activation function is applied to the final result.
  766. For each input :math:`X`, the equation is:
  767. .. math::
  768. Out = \sigma (W \ast X + b)
  769. In the above equation:
  770. * :math:`X`: Input value, a tensor with NCDHW or NDHWC format.
  771. * :math:`W`: Filter value, a tensor with MCDHW format.
  772. * :math:`\ast`: Convolution operation.
  773. * :math:`b`: Bias value, a 1-D tensor with shape [M].
  774. * :math:`\sigma`: Activation function.
  775. * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
  776. Parameters:
  777. in_channels(int): The number of input channels in the input image.
  778. out_channels(int): The number of output channels produced by the convolution.
  779. kernel_size(int|list|tuple): The size of the convolving kernel.
  780. stride(int|list|tuple, optional): The stride size. If stride is a list/tuple, it must
  781. contain three integers, (stride_D, stride_H, stride_W). Otherwise, the
  782. stride_D = stride_H = stride_W = stride. The default value is 1.
  783. padding(int|str|tuple|list, optional): The padding size. Padding coule be in one of the following forms.
  784. 1. a string in ['valid', 'same'].
  785. 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of `padding`
  786. 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, ...].
  787. 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, ...] for all spartial dimensions.
  788. 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0).
  789. The default value is 0.
  790. dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must
  791. contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the
  792. dilation_D = dilation_H = dilation_W = dilation. The default value is 1.
  793. groups(int, optional): The groups number of the Conv3D Layer. According to grouped
  794. convolution in Alex Krizhevsky's Deep CNN paper: when group=2,
  795. the first half of the filters is only connected to the first half
  796. of the input channels, while the second half of the filters is only
  797. connected to the second half of the input channels. The default value is 1.
  798. padding_mode(str, optional): ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'zeros'``.
  799. weight_attr(ParamAttr, optional): The parameter attribute for learnable parameters/weights
  800. of conv3d. If it is set to None or one attribute of ParamAttr, conv3d
  801. will create ParamAttr as param_attr. If it is set to None, the parameter
  802. is initialized with :math:`Normal(0.0, std)`, and the :math:`std` is
  803. :math:`(\frac{2.0 }{filter\_elem\_num})^{0.5}`. The default value is None.
  804. bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of conv3d.
  805. If it is set to False, no bias will be added to the output units.
  806. If it is set to None or one attribute of ParamAttr, conv3d
  807. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  808. is not set, the bias is initialized zero. The default value is None.
  809. data_format(str, optional): Data format that specifies the layout of input.
  810. It can be "NCDHW" or "NDHWC". Default: "NCDHW".
  811. Attribute:
  812. **weight** (Parameter): the learnable weights of filters of this layer.
  813. **bias** (Parameter): the learnable bias of this layer.
  814. Shape:
  815. - x: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})`
  816. - weight: :math:`(C_{out}, C_{in}, K_{d}, K_{h}, K_{w})`
  817. - bias: :math:`(C_{out})`
  818. - output: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})`
  819. Where
  820. .. math::
  821. D_{out}&= \frac{(D_{in} + 2 * paddings[0] - (dilations[0] * (kernel\_size[0] - 1) + 1))}{strides[0]} + 1
  822. H_{out}&= \frac{(H_{in} + 2 * paddings[1] - (dilations[1] * (kernel\_size[1] - 1) + 1))}{strides[1]} + 1
  823. W_{out}&= \frac{(W_{in} + 2 * paddings[2] - (dilations[2] * (kernel\_size[2] - 1) + 1))}{strides[2]} + 1
  824. Examples:
  825. .. code-block:: python
  826. >>> import paddle
  827. >>> import paddle.nn as nn
  828. >>> paddle.disable_static()
  829. >>> x_var = paddle.uniform((2, 4, 8, 8, 8), dtype='float32', min=-1., max=1.)
  830. >>> conv = nn.Conv3D(4, 6, (3, 3, 3))
  831. >>> y_var = conv(x_var)
  832. >>> print(y_var.shape)
  833. [2, 6, 6, 6, 6]
  834. """
  835. def __init__(
  836. self,
  837. in_channels,
  838. out_channels,
  839. kernel_size,
  840. stride=1,
  841. padding=0,
  842. dilation=1,
  843. groups=1,
  844. padding_mode='zeros',
  845. weight_attr=None,
  846. bias_attr=None,
  847. data_format="NCDHW",
  848. ):
  849. super().__init__(
  850. in_channels,
  851. out_channels,
  852. kernel_size,
  853. False,
  854. 3,
  855. stride=stride,
  856. padding=padding,
  857. padding_mode=padding_mode,
  858. dilation=dilation,
  859. groups=groups,
  860. weight_attr=weight_attr,
  861. bias_attr=bias_attr,
  862. data_format=data_format,
  863. )
  864. def forward(self, x):
  865. if self._padding_mode != 'zeros':
  866. x = F.pad(
  867. x,
  868. self._reversed_padding_repeated_twice,
  869. mode=self._padding_mode,
  870. data_format=self._data_format,
  871. )
  872. out = F.conv._conv_nd(
  873. x,
  874. self.weight,
  875. bias=self.bias,
  876. stride=self._stride,
  877. padding=self._updated_padding,
  878. padding_algorithm=self._padding_algorithm,
  879. dilation=self._dilation,
  880. groups=self._groups,
  881. data_format=self._data_format,
  882. channel_dim=self._channel_dim,
  883. op_type=self._op_type,
  884. use_cudnn=self._use_cudnn,
  885. )
  886. return out
  887. class Conv3DTranspose(_ConvNd):
  888. r"""
  889. **Convlution3D transpose layer**
  890. The convolution3D transpose layer calculates the output based on the input,
  891. filter, and dilations, strides, paddings. Input(Input) and output(Output)
  892. are in NCDHW format. Where N is batch size, C is the number of channels,
  893. D is the depth of the feature, H is the height of the feature, and W
  894. is the width of the feature. Parameters(dilations, strides, paddings) are
  895. two elements. These two elements represent height and width, respectively.
  896. The details of convolution transpose layer, please refer to the following
  897. explanation and references `therein <https://arxiv.org/pdf/1603.07285.pdf>`_.
  898. If bias attribution and activation type are provided, bias is added to
  899. the output of the convolution, and the corresponding activation function
  900. is applied to the final result.
  901. For each input :math:`X`, the equation is:
  902. .. math::
  903. Out = \sigma (W \ast X + b)
  904. In the above equation:
  905. * :math:`X`: Input value, a tensor with NCDHW format.
  906. * :math:`W`: Filter value, a tensor with CMDHW format.
  907. * :math:`\ast`: Convolution operation.
  908. * :math:`b`: Bias value, a 1-D tensor with shape [M].
  909. * :math:`\sigma`: Activation function.
  910. * :math:`Out`: Output value, the shape of :math:`Out` and :math:`X` may be different.
  911. .. note::
  912. The conv3d_transpose can be seen as the backward of the conv3d. For conv3d,
  913. when stride > 1, conv3d maps multiple input shape to the same output shape,
  914. so for conv3d_transpose, when stride > 1, input shape maps multiple output shape.
  915. If output_size is None, :math:`H_{out} = H^\prime_{out}, W_{out} = W^\prime_{out}`;
  916. else, the :math:`D_{out}` of the output size must between :math:`D^\prime_{out}`
  917. and :math:`D^\prime_{out} + strides[0]`, the :math:`H_{out}` of the output size must
  918. between :math:`H^\prime_{out}` and :math:`H^\prime_{out} + strides[1]`, and the
  919. :math:`W_{out}` of the output size must between :math:`W^\prime_{out}` and
  920. :math:`W^\prime_{out} + strides[2]`, conv3d_transpose can compute the kernel size automatically.
  921. Parameters:
  922. in_channels(int): The number of channels in the input image.
  923. out_channels(int): The number of channels produced by the convolution.
  924. kernel_size(int|list|tuple): The kernel size. If kernel_size is a list/tuple,
  925. it must contain three integers, (kernel_size_D, kernel_size_H, kernel_size_W).
  926. Otherwise, the kernel will be a square.
  927. stride(int|list|tuple, optional): The stride size. It means the stride in transposed convolution.
  928. If stride is a list/tuple, it must contain three integers, (stride_depth, stride_height,
  929. stride_width). Otherwise, stride_depth = stride_height = stride_width = stride.
  930. Default: 1.
  931. padding(int|str|tuple|list, optional): The padding size. Padding coule be in one of the following forms.
  932. 1. a string in ['valid', 'same'].
  933. 2. an int, which means each spartial dimension(depth, height, width) is zero paded by size of `padding`
  934. 3. a list[int] or tuple[int] whose length is the number of spartial dimensions, which contains the amount of padding on each side for each spartial dimension. It has the form [pad_d1, pad_d2, ...].
  935. 4. a list[int] or tuple[int] whose length is 2 * number of spartial dimensions. It has the form [pad_before, pad_after, pad_before, pad_after, ...] for all spartial dimensions.
  936. 5. a list or tuple of pairs of ints. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension are also included. Each pair of integers correspond to the amount of padding for a dimension of the input. Padding in batch dimension and channel dimension should be [0, 0] or (0, 0).
  937. Default: 0.
  938. output_padding(int|list|tuple, optional): Additional size added to one side
  939. of each dimension in the output shape. Default: 0.
  940. dilation(int|list|tuple, optional): The dilation size. If dilation is a list/tuple, it must
  941. contain three integers, (dilation_D, dilation_H, dilation_W). Otherwise, the
  942. dilation_D = dilation_H = dilation_W = dilation. Default: 1.
  943. groups(int, optional): The groups number of the Conv3D transpose layer. Inspired by
  944. grouped convolution in `Alex Krizhevsky's Deep CNN paper <https://papers.nips.cc/paper/2012/file/c399862d3b9d6b76c8436e924a68c45b-Paper.pdf>`_, in which
  945. when groups = 2, the first half of the filters is only connected to the
  946. first half of the input channels, while the second half of the
  947. filters is only connected to the second half of the input channels.
  948. Default: 1.
  949. weight_attr(ParamAttr, optional): The parameter attribute for learnable parameters/weights
  950. of conv3d_transpose. If it is set to None or one attribute of ParamAttr, conv3d_transpose
  951. will create ParamAttr as param_attr. If the Initializer of the param_attr
  952. is not set, the parameter is initialized with Xavier. Default: None.
  953. bias_attr(ParamAttr|bool, optional): The parameter attribute for the bias of conv3d_transpose.
  954. If it is set to False, no bias will be added to the output units.
  955. If it is set to None or one attribute of ParamAttr, conv3d_transpose
  956. will create ParamAttr as bias_attr. If the Initializer of the bias_attr
  957. is not set, the bias is initialized zero. Default: None.
  958. data_format(str, optional): Data format that specifies the layout of input.
  959. It can be "NCDHW" or "NDHWC". Default: "NCDHW".
  960. Attribute:
  961. **weight** (Parameter): the learnable weights of filters of this layer.
  962. **bias** (Parameter): the learnable bias of this layer.
  963. Shape:
  964. - x: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})`
  965. - weight: :math:`(C_{in}, C_{out}, K_{d}, K_{h}, K_{w})`
  966. - bias: :math:`(C_{out})`
  967. - output: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})`
  968. Where
  969. .. math::
  970. D^\prime_{out} &= (D_{in} - 1) * strides[0] - 2 * paddings[0] + dilations[0] * (kernel\_size[0] - 1) + 1
  971. H^\prime_{out} &= (H_{in} - 1) * strides[1] - 2 * paddings[1] + dilations[1] * (kernel\_size[1] - 1) + 1
  972. W^\prime_{out} &= (W_{in} - 1) * strides[2] - 2 * paddings[2] + dilations[2] * (kernel\_size[2] - 1) + 1
  973. Examples:
  974. .. code-block:: python
  975. >>> import paddle
  976. >>> import paddle.nn as nn
  977. >>> paddle.disable_static()
  978. >>> x_var = paddle.uniform((2, 4, 8, 8, 8), dtype='float32', min=-1., max=1.)
  979. >>> conv = nn.Conv3DTranspose(4, 6, (3, 3, 3))
  980. >>> y_var = conv(x_var)
  981. >>> print(y_var.shape)
  982. [2, 6, 10, 10, 10]
  983. """
  984. def __init__(
  985. self,
  986. in_channels,
  987. out_channels,
  988. kernel_size,
  989. stride=1,
  990. padding=0,
  991. output_padding=0,
  992. dilation=1,
  993. groups=1,
  994. weight_attr=None,
  995. bias_attr=None,
  996. data_format="NCDHW",
  997. ):
  998. super().__init__(
  999. in_channels,
  1000. out_channels,
  1001. kernel_size,
  1002. True,
  1003. 3,
  1004. stride=stride,
  1005. padding=padding,
  1006. dilation=dilation,
  1007. output_padding=output_padding,
  1008. groups=groups,
  1009. weight_attr=weight_attr,
  1010. bias_attr=bias_attr,
  1011. data_format=data_format,
  1012. )
  1013. def forward(self, x, output_size=None):
  1014. if output_size is None:
  1015. output_padding = self.output_padding
  1016. else:
  1017. output_padding = 0
  1018. out = F.conv3d_transpose(
  1019. x,
  1020. self.weight,
  1021. bias=self.bias,
  1022. padding=self._padding,
  1023. output_padding=output_padding,
  1024. stride=self._stride,
  1025. dilation=self._dilation,
  1026. groups=self._groups,
  1027. output_size=output_size,
  1028. data_format=self._data_format,
  1029. )
  1030. return out