conv.py 71 KB

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