conv.py 71 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596
  1. # -*- coding: utf-8 -*-
  2. import math
  3. import warnings
  4. import torch
  5. from torch import Tensor
  6. from torch.nn.parameter import Parameter, UninitializedParameter
  7. from .. import functional as F
  8. from .. import init
  9. from .lazy import LazyModuleMixin
  10. from .module import Module
  11. from .utils import _single, _pair, _triple, _reverse_repeat_tuple
  12. from torch._torch_docs import reproducibility_notes
  13. from ..common_types import _size_1_t, _size_2_t, _size_3_t
  14. from typing import Optional, List, Tuple, Union
  15. convolution_notes = \
  16. {"groups_note": r"""* :attr:`groups` controls the connections between inputs and outputs.
  17. :attr:`in_channels` and :attr:`out_channels` must both be divisible by
  18. :attr:`groups`. For example,
  19. * At groups=1, all inputs are convolved to all outputs.
  20. * At groups=2, the operation becomes equivalent to having two conv
  21. layers side by side, each seeing half the input channels
  22. and producing half the output channels, and both subsequently
  23. concatenated.
  24. * At groups= :attr:`in_channels`, each input channel is convolved with
  25. its own set of filters (of size
  26. :math:`\frac{\text{out\_channels}}{\text{in\_channels}}`).""",
  27. "depthwise_separable_note": r"""When `groups == in_channels` and `out_channels == K * in_channels`,
  28. where `K` is a positive integer, this operation is also known as a "depthwise convolution".
  29. In other words, for an input of size :math:`(N, C_{in}, L_{in})`,
  30. a depthwise convolution with a depthwise multiplier `K` can be performed with the arguments
  31. :math:`(C_\text{in}=C_\text{in}, C_\text{out}=C_\text{in} \times \text{K}, ..., \text{groups}=C_\text{in})`."""} # noqa: B950
  32. class _ConvNd(Module):
  33. __constants__ = ['stride', 'padding', 'dilation', 'groups',
  34. 'padding_mode', 'output_padding', 'in_channels',
  35. 'out_channels', 'kernel_size']
  36. __annotations__ = {'bias': Optional[torch.Tensor]}
  37. def _conv_forward(self, input: Tensor, weight: Tensor, bias: Optional[Tensor]) -> Tensor:
  38. ...
  39. _in_channels: int
  40. _reversed_padding_repeated_twice: List[int]
  41. out_channels: int
  42. kernel_size: Tuple[int, ...]
  43. stride: Tuple[int, ...]
  44. padding: Union[str, Tuple[int, ...]]
  45. dilation: Tuple[int, ...]
  46. transposed: bool
  47. output_padding: Tuple[int, ...]
  48. groups: int
  49. padding_mode: str
  50. weight: Tensor
  51. bias: Optional[Tensor]
  52. def __init__(self,
  53. in_channels: int,
  54. out_channels: int,
  55. kernel_size: Tuple[int, ...],
  56. stride: Tuple[int, ...],
  57. padding: Tuple[int, ...],
  58. dilation: Tuple[int, ...],
  59. transposed: bool,
  60. output_padding: Tuple[int, ...],
  61. groups: int,
  62. bias: bool,
  63. padding_mode: str,
  64. device=None,
  65. dtype=None) -> None:
  66. factory_kwargs = {'device': device, 'dtype': dtype}
  67. super(_ConvNd, self).__init__()
  68. if in_channels % groups != 0:
  69. raise ValueError('in_channels must be divisible by groups')
  70. if out_channels % groups != 0:
  71. raise ValueError('out_channels must be divisible by groups')
  72. valid_padding_strings = {'same', 'valid'}
  73. if isinstance(padding, str):
  74. if padding not in valid_padding_strings:
  75. raise ValueError(
  76. "Invalid padding string {!r}, should be one of {}".format(
  77. padding, valid_padding_strings))
  78. if padding == 'same' and any(s != 1 for s in stride):
  79. raise ValueError("padding='same' is not supported for strided convolutions")
  80. valid_padding_modes = {'zeros', 'reflect', 'replicate', 'circular'}
  81. if padding_mode not in valid_padding_modes:
  82. raise ValueError("padding_mode must be one of {}, but got padding_mode='{}'".format(
  83. valid_padding_modes, padding_mode))
  84. self.in_channels = in_channels
  85. self.out_channels = out_channels
  86. self.kernel_size = kernel_size
  87. self.stride = stride
  88. self.padding = padding
  89. self.dilation = dilation
  90. self.transposed = transposed
  91. self.output_padding = output_padding
  92. self.groups = groups
  93. self.padding_mode = padding_mode
  94. # `_reversed_padding_repeated_twice` is the padding to be passed to
  95. # `F.pad` if needed (e.g., for non-zero padding types that are
  96. # implemented as two ops: padding + conv). `F.pad` accepts paddings in
  97. # reverse order than the dimension.
  98. if isinstance(self.padding, str):
  99. self._reversed_padding_repeated_twice = [0, 0] * len(kernel_size)
  100. if padding == 'same':
  101. for d, k, i in zip(dilation, kernel_size,
  102. range(len(kernel_size) - 1, -1, -1)):
  103. total_padding = d * (k - 1)
  104. left_pad = total_padding // 2
  105. self._reversed_padding_repeated_twice[2 * i] = left_pad
  106. self._reversed_padding_repeated_twice[2 * i + 1] = (
  107. total_padding - left_pad)
  108. else:
  109. self._reversed_padding_repeated_twice = _reverse_repeat_tuple(self.padding, 2)
  110. if transposed:
  111. self.weight = Parameter(torch.empty(
  112. (in_channels, out_channels // groups, *kernel_size), **factory_kwargs))
  113. else:
  114. self.weight = Parameter(torch.empty(
  115. (out_channels, in_channels // groups, *kernel_size), **factory_kwargs))
  116. if bias:
  117. self.bias = Parameter(torch.empty(out_channels, **factory_kwargs))
  118. else:
  119. self.register_parameter('bias', None)
  120. self.reset_parameters()
  121. def reset_parameters(self) -> None:
  122. # Setting a=sqrt(5) in kaiming_uniform is the same as initializing with
  123. # uniform(-1/sqrt(k), 1/sqrt(k)), where k = weight.size(1) * prod(*kernel_size)
  124. # For more details see: https://github.com/pytorch/pytorch/issues/15314#issuecomment-477448573
  125. init.kaiming_uniform_(self.weight, a=math.sqrt(5))
  126. if self.bias is not None:
  127. fan_in, _ = init._calculate_fan_in_and_fan_out(self.weight)
  128. if fan_in != 0:
  129. bound = 1 / math.sqrt(fan_in)
  130. init.uniform_(self.bias, -bound, bound)
  131. def extra_repr(self):
  132. s = ('{in_channels}, {out_channels}, kernel_size={kernel_size}'
  133. ', stride={stride}')
  134. if self.padding != (0,) * len(self.padding):
  135. s += ', padding={padding}'
  136. if self.dilation != (1,) * len(self.dilation):
  137. s += ', dilation={dilation}'
  138. if self.output_padding != (0,) * len(self.output_padding):
  139. s += ', output_padding={output_padding}'
  140. if self.groups != 1:
  141. s += ', groups={groups}'
  142. if self.bias is None:
  143. s += ', bias=False'
  144. if self.padding_mode != 'zeros':
  145. s += ', padding_mode={padding_mode}'
  146. return s.format(**self.__dict__)
  147. def __setstate__(self, state):
  148. super(_ConvNd, self).__setstate__(state)
  149. if not hasattr(self, 'padding_mode'):
  150. self.padding_mode = 'zeros'
  151. class Conv1d(_ConvNd):
  152. __doc__ = r"""Applies a 1D convolution over an input signal composed of several input
  153. planes.
  154. In the simplest case, the output value of the layer with input size
  155. :math:`(N, C_{\text{in}}, L)` and output :math:`(N, C_{\text{out}}, L_{\text{out}})` can be
  156. precisely described as:
  157. .. math::
  158. \text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) +
  159. \sum_{k = 0}^{C_{in} - 1} \text{weight}(C_{\text{out}_j}, k)
  160. \star \text{input}(N_i, k)
  161. where :math:`\star` is the valid `cross-correlation`_ operator,
  162. :math:`N` is a batch size, :math:`C` denotes a number of channels,
  163. :math:`L` is a length of signal sequence.
  164. """ + r"""
  165. This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
  166. On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
  167. * :attr:`stride` controls the stride for the cross-correlation, a single
  168. number or a one-element tuple.
  169. * :attr:`padding` controls the amount of padding applied to the input. It
  170. can be either a string {{'valid', 'same'}} or a tuple of ints giving the
  171. amount of implicit padding applied on both sides.
  172. * :attr:`dilation` controls the spacing between the kernel points; also
  173. known as the à trous algorithm. It is harder to describe, but this `link`_
  174. has a nice visualization of what :attr:`dilation` does.
  175. {groups_note}
  176. Note:
  177. {depthwise_separable_note}
  178. Note:
  179. {cudnn_reproducibility_note}
  180. Note:
  181. ``padding='valid'`` is the same as no padding. ``padding='same'`` pads
  182. the input so the output has the shape as the input. However, this mode
  183. doesn't support any stride values other than 1.
  184. Note:
  185. This module supports complex data types i.e. ``complex32, complex64, complex128``.
  186. Args:
  187. in_channels (int): Number of channels in the input image
  188. out_channels (int): Number of channels produced by the convolution
  189. kernel_size (int or tuple): Size of the convolving kernel
  190. stride (int or tuple, optional): Stride of the convolution. Default: 1
  191. padding (int, tuple or str, optional): Padding added to both sides of
  192. the input. Default: 0
  193. padding_mode (string, optional): ``'zeros'``, ``'reflect'``,
  194. ``'replicate'`` or ``'circular'``. Default: ``'zeros'``
  195. dilation (int or tuple, optional): Spacing between kernel
  196. elements. Default: 1
  197. groups (int, optional): Number of blocked connections from input
  198. channels to output channels. Default: 1
  199. bias (bool, optional): If ``True``, adds a learnable bias to the
  200. output. Default: ``True``
  201. """.format(**reproducibility_notes, **convolution_notes) + r"""
  202. Shape:
  203. - Input: :math:`(N, C_{in}, L_{in})` or :math:`(C_{in}, L_{in})`
  204. - Output: :math:`(N, C_{out}, L_{out})` or :math:`(C_{out}, L_{out})`, where
  205. .. math::
  206. L_{out} = \left\lfloor\frac{L_{in} + 2 \times \text{padding} - \text{dilation}
  207. \times (\text{kernel\_size} - 1) - 1}{\text{stride}} + 1\right\rfloor
  208. Attributes:
  209. weight (Tensor): the learnable weights of the module of shape
  210. :math:`(\text{out\_channels},
  211. \frac{\text{in\_channels}}{\text{groups}}, \text{kernel\_size})`.
  212. The values of these weights are sampled from
  213. :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  214. :math:`k = \frac{groups}{C_\text{in} * \text{kernel\_size}}`
  215. bias (Tensor): the learnable bias of the module of shape
  216. (out_channels). If :attr:`bias` is ``True``, then the values of these weights are
  217. sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  218. :math:`k = \frac{groups}{C_\text{in} * \text{kernel\_size}}`
  219. Examples::
  220. >>> m = nn.Conv1d(16, 33, 3, stride=2)
  221. >>> input = torch.randn(20, 16, 50)
  222. >>> output = m(input)
  223. .. _cross-correlation:
  224. https://en.wikipedia.org/wiki/Cross-correlation
  225. .. _link:
  226. https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
  227. """
  228. def __init__(
  229. self,
  230. in_channels: int,
  231. out_channels: int,
  232. kernel_size: _size_1_t,
  233. stride: _size_1_t = 1,
  234. padding: Union[str, _size_1_t] = 0,
  235. dilation: _size_1_t = 1,
  236. groups: int = 1,
  237. bias: bool = True,
  238. padding_mode: str = 'zeros', # TODO: refine this type
  239. device=None,
  240. dtype=None
  241. ) -> None:
  242. factory_kwargs = {'device': device, 'dtype': dtype}
  243. # we create new variables below to make mypy happy since kernel_size has
  244. # type Union[int, Tuple[int]] and kernel_size_ has type Tuple[int]
  245. kernel_size_ = _single(kernel_size)
  246. stride_ = _single(stride)
  247. padding_ = padding if isinstance(padding, str) else _single(padding)
  248. dilation_ = _single(dilation)
  249. super(Conv1d, self).__init__(
  250. in_channels, out_channels, kernel_size_, stride_, padding_, dilation_,
  251. False, _single(0), groups, bias, padding_mode, **factory_kwargs)
  252. def _conv_forward(self, input: Tensor, weight: Tensor, bias: Optional[Tensor]):
  253. if self.padding_mode != 'zeros':
  254. return F.conv1d(F.pad(input, self._reversed_padding_repeated_twice, mode=self.padding_mode),
  255. weight, bias, self.stride,
  256. _single(0), self.dilation, self.groups)
  257. return F.conv1d(input, weight, bias, self.stride,
  258. self.padding, self.dilation, self.groups)
  259. def forward(self, input: Tensor) -> Tensor:
  260. return self._conv_forward(input, self.weight, self.bias)
  261. class Conv2d(_ConvNd):
  262. __doc__ = r"""Applies a 2D convolution over an input signal composed of several input
  263. planes.
  264. In the simplest case, the output value of the layer with input size
  265. :math:`(N, C_{\text{in}}, H, W)` and output :math:`(N, C_{\text{out}}, H_{\text{out}}, W_{\text{out}})`
  266. can be precisely described as:
  267. .. math::
  268. \text{out}(N_i, C_{\text{out}_j}) = \text{bias}(C_{\text{out}_j}) +
  269. \sum_{k = 0}^{C_{\text{in}} - 1} \text{weight}(C_{\text{out}_j}, k) \star \text{input}(N_i, k)
  270. where :math:`\star` is the valid 2D `cross-correlation`_ operator,
  271. :math:`N` is a batch size, :math:`C` denotes a number of channels,
  272. :math:`H` is a height of input planes in pixels, and :math:`W` is
  273. width in pixels.
  274. """ + r"""
  275. This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
  276. On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
  277. * :attr:`stride` controls the stride for the cross-correlation, a single
  278. number or a tuple.
  279. * :attr:`padding` controls the amount of padding applied to the input. It
  280. can be either a string {{'valid', 'same'}} or a tuple of ints giving the
  281. amount of implicit padding applied on both sides.
  282. * :attr:`dilation` controls the spacing between the kernel points; also
  283. known as the à trous algorithm. It is harder to describe, but this `link`_
  284. has a nice visualization of what :attr:`dilation` does.
  285. {groups_note}
  286. The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
  287. - a single ``int`` -- in which case the same value is used for the height and width dimension
  288. - a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
  289. and the second `int` for the width dimension
  290. Note:
  291. {depthwise_separable_note}
  292. Note:
  293. {cudnn_reproducibility_note}
  294. Note:
  295. ``padding='valid'`` is the same as no padding. ``padding='same'`` pads
  296. the input so the output has the shape as the input. However, this mode
  297. doesn't support any stride values other than 1.
  298. Note:
  299. This module supports complex data types i.e. ``complex32, complex64, complex128``.
  300. Args:
  301. in_channels (int): Number of channels in the input image
  302. out_channels (int): Number of channels produced by the convolution
  303. kernel_size (int or tuple): Size of the convolving kernel
  304. stride (int or tuple, optional): Stride of the convolution. Default: 1
  305. padding (int, tuple or str, optional): Padding added to all four sides of
  306. the input. Default: 0
  307. padding_mode (string, optional): ``'zeros'``, ``'reflect'``,
  308. ``'replicate'`` or ``'circular'``. Default: ``'zeros'``
  309. dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
  310. groups (int, optional): Number of blocked connections from input
  311. channels to output channels. Default: 1
  312. bias (bool, optional): If ``True``, adds a learnable bias to the
  313. output. Default: ``True``
  314. """.format(**reproducibility_notes, **convolution_notes) + r"""
  315. Shape:
  316. - Input: :math:`(N, C_{in}, H_{in}, W_{in})` or :math:`(C_{in}, H_{in}, W_{in})`
  317. - Output: :math:`(N, C_{out}, H_{out}, W_{out})` or :math:`(C_{out}, H_{out}, W_{out})`, where
  318. .. math::
  319. H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] - \text{dilation}[0]
  320. \times (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor
  321. .. math::
  322. W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[1] - \text{dilation}[1]
  323. \times (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor
  324. Attributes:
  325. weight (Tensor): the learnable weights of the module of shape
  326. :math:`(\text{out\_channels}, \frac{\text{in\_channels}}{\text{groups}},`
  327. :math:`\text{kernel\_size[0]}, \text{kernel\_size[1]})`.
  328. The values of these weights are sampled from
  329. :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  330. :math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{1}\text{kernel\_size}[i]}`
  331. bias (Tensor): the learnable bias of the module of shape
  332. (out_channels). If :attr:`bias` is ``True``,
  333. then the values of these weights are
  334. sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  335. :math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{1}\text{kernel\_size}[i]}`
  336. Examples:
  337. >>> # With square kernels and equal stride
  338. >>> m = nn.Conv2d(16, 33, 3, stride=2)
  339. >>> # non-square kernels and unequal stride and with padding
  340. >>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
  341. >>> # non-square kernels and unequal stride and with padding and dilation
  342. >>> m = nn.Conv2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2), dilation=(3, 1))
  343. >>> input = torch.randn(20, 16, 50, 100)
  344. >>> output = m(input)
  345. .. _cross-correlation:
  346. https://en.wikipedia.org/wiki/Cross-correlation
  347. .. _link:
  348. https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
  349. """
  350. def __init__(
  351. self,
  352. in_channels: int,
  353. out_channels: int,
  354. kernel_size: _size_2_t,
  355. stride: _size_2_t = 1,
  356. padding: Union[str, _size_2_t] = 0,
  357. dilation: _size_2_t = 1,
  358. groups: int = 1,
  359. bias: bool = True,
  360. padding_mode: str = 'zeros', # TODO: refine this type
  361. device=None,
  362. dtype=None
  363. ) -> None:
  364. factory_kwargs = {'device': device, 'dtype': dtype}
  365. kernel_size_ = _pair(kernel_size)
  366. stride_ = _pair(stride)
  367. padding_ = padding if isinstance(padding, str) else _pair(padding)
  368. dilation_ = _pair(dilation)
  369. super(Conv2d, self).__init__(
  370. in_channels, out_channels, kernel_size_, stride_, padding_, dilation_,
  371. False, _pair(0), groups, bias, padding_mode, **factory_kwargs)
  372. def _conv_forward(self, input: Tensor, weight: Tensor, bias: Optional[Tensor]):
  373. if self.padding_mode != 'zeros':
  374. return F.conv2d(F.pad(input, self._reversed_padding_repeated_twice, mode=self.padding_mode),
  375. weight, bias, self.stride,
  376. _pair(0), self.dilation, self.groups)
  377. return F.conv2d(input, weight, bias, self.stride,
  378. self.padding, self.dilation, self.groups)
  379. def forward(self, input: Tensor) -> Tensor:
  380. return self._conv_forward(input, self.weight, self.bias)
  381. class Conv3d(_ConvNd):
  382. __doc__ = r"""Applies a 3D convolution over an input signal composed of several input
  383. planes.
  384. In the simplest case, the output value of the layer with input size :math:`(N, C_{in}, D, H, W)`
  385. and output :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` can be precisely described as:
  386. .. math::
  387. out(N_i, C_{out_j}) = bias(C_{out_j}) +
  388. \sum_{k = 0}^{C_{in} - 1} weight(C_{out_j}, k) \star input(N_i, k)
  389. where :math:`\star` is the valid 3D `cross-correlation`_ operator
  390. """ + r"""
  391. This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
  392. On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
  393. * :attr:`stride` controls the stride for the cross-correlation.
  394. * :attr:`padding` controls the amount of padding applied to the input. It
  395. can be either a string {{'valid', 'same'}} or a tuple of ints giving the
  396. amount of implicit padding applied on both sides.
  397. * :attr:`dilation` controls the spacing between the kernel points; also known as the à trous algorithm.
  398. It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
  399. {groups_note}
  400. The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
  401. - a single ``int`` -- in which case the same value is used for the depth, height and width dimension
  402. - a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension,
  403. the second `int` for the height dimension and the third `int` for the width dimension
  404. Note:
  405. {depthwise_separable_note}
  406. Note:
  407. {cudnn_reproducibility_note}
  408. Note:
  409. ``padding='valid'`` is the same as no padding. ``padding='same'`` pads
  410. the input so the output has the shape as the input. However, this mode
  411. doesn't support any stride values other than 1.
  412. Note:
  413. This module supports complex data types i.e. ``complex32, complex64, complex128``.
  414. Args:
  415. in_channels (int): Number of channels in the input image
  416. out_channels (int): Number of channels produced by the convolution
  417. kernel_size (int or tuple): Size of the convolving kernel
  418. stride (int or tuple, optional): Stride of the convolution. Default: 1
  419. padding (int, tuple or str, optional): Padding added to all six sides of
  420. the input. Default: 0
  421. padding_mode (string, optional): ``'zeros'``, ``'reflect'``, ``'replicate'`` or ``'circular'``. Default: ``'zeros'``
  422. dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
  423. groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
  424. bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
  425. """.format(**reproducibility_notes, **convolution_notes) + r"""
  426. Shape:
  427. - Input: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` or :math:`(C_{in}, D_{in}, H_{in}, W_{in})`
  428. - Output: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` or :math:`(C_{out}, D_{out}, H_{out}, W_{out})`,
  429. where
  430. .. math::
  431. D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{dilation}[0]
  432. \times (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor
  433. .. math::
  434. H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{dilation}[1]
  435. \times (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor
  436. .. math::
  437. W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{dilation}[2]
  438. \times (\text{kernel\_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor
  439. Attributes:
  440. weight (Tensor): the learnable weights of the module of shape
  441. :math:`(\text{out\_channels}, \frac{\text{in\_channels}}{\text{groups}},`
  442. :math:`\text{kernel\_size[0]}, \text{kernel\_size[1]}, \text{kernel\_size[2]})`.
  443. The values of these weights are sampled from
  444. :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  445. :math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{2}\text{kernel\_size}[i]}`
  446. bias (Tensor): the learnable bias of the module of shape (out_channels). If :attr:`bias` is ``True``,
  447. then the values of these weights are
  448. sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  449. :math:`k = \frac{groups}{C_\text{in} * \prod_{i=0}^{2}\text{kernel\_size}[i]}`
  450. Examples::
  451. >>> # With square kernels and equal stride
  452. >>> m = nn.Conv3d(16, 33, 3, stride=2)
  453. >>> # non-square kernels and unequal stride and with padding
  454. >>> m = nn.Conv3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(4, 2, 0))
  455. >>> input = torch.randn(20, 16, 10, 50, 100)
  456. >>> output = m(input)
  457. .. _cross-correlation:
  458. https://en.wikipedia.org/wiki/Cross-correlation
  459. .. _link:
  460. https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
  461. """
  462. def __init__(
  463. self,
  464. in_channels: int,
  465. out_channels: int,
  466. kernel_size: _size_3_t,
  467. stride: _size_3_t = 1,
  468. padding: Union[str, _size_3_t] = 0,
  469. dilation: _size_3_t = 1,
  470. groups: int = 1,
  471. bias: bool = True,
  472. padding_mode: str = 'zeros',
  473. device=None,
  474. dtype=None
  475. ) -> None:
  476. factory_kwargs = {'device': device, 'dtype': dtype}
  477. kernel_size_ = _triple(kernel_size)
  478. stride_ = _triple(stride)
  479. padding_ = padding if isinstance(padding, str) else _triple(padding)
  480. dilation_ = _triple(dilation)
  481. super(Conv3d, self).__init__(
  482. in_channels, out_channels, kernel_size_, stride_, padding_, dilation_,
  483. False, _triple(0), groups, bias, padding_mode, **factory_kwargs)
  484. def _conv_forward(self, input: Tensor, weight: Tensor, bias: Optional[Tensor]):
  485. if self.padding_mode != "zeros":
  486. return F.conv3d(
  487. F.pad(
  488. input, self._reversed_padding_repeated_twice, mode=self.padding_mode
  489. ),
  490. weight,
  491. bias,
  492. self.stride,
  493. _triple(0),
  494. self.dilation,
  495. self.groups,
  496. )
  497. return F.conv3d(
  498. input, weight, bias, self.stride, self.padding, self.dilation, self.groups
  499. )
  500. def forward(self, input: Tensor) -> Tensor:
  501. return self._conv_forward(input, self.weight, self.bias)
  502. class _ConvTransposeNd(_ConvNd):
  503. def __init__(self, in_channels, out_channels, kernel_size, stride,
  504. padding, dilation, transposed, output_padding,
  505. groups, bias, padding_mode, device=None, dtype=None) -> None:
  506. if padding_mode != 'zeros':
  507. raise ValueError('Only "zeros" padding mode is supported for {}'.format(self.__class__.__name__))
  508. factory_kwargs = {'device': device, 'dtype': dtype}
  509. super(_ConvTransposeNd, self).__init__(
  510. in_channels, out_channels, kernel_size, stride,
  511. padding, dilation, transposed, output_padding,
  512. groups, bias, padding_mode, **factory_kwargs)
  513. # dilation being an optional parameter is for backwards
  514. # compatibility
  515. def _output_padding(self, input: Tensor, output_size: Optional[List[int]],
  516. stride: List[int], padding: List[int], kernel_size: List[int],
  517. num_spatial_dims: int, dilation: Optional[List[int]] = None) -> List[int]:
  518. if output_size is None:
  519. ret = _single(self.output_padding) # converting to list if was not already
  520. else:
  521. has_batch_dim = input.dim() == num_spatial_dims + 2
  522. num_non_spatial_dims = 2 if has_batch_dim else 1
  523. if len(output_size) == num_non_spatial_dims + num_spatial_dims:
  524. output_size = output_size[num_non_spatial_dims:]
  525. if len(output_size) != num_spatial_dims:
  526. raise ValueError(
  527. "ConvTranspose{}D: for {}D input, output_size must have {} or {} elements (got {})"
  528. .format(num_spatial_dims, input.dim(), num_spatial_dims,
  529. num_non_spatial_dims + num_spatial_dims, len(output_size)))
  530. min_sizes = torch.jit.annotate(List[int], [])
  531. max_sizes = torch.jit.annotate(List[int], [])
  532. for d in range(num_spatial_dims):
  533. dim_size = ((input.size(d + num_non_spatial_dims) - 1) * stride[d] -
  534. 2 * padding[d] +
  535. (dilation[d] if dilation is not None else 1) * (kernel_size[d] - 1) + 1)
  536. min_sizes.append(dim_size)
  537. max_sizes.append(min_sizes[d] + stride[d] - 1)
  538. for i in range(len(output_size)):
  539. size = output_size[i]
  540. min_size = min_sizes[i]
  541. max_size = max_sizes[i]
  542. if size < min_size or size > max_size:
  543. raise ValueError((
  544. "requested an output size of {}, but valid sizes range "
  545. "from {} to {} (for an input of {})").format(
  546. output_size, min_sizes, max_sizes, input.size()[2:]))
  547. res = torch.jit.annotate(List[int], [])
  548. for d in range(num_spatial_dims):
  549. res.append(output_size[d] - min_sizes[d])
  550. ret = res
  551. return ret
  552. class ConvTranspose1d(_ConvTransposeNd):
  553. __doc__ = r"""Applies a 1D transposed convolution operator over an input image
  554. composed of several input planes.
  555. This module can be seen as the gradient of Conv1d with respect to its input.
  556. It is also known as a fractionally-strided convolution or
  557. a deconvolution (although it is not an actual deconvolution operation as it does
  558. not compute a true inverse of convolution). For more information, see the visualizations
  559. `here`_ and the `Deconvolutional Networks`_ paper.
  560. This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
  561. On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
  562. * :attr:`stride` controls the stride for the cross-correlation.
  563. * :attr:`padding` controls the amount of implicit zero padding on both
  564. sides for ``dilation * (kernel_size - 1) - padding`` number of points. See note
  565. below for details.
  566. * :attr:`output_padding` controls the additional size added to one side
  567. of the output shape. See note below for details.
  568. * :attr:`dilation` controls the spacing between the kernel points; also known as the à trous algorithm.
  569. It is harder to describe, but the link `here`_ has a nice visualization of what :attr:`dilation` does.
  570. {groups_note}
  571. Note:
  572. The :attr:`padding` argument effectively adds ``dilation * (kernel_size - 1) - padding``
  573. amount of zero padding to both sizes of the input. This is set so that
  574. when a :class:`~torch.nn.Conv1d` and a :class:`~torch.nn.ConvTranspose1d`
  575. are initialized with same parameters, they are inverses of each other in
  576. regard to the input and output shapes. However, when ``stride > 1``,
  577. :class:`~torch.nn.Conv1d` maps multiple input shapes to the same output
  578. shape. :attr:`output_padding` is provided to resolve this ambiguity by
  579. effectively increasing the calculated output shape on one side. Note
  580. that :attr:`output_padding` is only used to find output shape, but does
  581. not actually add zero-padding to output.
  582. Note:
  583. In some circumstances when using the CUDA backend with CuDNN, this operator
  584. may select a nondeterministic algorithm to increase performance. If this is
  585. undesirable, you can try to make the operation deterministic (potentially at
  586. a performance cost) by setting ``torch.backends.cudnn.deterministic =
  587. True``.
  588. Please see the notes on :doc:`/notes/randomness` for background.
  589. Args:
  590. in_channels (int): Number of channels in the input image
  591. out_channels (int): Number of channels produced by the convolution
  592. kernel_size (int or tuple): Size of the convolving kernel
  593. stride (int or tuple, optional): Stride of the convolution. Default: 1
  594. padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
  595. will be added to both sides of the input. Default: 0
  596. output_padding (int or tuple, optional): Additional size added to one side
  597. of the output shape. Default: 0
  598. groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
  599. bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
  600. dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
  601. """.format(**reproducibility_notes, **convolution_notes) + r"""
  602. Shape:
  603. - Input: :math:`(N, C_{in}, L_{in})` or :math:`(C_{in}, L_{in})`
  604. - Output: :math:`(N, C_{out}, L_{out})` or :math:`(C_{out}, L_{out})`, where
  605. .. math::
  606. L_{out} = (L_{in} - 1) \times \text{stride} - 2 \times \text{padding} + \text{dilation}
  607. \times (\text{kernel\_size} - 1) + \text{output\_padding} + 1
  608. Attributes:
  609. weight (Tensor): the learnable weights of the module of shape
  610. :math:`(\text{in\_channels}, \frac{\text{out\_channels}}{\text{groups}},`
  611. :math:`\text{kernel\_size})`.
  612. The values of these weights are sampled from
  613. :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  614. :math:`k = \frac{groups}{C_\text{out} * \text{kernel\_size}}`
  615. bias (Tensor): the learnable bias of the module of shape (out_channels).
  616. If :attr:`bias` is ``True``, then the values of these weights are
  617. sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  618. :math:`k = \frac{groups}{C_\text{out} * \text{kernel\_size}}`
  619. .. _`here`:
  620. https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
  621. .. _`Deconvolutional Networks`:
  622. https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf
  623. """
  624. def __init__(
  625. self,
  626. in_channels: int,
  627. out_channels: int,
  628. kernel_size: _size_1_t,
  629. stride: _size_1_t = 1,
  630. padding: _size_1_t = 0,
  631. output_padding: _size_1_t = 0,
  632. groups: int = 1,
  633. bias: bool = True,
  634. dilation: _size_1_t = 1,
  635. padding_mode: str = 'zeros',
  636. device=None,
  637. dtype=None
  638. ) -> None:
  639. factory_kwargs = {'device': device, 'dtype': dtype}
  640. kernel_size = _single(kernel_size)
  641. stride = _single(stride)
  642. padding = _single(padding)
  643. dilation = _single(dilation)
  644. output_padding = _single(output_padding)
  645. super(ConvTranspose1d, self).__init__(
  646. in_channels, out_channels, kernel_size, stride, padding, dilation,
  647. True, output_padding, groups, bias, padding_mode, **factory_kwargs)
  648. def forward(self, input: Tensor, output_size: Optional[List[int]] = None) -> Tensor:
  649. if self.padding_mode != 'zeros':
  650. raise ValueError('Only `zeros` padding mode is supported for ConvTranspose1d')
  651. assert isinstance(self.padding, tuple)
  652. # One cannot replace List by Tuple or Sequence in "_output_padding" because
  653. # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
  654. num_spatial_dims = 1
  655. output_padding = self._output_padding(
  656. input, output_size, self.stride, self.padding, self.kernel_size, # type: ignore[arg-type]
  657. num_spatial_dims, self.dilation) # type: ignore[arg-type]
  658. return F.conv_transpose1d(
  659. input, self.weight, self.bias, self.stride, self.padding,
  660. output_padding, self.groups, self.dilation)
  661. class ConvTranspose2d(_ConvTransposeNd):
  662. __doc__ = r"""Applies a 2D transposed convolution operator over an input image
  663. composed of several input planes.
  664. This module can be seen as the gradient of Conv2d with respect to its input.
  665. It is also known as a fractionally-strided convolution or
  666. a deconvolution (although it is not an actual deconvolution operation as it does
  667. not compute a true inverse of convolution). For more information, see the visualizations
  668. `here`_ and the `Deconvolutional Networks`_ paper.
  669. This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
  670. On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
  671. * :attr:`stride` controls the stride for the cross-correlation.
  672. * :attr:`padding` controls the amount of implicit zero padding on both
  673. sides for ``dilation * (kernel_size - 1) - padding`` number of points. See note
  674. below for details.
  675. * :attr:`output_padding` controls the additional size added to one side
  676. of the output shape. See note below for details.
  677. * :attr:`dilation` controls the spacing between the kernel points; also known as the à trous algorithm.
  678. It is harder to describe, but the link `here`_ has a nice visualization of what :attr:`dilation` does.
  679. {groups_note}
  680. The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`output_padding`
  681. can either be:
  682. - a single ``int`` -- in which case the same value is used for the height and width dimensions
  683. - a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
  684. and the second `int` for the width dimension
  685. Note:
  686. The :attr:`padding` argument effectively adds ``dilation * (kernel_size - 1) - padding``
  687. amount of zero padding to both sizes of the input. This is set so that
  688. when a :class:`~torch.nn.Conv2d` and a :class:`~torch.nn.ConvTranspose2d`
  689. are initialized with same parameters, they are inverses of each other in
  690. regard to the input and output shapes. However, when ``stride > 1``,
  691. :class:`~torch.nn.Conv2d` maps multiple input shapes to the same output
  692. shape. :attr:`output_padding` is provided to resolve this ambiguity by
  693. effectively increasing the calculated output shape on one side. Note
  694. that :attr:`output_padding` is only used to find output shape, but does
  695. not actually add zero-padding to output.
  696. Note:
  697. {cudnn_reproducibility_note}
  698. Args:
  699. in_channels (int): Number of channels in the input image
  700. out_channels (int): Number of channels produced by the convolution
  701. kernel_size (int or tuple): Size of the convolving kernel
  702. stride (int or tuple, optional): Stride of the convolution. Default: 1
  703. padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
  704. will be added to both sides of each dimension in the input. Default: 0
  705. output_padding (int or tuple, optional): Additional size added to one side
  706. of each dimension in the output shape. Default: 0
  707. groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
  708. bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
  709. dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
  710. """.format(**reproducibility_notes, **convolution_notes) + r"""
  711. Shape:
  712. - Input: :math:`(N, C_{in}, H_{in}, W_{in})` or :math:`(C_{in}, H_{in}, W_{in})`
  713. - Output: :math:`(N, C_{out}, H_{out}, W_{out})` or :math:`(C_{out}, H_{out}, W_{out})`, where
  714. .. math::
  715. H_{out} = (H_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{dilation}[0]
  716. \times (\text{kernel\_size}[0] - 1) + \text{output\_padding}[0] + 1
  717. .. math::
  718. W_{out} = (W_{in} - 1) \times \text{stride}[1] - 2 \times \text{padding}[1] + \text{dilation}[1]
  719. \times (\text{kernel\_size}[1] - 1) + \text{output\_padding}[1] + 1
  720. Attributes:
  721. weight (Tensor): the learnable weights of the module of shape
  722. :math:`(\text{in\_channels}, \frac{\text{out\_channels}}{\text{groups}},`
  723. :math:`\text{kernel\_size[0]}, \text{kernel\_size[1]})`.
  724. The values of these weights are sampled from
  725. :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  726. :math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{1}\text{kernel\_size}[i]}`
  727. bias (Tensor): the learnable bias of the module of shape (out_channels)
  728. If :attr:`bias` is ``True``, then the values of these weights are
  729. sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  730. :math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{1}\text{kernel\_size}[i]}`
  731. Examples::
  732. >>> # With square kernels and equal stride
  733. >>> m = nn.ConvTranspose2d(16, 33, 3, stride=2)
  734. >>> # non-square kernels and unequal stride and with padding
  735. >>> m = nn.ConvTranspose2d(16, 33, (3, 5), stride=(2, 1), padding=(4, 2))
  736. >>> input = torch.randn(20, 16, 50, 100)
  737. >>> output = m(input)
  738. >>> # exact output size can be also specified as an argument
  739. >>> input = torch.randn(1, 16, 12, 12)
  740. >>> downsample = nn.Conv2d(16, 16, 3, stride=2, padding=1)
  741. >>> upsample = nn.ConvTranspose2d(16, 16, 3, stride=2, padding=1)
  742. >>> h = downsample(input)
  743. >>> h.size()
  744. torch.Size([1, 16, 6, 6])
  745. >>> output = upsample(h, output_size=input.size())
  746. >>> output.size()
  747. torch.Size([1, 16, 12, 12])
  748. .. _`here`:
  749. https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
  750. .. _`Deconvolutional Networks`:
  751. https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf
  752. """
  753. def __init__(
  754. self,
  755. in_channels: int,
  756. out_channels: int,
  757. kernel_size: _size_2_t,
  758. stride: _size_2_t = 1,
  759. padding: _size_2_t = 0,
  760. output_padding: _size_2_t = 0,
  761. groups: int = 1,
  762. bias: bool = True,
  763. dilation: _size_2_t = 1,
  764. padding_mode: str = 'zeros',
  765. device=None,
  766. dtype=None
  767. ) -> None:
  768. factory_kwargs = {'device': device, 'dtype': dtype}
  769. kernel_size = _pair(kernel_size)
  770. stride = _pair(stride)
  771. padding = _pair(padding)
  772. dilation = _pair(dilation)
  773. output_padding = _pair(output_padding)
  774. super(ConvTranspose2d, self).__init__(
  775. in_channels, out_channels, kernel_size, stride, padding, dilation,
  776. True, output_padding, groups, bias, padding_mode, **factory_kwargs)
  777. def forward(self, input: Tensor, output_size: Optional[List[int]] = None) -> Tensor:
  778. if self.padding_mode != 'zeros':
  779. raise ValueError('Only `zeros` padding mode is supported for ConvTranspose2d')
  780. assert isinstance(self.padding, tuple)
  781. # One cannot replace List by Tuple or Sequence in "_output_padding" because
  782. # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
  783. num_spatial_dims = 2
  784. output_padding = self._output_padding(
  785. input, output_size, self.stride, self.padding, self.kernel_size, # type: ignore[arg-type]
  786. num_spatial_dims, self.dilation) # type: ignore[arg-type]
  787. return F.conv_transpose2d(
  788. input, self.weight, self.bias, self.stride, self.padding,
  789. output_padding, self.groups, self.dilation)
  790. class ConvTranspose3d(_ConvTransposeNd):
  791. __doc__ = r"""Applies a 3D transposed convolution operator over an input image composed of several input
  792. planes.
  793. The transposed convolution operator multiplies each input value element-wise by a learnable kernel,
  794. and sums over the outputs from all input feature planes.
  795. This module can be seen as the gradient of Conv3d with respect to its input.
  796. It is also known as a fractionally-strided convolution or
  797. a deconvolution (although it is not an actual deconvolution operation as it does
  798. not compute a true inverse of convolution). For more information, see the visualizations
  799. `here`_ and the `Deconvolutional Networks`_ paper.
  800. This module supports :ref:`TensorFloat32<tf32_on_ampere>`.
  801. On certain ROCm devices, when using float16 inputs this module will use :ref:`different precision<fp16_on_mi200>` for backward.
  802. * :attr:`stride` controls the stride for the cross-correlation.
  803. * :attr:`padding` controls the amount of implicit zero padding on both
  804. sides for ``dilation * (kernel_size - 1) - padding`` number of points. See note
  805. below for details.
  806. * :attr:`output_padding` controls the additional size added to one side
  807. of the output shape. See note below for details.
  808. * :attr:`dilation` controls the spacing between the kernel points; also known as the à trous algorithm.
  809. It is harder to describe, but the link `here`_ has a nice visualization of what :attr:`dilation` does.
  810. {groups_note}
  811. The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`output_padding`
  812. can either be:
  813. - a single ``int`` -- in which case the same value is used for the depth, height and width dimensions
  814. - a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension,
  815. the second `int` for the height dimension and the third `int` for the width dimension
  816. Note:
  817. The :attr:`padding` argument effectively adds ``dilation * (kernel_size - 1) - padding``
  818. amount of zero padding to both sizes of the input. This is set so that
  819. when a :class:`~torch.nn.Conv3d` and a :class:`~torch.nn.ConvTranspose3d`
  820. are initialized with same parameters, they are inverses of each other in
  821. regard to the input and output shapes. However, when ``stride > 1``,
  822. :class:`~torch.nn.Conv3d` maps multiple input shapes to the same output
  823. shape. :attr:`output_padding` is provided to resolve this ambiguity by
  824. effectively increasing the calculated output shape on one side. Note
  825. that :attr:`output_padding` is only used to find output shape, but does
  826. not actually add zero-padding to output.
  827. Note:
  828. {cudnn_reproducibility_note}
  829. Args:
  830. in_channels (int): Number of channels in the input image
  831. out_channels (int): Number of channels produced by the convolution
  832. kernel_size (int or tuple): Size of the convolving kernel
  833. stride (int or tuple, optional): Stride of the convolution. Default: 1
  834. padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
  835. will be added to both sides of each dimension in the input. Default: 0
  836. output_padding (int or tuple, optional): Additional size added to one side
  837. of each dimension in the output shape. Default: 0
  838. groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
  839. bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
  840. dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
  841. """.format(**reproducibility_notes, **convolution_notes) + r"""
  842. Shape:
  843. - Input: :math:`(N, C_{in}, D_{in}, H_{in}, W_{in})` or :math:`(C_{in}, D_{in}, H_{in}, W_{in})`
  844. - Output: :math:`(N, C_{out}, D_{out}, H_{out}, W_{out})` or
  845. :math:`(C_{out}, D_{out}, H_{out}, W_{out})`, where
  846. .. math::
  847. D_{out} = (D_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{dilation}[0]
  848. \times (\text{kernel\_size}[0] - 1) + \text{output\_padding}[0] + 1
  849. .. math::
  850. H_{out} = (H_{in} - 1) \times \text{stride}[1] - 2 \times \text{padding}[1] + \text{dilation}[1]
  851. \times (\text{kernel\_size}[1] - 1) + \text{output\_padding}[1] + 1
  852. .. math::
  853. W_{out} = (W_{in} - 1) \times \text{stride}[2] - 2 \times \text{padding}[2] + \text{dilation}[2]
  854. \times (\text{kernel\_size}[2] - 1) + \text{output\_padding}[2] + 1
  855. Attributes:
  856. weight (Tensor): the learnable weights of the module of shape
  857. :math:`(\text{in\_channels}, \frac{\text{out\_channels}}{\text{groups}},`
  858. :math:`\text{kernel\_size[0]}, \text{kernel\_size[1]}, \text{kernel\_size[2]})`.
  859. The values of these weights are sampled from
  860. :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  861. :math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{2}\text{kernel\_size}[i]}`
  862. bias (Tensor): the learnable bias of the module of shape (out_channels)
  863. If :attr:`bias` is ``True``, then the values of these weights are
  864. sampled from :math:`\mathcal{U}(-\sqrt{k}, \sqrt{k})` where
  865. :math:`k = \frac{groups}{C_\text{out} * \prod_{i=0}^{2}\text{kernel\_size}[i]}`
  866. Examples::
  867. >>> # With square kernels and equal stride
  868. >>> m = nn.ConvTranspose3d(16, 33, 3, stride=2)
  869. >>> # non-square kernels and unequal stride and with padding
  870. >>> m = nn.ConvTranspose3d(16, 33, (3, 5, 2), stride=(2, 1, 1), padding=(0, 4, 2))
  871. >>> input = torch.randn(20, 16, 10, 50, 100)
  872. >>> output = m(input)
  873. .. _`here`:
  874. https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
  875. .. _`Deconvolutional Networks`:
  876. https://www.matthewzeiler.com/mattzeiler/deconvolutionalnetworks.pdf
  877. """
  878. def __init__(
  879. self,
  880. in_channels: int,
  881. out_channels: int,
  882. kernel_size: _size_3_t,
  883. stride: _size_3_t = 1,
  884. padding: _size_3_t = 0,
  885. output_padding: _size_3_t = 0,
  886. groups: int = 1,
  887. bias: bool = True,
  888. dilation: _size_3_t = 1,
  889. padding_mode: str = 'zeros',
  890. device=None,
  891. dtype=None
  892. ) -> None:
  893. factory_kwargs = {'device': device, 'dtype': dtype}
  894. kernel_size = _triple(kernel_size)
  895. stride = _triple(stride)
  896. padding = _triple(padding)
  897. dilation = _triple(dilation)
  898. output_padding = _triple(output_padding)
  899. super(ConvTranspose3d, self).__init__(
  900. in_channels, out_channels, kernel_size, stride, padding, dilation,
  901. True, output_padding, groups, bias, padding_mode, **factory_kwargs)
  902. def forward(self, input: Tensor, output_size: Optional[List[int]] = None) -> Tensor:
  903. if self.padding_mode != 'zeros':
  904. raise ValueError('Only `zeros` padding mode is supported for ConvTranspose3d')
  905. assert isinstance(self.padding, tuple)
  906. # One cannot replace List by Tuple or Sequence in "_output_padding" because
  907. # TorchScript does not support `Sequence[T]` or `Tuple[T, ...]`.
  908. num_spatial_dims = 3
  909. output_padding = self._output_padding(
  910. input, output_size, self.stride, self.padding, self.kernel_size, # type: ignore[arg-type]
  911. num_spatial_dims, self.dilation) # type: ignore[arg-type]
  912. return F.conv_transpose3d(
  913. input, self.weight, self.bias, self.stride, self.padding,
  914. output_padding, self.groups, self.dilation)
  915. # TODO: Deprecate and remove the following alias `_ConvTransposeMixin`.
  916. #
  917. # `_ConvTransposeMixin` was a mixin that was removed. It is meant to be used
  918. # with `_ConvNd` to construct actual module classes that implements conv
  919. # transpose ops:
  920. #
  921. # class MyConvTranspose(_ConvNd, _ConvTransposeMixin):
  922. # ...
  923. #
  924. # In PyTorch, it has been replaced by `_ConvTransposeNd`, which is a proper
  925. # subclass of `_ConvNd`. However, some user code in the wild still (incorrectly)
  926. # use the internal class `_ConvTransposeMixin`. Hence, we provide this alias
  927. # for BC, because it is cheap and easy for us to do so, even though that
  928. # `_ConvTransposeNd` is really not a mixin anymore (but multiple inheritance as
  929. # above would still work).
  930. class _ConvTransposeMixin(_ConvTransposeNd):
  931. def __init__(self, *args, **kwargs):
  932. warnings.warn(
  933. "_ConvTransposeMixin is a deprecated internal class. "
  934. "Please consider using public APIs.")
  935. super(_ConvTransposeMixin, self).__init__(*args, **kwargs)
  936. # TODO: Conv2dLocal
  937. # TODO: Conv2dMap
  938. # TODO: ConvTranspose2dMap
  939. class _LazyConvXdMixin(LazyModuleMixin):
  940. groups: int
  941. transposed: bool
  942. in_channels: int
  943. out_channels: int
  944. kernel_size: Tuple[int, ...]
  945. weight: UninitializedParameter
  946. bias: UninitializedParameter
  947. def reset_parameters(self) -> None:
  948. # has_uninitialized_params is defined in parent class and it is using a protocol on self
  949. if not self.has_uninitialized_params() and self.in_channels != 0: # type: ignore[misc]
  950. # "type:ignore[..]" is required because mypy thinks that "reset_parameters" is undefined
  951. # in super class. Turns out that it is defined in _ConvND which is inherited by any class
  952. # that also inherits _LazyConvXdMixin
  953. super().reset_parameters() # type: ignore[misc]
  954. # Signature of "initialize_parameters" is incompatible with the definition in supertype LazyModuleMixin
  955. def initialize_parameters(self, input) -> None: # type: ignore[override]
  956. # defined by parent class but using a protocol
  957. if self.has_uninitialized_params(): # type: ignore[misc]
  958. self.in_channels = self._get_in_channels(input)
  959. if self.in_channels % self.groups != 0:
  960. raise ValueError('in_channels must be divisible by groups')
  961. assert isinstance(self.weight, UninitializedParameter)
  962. if self.transposed:
  963. self.weight.materialize((
  964. self.in_channels, self.out_channels // self.groups, *self.kernel_size))
  965. else:
  966. self.weight.materialize((
  967. self.out_channels, self.in_channels // self.groups, *self.kernel_size))
  968. if self.bias is not None:
  969. assert isinstance(self.bias, UninitializedParameter)
  970. self.bias.materialize((self.out_channels,))
  971. self.reset_parameters()
  972. # Function to extract in_channels from first input.
  973. def _get_in_channels(self, input: Tensor) -> int:
  974. num_spatial_dims = self._get_num_spatial_dims()
  975. num_dims_no_batch = num_spatial_dims + 1 # +1 for channels dim
  976. num_dims_batch = num_dims_no_batch + 1
  977. if input.dim() not in (num_dims_no_batch, num_dims_batch):
  978. raise RuntimeError("Expected {}D (unbatched) or {}D (batched) input to {}, but "
  979. "got input of size: {}".format(num_dims_no_batch, num_dims_batch,
  980. self.__class__.__name__, input.shape))
  981. return input.shape[1] if input.dim() == num_dims_batch else input.shape[0]
  982. # Function to return the number of spatial dims expected for inputs to the module.
  983. # This is expected to be implemented by subclasses.
  984. def _get_num_spatial_dims(self) -> int:
  985. raise NotImplementedError()
  986. # LazyConv1d defines weight as a Tensor but derived class defines it as UnitializeParameter
  987. class LazyConv1d(_LazyConvXdMixin, Conv1d): # type: ignore[misc]
  988. r"""A :class:`torch.nn.Conv1d` module with lazy initialization of
  989. the ``in_channels`` argument of the :class:`Conv1d` that is inferred from
  990. the ``input.size(1)``.
  991. The attributes that will be lazily initialized are `weight` and `bias`.
  992. Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
  993. on lazy modules and their limitations.
  994. Args:
  995. out_channels (int): Number of channels produced by the convolution
  996. kernel_size (int or tuple): Size of the convolving kernel
  997. stride (int or tuple, optional): Stride of the convolution. Default: 1
  998. padding (int or tuple, optional): Zero-padding added to both sides of
  999. the input. Default: 0
  1000. padding_mode (string, optional): ``'zeros'``, ``'reflect'``,
  1001. ``'replicate'`` or ``'circular'``. Default: ``'zeros'``
  1002. dilation (int or tuple, optional): Spacing between kernel
  1003. elements. Default: 1
  1004. groups (int, optional): Number of blocked connections from input
  1005. channels to output channels. Default: 1
  1006. bias (bool, optional): If ``True``, adds a learnable bias to the
  1007. output. Default: ``True``
  1008. .. seealso:: :class:`torch.nn.Conv1d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
  1009. """
  1010. # super class define this variable as None. "type: ignore[..] is required
  1011. # since we are redefining the variable.
  1012. cls_to_become = Conv1d # type: ignore[assignment]
  1013. def __init__(
  1014. self,
  1015. out_channels: int,
  1016. kernel_size: _size_1_t,
  1017. stride: _size_1_t = 1,
  1018. padding: _size_1_t = 0,
  1019. dilation: _size_1_t = 1,
  1020. groups: int = 1,
  1021. bias: bool = True,
  1022. padding_mode: str = 'zeros',
  1023. device=None,
  1024. dtype=None
  1025. ) -> None:
  1026. factory_kwargs = {'device': device, 'dtype': dtype}
  1027. super().__init__(
  1028. 0,
  1029. 0,
  1030. kernel_size,
  1031. stride,
  1032. padding,
  1033. dilation,
  1034. groups,
  1035. # bias is hardcoded to False to avoid creating tensor
  1036. # that will soon be overwritten.
  1037. False,
  1038. padding_mode,
  1039. **factory_kwargs
  1040. )
  1041. self.weight = UninitializedParameter(**factory_kwargs)
  1042. self.out_channels = out_channels
  1043. if bias:
  1044. self.bias = UninitializedParameter(**factory_kwargs)
  1045. def _get_num_spatial_dims(self) -> int:
  1046. return 1
  1047. # LazyConv2d defines weight as a Tensor but derived class defines it as UnitializeParameter
  1048. class LazyConv2d(_LazyConvXdMixin, Conv2d): # type: ignore[misc]
  1049. r"""A :class:`torch.nn.Conv2d` module with lazy initialization of
  1050. the ``in_channels`` argument of the :class:`Conv2d` that is inferred from
  1051. the ``input.size(1)``.
  1052. The attributes that will be lazily initialized are `weight` and `bias`.
  1053. Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
  1054. on lazy modules and their limitations.
  1055. Args:
  1056. out_channels (int): Number of channels produced by the convolution
  1057. kernel_size (int or tuple): Size of the convolving kernel
  1058. stride (int or tuple, optional): Stride of the convolution. Default: 1
  1059. padding (int or tuple, optional): Zero-padding added to both sides of
  1060. the input. Default: 0
  1061. padding_mode (string, optional): ``'zeros'``, ``'reflect'``,
  1062. ``'replicate'`` or ``'circular'``. Default: ``'zeros'``
  1063. dilation (int or tuple, optional): Spacing between kernel
  1064. elements. Default: 1
  1065. groups (int, optional): Number of blocked connections from input
  1066. channels to output channels. Default: 1
  1067. bias (bool, optional): If ``True``, adds a learnable bias to the
  1068. output. Default: ``True``
  1069. .. seealso:: :class:`torch.nn.Conv2d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
  1070. """
  1071. # super class define this variable as None. "type: ignore[..] is required
  1072. # since we are redefining the variable.
  1073. cls_to_become = Conv2d # type: ignore[assignment]
  1074. def __init__(
  1075. self,
  1076. out_channels: int,
  1077. kernel_size: _size_2_t,
  1078. stride: _size_2_t = 1,
  1079. padding: _size_2_t = 0,
  1080. dilation: _size_2_t = 1,
  1081. groups: int = 1,
  1082. bias: bool = True,
  1083. padding_mode: str = 'zeros', # TODO: refine this type
  1084. device=None,
  1085. dtype=None
  1086. ) -> None:
  1087. factory_kwargs = {'device': device, 'dtype': dtype}
  1088. super().__init__(
  1089. 0,
  1090. 0,
  1091. kernel_size,
  1092. stride,
  1093. padding,
  1094. dilation,
  1095. groups,
  1096. # bias is hardcoded to False to avoid creating tensor
  1097. # that will soon be overwritten.
  1098. False,
  1099. padding_mode,
  1100. **factory_kwargs
  1101. )
  1102. self.weight = UninitializedParameter(**factory_kwargs)
  1103. self.out_channels = out_channels
  1104. if bias:
  1105. self.bias = UninitializedParameter(**factory_kwargs)
  1106. def _get_num_spatial_dims(self) -> int:
  1107. return 2
  1108. # LazyConv3d defines weight as a Tensor but derived class defines it as UnitializeParameter
  1109. class LazyConv3d(_LazyConvXdMixin, Conv3d): # type: ignore[misc]
  1110. r"""A :class:`torch.nn.Conv3d` module with lazy initialization of
  1111. the ``in_channels`` argument of the :class:`Conv3d` that is inferred from
  1112. the ``input.size(1)``.
  1113. The attributes that will be lazily initialized are `weight` and `bias`.
  1114. Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
  1115. on lazy modules and their limitations.
  1116. Args:
  1117. out_channels (int): Number of channels produced by the convolution
  1118. kernel_size (int or tuple): Size of the convolving kernel
  1119. stride (int or tuple, optional): Stride of the convolution. Default: 1
  1120. padding (int or tuple, optional): Zero-padding added to both sides of
  1121. the input. Default: 0
  1122. padding_mode (string, optional): ``'zeros'``, ``'reflect'``,
  1123. ``'replicate'`` or ``'circular'``. Default: ``'zeros'``
  1124. dilation (int or tuple, optional): Spacing between kernel
  1125. elements. Default: 1
  1126. groups (int, optional): Number of blocked connections from input
  1127. channels to output channels. Default: 1
  1128. bias (bool, optional): If ``True``, adds a learnable bias to the
  1129. output. Default: ``True``
  1130. .. seealso:: :class:`torch.nn.Conv3d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
  1131. """
  1132. # super class define this variable as None. "type: ignore[..] is required
  1133. # since we are redefining the variable.
  1134. cls_to_become = Conv3d # type: ignore[assignment]
  1135. def __init__(
  1136. self,
  1137. out_channels: int,
  1138. kernel_size: _size_3_t,
  1139. stride: _size_3_t = 1,
  1140. padding: _size_3_t = 0,
  1141. dilation: _size_3_t = 1,
  1142. groups: int = 1,
  1143. bias: bool = True,
  1144. padding_mode: str = 'zeros',
  1145. device=None,
  1146. dtype=None
  1147. ) -> None:
  1148. factory_kwargs = {'device': device, 'dtype': dtype}
  1149. super().__init__(
  1150. 0,
  1151. 0,
  1152. kernel_size,
  1153. stride,
  1154. padding,
  1155. dilation,
  1156. groups,
  1157. # bias is hardcoded to False to avoid creating tensor
  1158. # that will soon be overwritten.
  1159. False,
  1160. padding_mode,
  1161. **factory_kwargs
  1162. )
  1163. self.weight = UninitializedParameter(**factory_kwargs)
  1164. self.out_channels = out_channels
  1165. if bias:
  1166. self.bias = UninitializedParameter(**factory_kwargs)
  1167. def _get_num_spatial_dims(self) -> int:
  1168. return 3
  1169. # LazyConvTranspose1d defines weight as a Tensor but derived class defines it as UnitializeParameter
  1170. class LazyConvTranspose1d(_LazyConvXdMixin, ConvTranspose1d): # type: ignore[misc]
  1171. r"""A :class:`torch.nn.ConvTranspose1d` module with lazy initialization of
  1172. the ``in_channels`` argument of the :class:`ConvTranspose1d` that is inferred from
  1173. the ``input.size(1)``.
  1174. The attributes that will be lazily initialized are `weight` and `bias`.
  1175. Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
  1176. on lazy modules and their limitations.
  1177. Args:
  1178. out_channels (int): Number of channels produced by the convolution
  1179. kernel_size (int or tuple): Size of the convolving kernel
  1180. stride (int or tuple, optional): Stride of the convolution. Default: 1
  1181. padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
  1182. will be added to both sides of the input. Default: 0
  1183. output_padding (int or tuple, optional): Additional size added to one side
  1184. of the output shape. Default: 0
  1185. groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
  1186. bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
  1187. dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
  1188. .. seealso:: :class:`torch.nn.ConvTranspose1d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
  1189. """
  1190. # super class define this variable as None. "type: ignore[..] is required
  1191. # since we are redefining the variable.
  1192. cls_to_become = ConvTranspose1d # type: ignore[assignment]
  1193. def __init__(
  1194. self,
  1195. out_channels: int,
  1196. kernel_size: _size_1_t,
  1197. stride: _size_1_t = 1,
  1198. padding: _size_1_t = 0,
  1199. output_padding: _size_1_t = 0,
  1200. groups: int = 1,
  1201. bias: bool = True,
  1202. dilation: _size_1_t = 1,
  1203. padding_mode: str = 'zeros',
  1204. device=None,
  1205. dtype=None
  1206. ) -> None:
  1207. factory_kwargs = {'device': device, 'dtype': dtype}
  1208. super().__init__(
  1209. 0,
  1210. 0,
  1211. kernel_size,
  1212. stride,
  1213. padding,
  1214. output_padding,
  1215. groups,
  1216. # bias is hardcoded to False to avoid creating tensor
  1217. # that will soon be overwritten.
  1218. False,
  1219. dilation,
  1220. padding_mode,
  1221. **factory_kwargs
  1222. )
  1223. self.weight = UninitializedParameter(**factory_kwargs)
  1224. self.out_channels = out_channels
  1225. if bias:
  1226. self.bias = UninitializedParameter(**factory_kwargs)
  1227. def _get_num_spatial_dims(self) -> int:
  1228. return 1
  1229. # LazyConvTranspose2d defines weight as a Tensor but derived class defines it as UnitializeParameter
  1230. class LazyConvTranspose2d(_LazyConvXdMixin, ConvTranspose2d): # type: ignore[misc]
  1231. r"""A :class:`torch.nn.ConvTranspose2d` module with lazy initialization of
  1232. the ``in_channels`` argument of the :class:`ConvTranspose2d` that is inferred from
  1233. the ``input.size(1)``.
  1234. The attributes that will be lazily initialized are `weight` and `bias`.
  1235. Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
  1236. on lazy modules and their limitations.
  1237. Args:
  1238. out_channels (int): Number of channels produced by the convolution
  1239. kernel_size (int or tuple): Size of the convolving kernel
  1240. stride (int or tuple, optional): Stride of the convolution. Default: 1
  1241. padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
  1242. will be added to both sides of each dimension in the input. Default: 0
  1243. output_padding (int or tuple, optional): Additional size added to one side
  1244. of each dimension in the output shape. Default: 0
  1245. groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
  1246. bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
  1247. dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
  1248. .. seealso:: :class:`torch.nn.ConvTranspose2d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
  1249. """
  1250. # super class define this variable as None. "type: ignore[..] is required
  1251. # since we are redefining the variable.
  1252. cls_to_become = ConvTranspose2d # type: ignore[assignment]
  1253. def __init__(
  1254. self,
  1255. out_channels: int,
  1256. kernel_size: _size_2_t,
  1257. stride: _size_2_t = 1,
  1258. padding: _size_2_t = 0,
  1259. output_padding: _size_2_t = 0,
  1260. groups: int = 1,
  1261. bias: bool = True,
  1262. dilation: int = 1,
  1263. padding_mode: str = 'zeros',
  1264. device=None,
  1265. dtype=None
  1266. ) -> None:
  1267. factory_kwargs = {'device': device, 'dtype': dtype}
  1268. super().__init__(
  1269. 0,
  1270. 0,
  1271. kernel_size,
  1272. stride,
  1273. padding,
  1274. output_padding,
  1275. groups,
  1276. # bias is hardcoded to False to avoid creating tensor
  1277. # that will soon be overwritten.
  1278. False,
  1279. dilation,
  1280. padding_mode,
  1281. **factory_kwargs
  1282. )
  1283. self.weight = UninitializedParameter(**factory_kwargs)
  1284. self.out_channels = out_channels
  1285. if bias:
  1286. self.bias = UninitializedParameter(**factory_kwargs)
  1287. def _get_num_spatial_dims(self) -> int:
  1288. return 2
  1289. # LazyConvTranspose3d defines weight as a Tensor but derived class defines it as UnitializeParameter
  1290. class LazyConvTranspose3d(_LazyConvXdMixin, ConvTranspose3d): # type: ignore[misc]
  1291. r"""A :class:`torch.nn.ConvTranspose3d` module with lazy initialization of
  1292. the ``in_channels`` argument of the :class:`ConvTranspose3d` that is inferred from
  1293. the ``input.size(1)``.
  1294. The attributes that will be lazily initialized are `weight` and `bias`.
  1295. Check the :class:`torch.nn.modules.lazy.LazyModuleMixin` for further documentation
  1296. on lazy modules and their limitations.
  1297. Args:
  1298. out_channels (int): Number of channels produced by the convolution
  1299. kernel_size (int or tuple): Size of the convolving kernel
  1300. stride (int or tuple, optional): Stride of the convolution. Default: 1
  1301. padding (int or tuple, optional): ``dilation * (kernel_size - 1) - padding`` zero-padding
  1302. will be added to both sides of each dimension in the input. Default: 0
  1303. output_padding (int or tuple, optional): Additional size added to one side
  1304. of each dimension in the output shape. Default: 0
  1305. groups (int, optional): Number of blocked connections from input channels to output channels. Default: 1
  1306. bias (bool, optional): If ``True``, adds a learnable bias to the output. Default: ``True``
  1307. dilation (int or tuple, optional): Spacing between kernel elements. Default: 1
  1308. .. seealso:: :class:`torch.nn.ConvTranspose3d` and :class:`torch.nn.modules.lazy.LazyModuleMixin`
  1309. """
  1310. # super class define this variable as None. "type: ignore[..] is required
  1311. # since we are redefining the variable.
  1312. cls_to_become = ConvTranspose3d # type: ignore[assignment]
  1313. def __init__(
  1314. self,
  1315. out_channels: int,
  1316. kernel_size: _size_3_t,
  1317. stride: _size_3_t = 1,
  1318. padding: _size_3_t = 0,
  1319. output_padding: _size_3_t = 0,
  1320. groups: int = 1,
  1321. bias: bool = True,
  1322. dilation: _size_3_t = 1,
  1323. padding_mode: str = 'zeros',
  1324. device=None,
  1325. dtype=None
  1326. ) -> None:
  1327. factory_kwargs = {'device': device, 'dtype': dtype}
  1328. super().__init__(
  1329. 0,
  1330. 0,
  1331. kernel_size,
  1332. stride,
  1333. padding,
  1334. output_padding,
  1335. groups,
  1336. # bias is hardcoded to False to avoid creating tensor
  1337. # that will soon be overwritten.
  1338. False,
  1339. dilation,
  1340. padding_mode,
  1341. **factory_kwargs
  1342. )
  1343. self.weight = UninitializedParameter(**factory_kwargs)
  1344. self.out_channels = out_channels
  1345. if bias:
  1346. self.bias = UninitializedParameter(**factory_kwargs)
  1347. def _get_num_spatial_dims(self) -> int:
  1348. return 3