pooling.py 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. from typing import List, Optional
  2. from torch import Tensor
  3. from .module import Module
  4. from .utils import _single, _pair, _triple
  5. from .. import functional as F
  6. from ..common_types import (_size_any_t, _size_1_t, _size_2_t, _size_3_t,
  7. _ratio_3_t, _ratio_2_t, _size_any_opt_t, _size_2_opt_t, _size_3_opt_t)
  8. class _MaxPoolNd(Module):
  9. __constants__ = ['kernel_size', 'stride', 'padding', 'dilation',
  10. 'return_indices', 'ceil_mode']
  11. return_indices: bool
  12. ceil_mode: bool
  13. def __init__(self, kernel_size: _size_any_t, stride: Optional[_size_any_t] = None,
  14. padding: _size_any_t = 0, dilation: _size_any_t = 1,
  15. return_indices: bool = False, ceil_mode: bool = False) -> None:
  16. super(_MaxPoolNd, self).__init__()
  17. self.kernel_size = kernel_size
  18. self.stride = stride if (stride is not None) else kernel_size
  19. self.padding = padding
  20. self.dilation = dilation
  21. self.return_indices = return_indices
  22. self.ceil_mode = ceil_mode
  23. def extra_repr(self) -> str:
  24. return 'kernel_size={kernel_size}, stride={stride}, padding={padding}' \
  25. ', dilation={dilation}, ceil_mode={ceil_mode}'.format(**self.__dict__)
  26. class MaxPool1d(_MaxPoolNd):
  27. r"""Applies a 1D max pooling over an input signal composed of several input
  28. planes.
  29. In the simplest case, the output value of the layer with input size :math:`(N, C, L)`
  30. and output :math:`(N, C, L_{out})` can be precisely described as:
  31. .. math::
  32. out(N_i, C_j, k) = \max_{m=0, \ldots, \text{kernel\_size} - 1}
  33. input(N_i, C_j, stride \times k + m)
  34. If :attr:`padding` is non-zero, then the input is implicitly padded with negative infinity on both sides
  35. for :attr:`padding` number of points. :attr:`dilation` is the stride between the elements within the
  36. sliding window. This `link`_ has a nice visualization of the pooling parameters.
  37. Note:
  38. When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
  39. or the input. Sliding windows that would start in the right padded region are ignored.
  40. Args:
  41. kernel_size: The size of the sliding window, must be > 0.
  42. stride: The stride of the sliding window, must be > 0. Default value is :attr:`kernel_size`.
  43. padding: Implicit negative infinity padding to be added on both sides, must be >= 0 and <= kernel_size / 2.
  44. dilation: The stride between elements within a sliding window, must be > 0.
  45. return_indices: If ``True``, will return the argmax along with the max values.
  46. Useful for :class:`torch.nn.MaxUnpool1d` later
  47. ceil_mode: If ``True``, will use `ceil` instead of `floor` to compute the output shape. This
  48. ensures that every element in the input tensor is covered by a sliding window.
  49. Shape:
  50. - Input: :math:`(N, C, L_{in})` or :math:`(C, L_{in})`.
  51. - Output: :math:`(N, C, L_{out})` or :math:`(C, L_{out})`, where
  52. .. math::
  53. L_{out} = \left\lfloor \frac{L_{in} + 2 \times \text{padding} - \text{dilation}
  54. \times (\text{kernel\_size} - 1) - 1}{\text{stride}} + 1\right\rfloor
  55. Examples::
  56. >>> # pool of size=3, stride=2
  57. >>> m = nn.MaxPool1d(3, stride=2)
  58. >>> input = torch.randn(20, 16, 50)
  59. >>> output = m(input)
  60. .. _link:
  61. https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
  62. """
  63. kernel_size: _size_1_t
  64. stride: _size_1_t
  65. padding: _size_1_t
  66. dilation: _size_1_t
  67. def forward(self, input: Tensor):
  68. return F.max_pool1d(input, self.kernel_size, self.stride,
  69. self.padding, self.dilation, ceil_mode=self.ceil_mode,
  70. return_indices=self.return_indices)
  71. class MaxPool2d(_MaxPoolNd):
  72. r"""Applies a 2D max pooling over an input signal composed of several input
  73. planes.
  74. In the simplest case, the output value of the layer with input size :math:`(N, C, H, W)`,
  75. output :math:`(N, C, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kH, kW)`
  76. can be precisely described as:
  77. .. math::
  78. \begin{aligned}
  79. out(N_i, C_j, h, w) ={} & \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1} \\
  80. & \text{input}(N_i, C_j, \text{stride[0]} \times h + m,
  81. \text{stride[1]} \times w + n)
  82. \end{aligned}
  83. If :attr:`padding` is non-zero, then the input is implicitly padded with negative infinity on both sides
  84. for :attr:`padding` number of points. :attr:`dilation` controls the spacing between the kernel points.
  85. It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
  86. Note:
  87. When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
  88. or the input. Sliding windows that would start in the right padded region are ignored.
  89. The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
  90. - a single ``int`` -- in which case the same value is used for the height and width dimension
  91. - a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
  92. and the second `int` for the width dimension
  93. Args:
  94. kernel_size: the size of the window to take a max over
  95. stride: the stride of the window. Default value is :attr:`kernel_size`
  96. padding: implicit zero padding to be added on both sides
  97. dilation: a parameter that controls the stride of elements in the window
  98. return_indices: if ``True``, will return the max indices along with the outputs.
  99. Useful for :class:`torch.nn.MaxUnpool2d` later
  100. ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
  101. Shape:
  102. - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`
  103. - Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
  104. .. math::
  105. H_{out} = \left\lfloor\frac{H_{in} + 2 * \text{padding[0]} - \text{dilation[0]}
  106. \times (\text{kernel\_size[0]} - 1) - 1}{\text{stride[0]}} + 1\right\rfloor
  107. .. math::
  108. W_{out} = \left\lfloor\frac{W_{in} + 2 * \text{padding[1]} - \text{dilation[1]}
  109. \times (\text{kernel\_size[1]} - 1) - 1}{\text{stride[1]}} + 1\right\rfloor
  110. Examples::
  111. >>> # pool of square window of size=3, stride=2
  112. >>> m = nn.MaxPool2d(3, stride=2)
  113. >>> # pool of non-square window
  114. >>> m = nn.MaxPool2d((3, 2), stride=(2, 1))
  115. >>> input = torch.randn(20, 16, 50, 32)
  116. >>> output = m(input)
  117. .. _link:
  118. https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
  119. """
  120. kernel_size: _size_2_t
  121. stride: _size_2_t
  122. padding: _size_2_t
  123. dilation: _size_2_t
  124. def forward(self, input: Tensor):
  125. return F.max_pool2d(input, self.kernel_size, self.stride,
  126. self.padding, self.dilation, ceil_mode=self.ceil_mode,
  127. return_indices=self.return_indices)
  128. class MaxPool3d(_MaxPoolNd):
  129. r"""Applies a 3D max pooling over an input signal composed of several input
  130. planes.
  131. In the simplest case, the output value of the layer with input size :math:`(N, C, D, H, W)`,
  132. output :math:`(N, C, D_{out}, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kD, kH, kW)`
  133. can be precisely described as:
  134. .. math::
  135. \begin{aligned}
  136. \text{out}(N_i, C_j, d, h, w) ={} & \max_{k=0, \ldots, kD-1} \max_{m=0, \ldots, kH-1} \max_{n=0, \ldots, kW-1} \\
  137. & \text{input}(N_i, C_j, \text{stride[0]} \times d + k,
  138. \text{stride[1]} \times h + m, \text{stride[2]} \times w + n)
  139. \end{aligned}
  140. If :attr:`padding` is non-zero, then the input is implicitly padded with negative infinity on both sides
  141. for :attr:`padding` number of points. :attr:`dilation` controls the spacing between the kernel points.
  142. It is harder to describe, but this `link`_ has a nice visualization of what :attr:`dilation` does.
  143. Note:
  144. When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
  145. or the input. Sliding windows that would start in the right padded region are ignored.
  146. The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding`, :attr:`dilation` can either be:
  147. - a single ``int`` -- in which case the same value is used for the depth, height and width dimension
  148. - a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension,
  149. the second `int` for the height dimension and the third `int` for the width dimension
  150. Args:
  151. kernel_size: the size of the window to take a max over
  152. stride: the stride of the window. Default value is :attr:`kernel_size`
  153. padding: implicit zero padding to be added on all three sides
  154. dilation: a parameter that controls the stride of elements in the window
  155. return_indices: if ``True``, will return the max indices along with the outputs.
  156. Useful for :class:`torch.nn.MaxUnpool3d` later
  157. ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
  158. Shape:
  159. - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
  160. - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`, where
  161. .. math::
  162. D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] - \text{dilation}[0] \times
  163. (\text{kernel\_size}[0] - 1) - 1}{\text{stride}[0]} + 1\right\rfloor
  164. .. math::
  165. H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] - \text{dilation}[1] \times
  166. (\text{kernel\_size}[1] - 1) - 1}{\text{stride}[1]} + 1\right\rfloor
  167. .. math::
  168. W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] - \text{dilation}[2] \times
  169. (\text{kernel\_size}[2] - 1) - 1}{\text{stride}[2]} + 1\right\rfloor
  170. Examples::
  171. >>> # pool of square window of size=3, stride=2
  172. >>> m = nn.MaxPool3d(3, stride=2)
  173. >>> # pool of non-square window
  174. >>> m = nn.MaxPool3d((3, 2, 2), stride=(2, 1, 2))
  175. >>> input = torch.randn(20, 16, 50,44, 31)
  176. >>> output = m(input)
  177. .. _link:
  178. https://github.com/vdumoulin/conv_arithmetic/blob/master/README.md
  179. """ # noqa: E501
  180. kernel_size: _size_3_t
  181. stride: _size_3_t
  182. padding: _size_3_t
  183. dilation: _size_3_t
  184. def forward(self, input: Tensor):
  185. return F.max_pool3d(input, self.kernel_size, self.stride,
  186. self.padding, self.dilation, ceil_mode=self.ceil_mode,
  187. return_indices=self.return_indices)
  188. class _MaxUnpoolNd(Module):
  189. def extra_repr(self) -> str:
  190. return 'kernel_size={}, stride={}, padding={}'.format(
  191. self.kernel_size, self.stride, self.padding
  192. )
  193. class MaxUnpool1d(_MaxUnpoolNd):
  194. r"""Computes a partial inverse of :class:`MaxPool1d`.
  195. :class:`MaxPool1d` is not fully invertible, since the non-maximal values are lost.
  196. :class:`MaxUnpool1d` takes in as input the output of :class:`MaxPool1d`
  197. including the indices of the maximal values and computes a partial inverse
  198. in which all non-maximal values are set to zero.
  199. .. note:: :class:`MaxPool1d` can map several input sizes to the same output
  200. sizes. Hence, the inversion process can get ambiguous.
  201. To accommodate this, you can provide the needed output size
  202. as an additional argument :attr:`output_size` in the forward call.
  203. See the Inputs and Example below.
  204. Args:
  205. kernel_size (int or tuple): Size of the max pooling window.
  206. stride (int or tuple): Stride of the max pooling window.
  207. It is set to :attr:`kernel_size` by default.
  208. padding (int or tuple): Padding that was added to the input
  209. Inputs:
  210. - `input`: the input Tensor to invert
  211. - `indices`: the indices given out by :class:`~torch.nn.MaxPool1d`
  212. - `output_size` (optional): the targeted output size
  213. Shape:
  214. - Input: :math:`(N, C, H_{in})` or :math:`(C, H_{in})`.
  215. - Output: :math:`(N, C, H_{out})` or :math:`(C, H_{out})`, where
  216. .. math::
  217. H_{out} = (H_{in} - 1) \times \text{stride}[0] - 2 \times \text{padding}[0] + \text{kernel\_size}[0]
  218. or as given by :attr:`output_size` in the call operator
  219. Example::
  220. >>> pool = nn.MaxPool1d(2, stride=2, return_indices=True)
  221. >>> unpool = nn.MaxUnpool1d(2, stride=2)
  222. >>> input = torch.tensor([[[1., 2, 3, 4, 5, 6, 7, 8]]])
  223. >>> output, indices = pool(input)
  224. >>> unpool(output, indices)
  225. tensor([[[ 0., 2., 0., 4., 0., 6., 0., 8.]]])
  226. >>> # Example showcasing the use of output_size
  227. >>> input = torch.tensor([[[1., 2, 3, 4, 5, 6, 7, 8, 9]]])
  228. >>> output, indices = pool(input)
  229. >>> unpool(output, indices, output_size=input.size())
  230. tensor([[[ 0., 2., 0., 4., 0., 6., 0., 8., 0.]]])
  231. >>> unpool(output, indices)
  232. tensor([[[ 0., 2., 0., 4., 0., 6., 0., 8.]]])
  233. """
  234. kernel_size: _size_1_t
  235. stride: _size_1_t
  236. padding: _size_1_t
  237. def __init__(self, kernel_size: _size_1_t, stride: Optional[_size_1_t] = None, padding: _size_1_t = 0) -> None:
  238. super(MaxUnpool1d, self).__init__()
  239. self.kernel_size = _single(kernel_size)
  240. self.stride = _single(stride if (stride is not None) else kernel_size)
  241. self.padding = _single(padding)
  242. def forward(self, input: Tensor, indices: Tensor, output_size: Optional[List[int]] = None) -> Tensor:
  243. return F.max_unpool1d(input, indices, self.kernel_size, self.stride,
  244. self.padding, output_size)
  245. class MaxUnpool2d(_MaxUnpoolNd):
  246. r"""Computes a partial inverse of :class:`MaxPool2d`.
  247. :class:`MaxPool2d` is not fully invertible, since the non-maximal values are lost.
  248. :class:`MaxUnpool2d` takes in as input the output of :class:`MaxPool2d`
  249. including the indices of the maximal values and computes a partial inverse
  250. in which all non-maximal values are set to zero.
  251. .. note:: :class:`MaxPool2d` can map several input sizes to the same output
  252. sizes. Hence, the inversion process can get ambiguous.
  253. To accommodate this, you can provide the needed output size
  254. as an additional argument :attr:`output_size` in the forward call.
  255. See the Inputs and Example below.
  256. Args:
  257. kernel_size (int or tuple): Size of the max pooling window.
  258. stride (int or tuple): Stride of the max pooling window.
  259. It is set to :attr:`kernel_size` by default.
  260. padding (int or tuple): Padding that was added to the input
  261. Inputs:
  262. - `input`: the input Tensor to invert
  263. - `indices`: the indices given out by :class:`~torch.nn.MaxPool2d`
  264. - `output_size` (optional): the targeted output size
  265. Shape:
  266. - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
  267. - Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
  268. .. math::
  269. H_{out} = (H_{in} - 1) \times \text{stride[0]} - 2 \times \text{padding[0]} + \text{kernel\_size[0]}
  270. .. math::
  271. W_{out} = (W_{in} - 1) \times \text{stride[1]} - 2 \times \text{padding[1]} + \text{kernel\_size[1]}
  272. or as given by :attr:`output_size` in the call operator
  273. Example::
  274. >>> pool = nn.MaxPool2d(2, stride=2, return_indices=True)
  275. >>> unpool = nn.MaxUnpool2d(2, stride=2)
  276. >>> input = torch.tensor([[[[ 1., 2., 3., 4.],
  277. [ 5., 6., 7., 8.],
  278. [ 9., 10., 11., 12.],
  279. [13., 14., 15., 16.]]]])
  280. >>> output, indices = pool(input)
  281. >>> unpool(output, indices)
  282. tensor([[[[ 0., 0., 0., 0.],
  283. [ 0., 6., 0., 8.],
  284. [ 0., 0., 0., 0.],
  285. [ 0., 14., 0., 16.]]]])
  286. >>> # Now using output_size to resolve an ambiguous size for the inverse
  287. >>> input = torch.torch.tensor([[[[ 1., 2., 3., 4., 5.],
  288. [ 6., 7., 8., 9., 10.],
  289. [11., 12., 13., 14., 15.],
  290. [16., 17., 18., 19., 20.]]]])
  291. >>> output, indices = pool(input)
  292. >>> # This call will not work without specifying output_size
  293. >>> unpool(output, indices, output_size=input.size())
  294. tensor([[[[ 0., 0., 0., 0., 0.],
  295. [ 0., 7., 0., 9., 0.],
  296. [ 0., 0., 0., 0., 0.],
  297. [ 0., 17., 0., 19., 0.]]]])
  298. """
  299. kernel_size: _size_2_t
  300. stride: _size_2_t
  301. padding: _size_2_t
  302. def __init__(self, kernel_size: _size_2_t, stride: Optional[_size_2_t] = None, padding: _size_2_t = 0) -> None:
  303. super(MaxUnpool2d, self).__init__()
  304. self.kernel_size = _pair(kernel_size)
  305. self.stride = _pair(stride if (stride is not None) else kernel_size)
  306. self.padding = _pair(padding)
  307. def forward(self, input: Tensor, indices: Tensor, output_size: Optional[List[int]] = None) -> Tensor:
  308. return F.max_unpool2d(input, indices, self.kernel_size, self.stride,
  309. self.padding, output_size)
  310. class MaxUnpool3d(_MaxUnpoolNd):
  311. r"""Computes a partial inverse of :class:`MaxPool3d`.
  312. :class:`MaxPool3d` is not fully invertible, since the non-maximal values are lost.
  313. :class:`MaxUnpool3d` takes in as input the output of :class:`MaxPool3d`
  314. including the indices of the maximal values and computes a partial inverse
  315. in which all non-maximal values are set to zero.
  316. .. note:: :class:`MaxPool3d` can map several input sizes to the same output
  317. sizes. Hence, the inversion process can get ambiguous.
  318. To accommodate this, you can provide the needed output size
  319. as an additional argument :attr:`output_size` in the forward call.
  320. See the Inputs section below.
  321. Args:
  322. kernel_size (int or tuple): Size of the max pooling window.
  323. stride (int or tuple): Stride of the max pooling window.
  324. It is set to :attr:`kernel_size` by default.
  325. padding (int or tuple): Padding that was added to the input
  326. Inputs:
  327. - `input`: the input Tensor to invert
  328. - `indices`: the indices given out by :class:`~torch.nn.MaxPool3d`
  329. - `output_size` (optional): the targeted output size
  330. Shape:
  331. - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
  332. - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`, where
  333. .. math::
  334. D_{out} = (D_{in} - 1) \times \text{stride[0]} - 2 \times \text{padding[0]} + \text{kernel\_size[0]}
  335. .. math::
  336. H_{out} = (H_{in} - 1) \times \text{stride[1]} - 2 \times \text{padding[1]} + \text{kernel\_size[1]}
  337. .. math::
  338. W_{out} = (W_{in} - 1) \times \text{stride[2]} - 2 \times \text{padding[2]} + \text{kernel\_size[2]}
  339. or as given by :attr:`output_size` in the call operator
  340. Example::
  341. >>> # pool of square window of size=3, stride=2
  342. >>> pool = nn.MaxPool3d(3, stride=2, return_indices=True)
  343. >>> unpool = nn.MaxUnpool3d(3, stride=2)
  344. >>> output, indices = pool(torch.randn(20, 16, 51, 33, 15))
  345. >>> unpooled_output = unpool(output, indices)
  346. >>> unpooled_output.size()
  347. torch.Size([20, 16, 51, 33, 15])
  348. """
  349. kernel_size: _size_3_t
  350. stride: _size_3_t
  351. padding: _size_3_t
  352. def __init__(self, kernel_size: _size_3_t, stride: Optional[_size_3_t] = None, padding: _size_3_t = 0) -> None:
  353. super(MaxUnpool3d, self).__init__()
  354. self.kernel_size = _triple(kernel_size)
  355. self.stride = _triple(stride if (stride is not None) else kernel_size)
  356. self.padding = _triple(padding)
  357. def forward(self, input: Tensor, indices: Tensor, output_size: Optional[List[int]] = None) -> Tensor:
  358. return F.max_unpool3d(input, indices, self.kernel_size, self.stride,
  359. self.padding, output_size)
  360. class _AvgPoolNd(Module):
  361. __constants__ = ['kernel_size', 'stride', 'padding', 'ceil_mode', 'count_include_pad']
  362. def extra_repr(self) -> str:
  363. return 'kernel_size={}, stride={}, padding={}'.format(
  364. self.kernel_size, self.stride, self.padding
  365. )
  366. class AvgPool1d(_AvgPoolNd):
  367. r"""Applies a 1D average pooling over an input signal composed of several
  368. input planes.
  369. In the simplest case, the output value of the layer with input size :math:`(N, C, L)`,
  370. output :math:`(N, C, L_{out})` and :attr:`kernel_size` :math:`k`
  371. can be precisely described as:
  372. .. math::
  373. \text{out}(N_i, C_j, l) = \frac{1}{k} \sum_{m=0}^{k-1}
  374. \text{input}(N_i, C_j, \text{stride} \times l + m)
  375. If :attr:`padding` is non-zero, then the input is implicitly zero-padded on both sides
  376. for :attr:`padding` number of points.
  377. Note:
  378. When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
  379. or the input. Sliding windows that would start in the right padded region are ignored.
  380. The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding` can each be
  381. an ``int`` or a one-element tuple.
  382. Args:
  383. kernel_size: the size of the window
  384. stride: the stride of the window. Default value is :attr:`kernel_size`
  385. padding: implicit zero padding to be added on both sides
  386. ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
  387. count_include_pad: when True, will include the zero-padding in the averaging calculation
  388. Shape:
  389. - Input: :math:`(N, C, L_{in})` or :math:`(C, L_{in})`.
  390. - Output: :math:`(N, C, L_{out})` or :math:`(C, L_{out})`, where
  391. .. math::
  392. L_{out} = \left\lfloor \frac{L_{in} +
  393. 2 \times \text{padding} - \text{kernel\_size}}{\text{stride}} + 1\right\rfloor
  394. Examples::
  395. >>> # pool with window of size=3, stride=2
  396. >>> m = nn.AvgPool1d(3, stride=2)
  397. >>> m(torch.tensor([[[1.,2,3,4,5,6,7]]]))
  398. tensor([[[ 2., 4., 6.]]])
  399. """
  400. kernel_size: _size_1_t
  401. stride: _size_1_t
  402. padding: _size_1_t
  403. ceil_mode: bool
  404. count_include_pad: bool
  405. def __init__(self, kernel_size: _size_1_t, stride: _size_1_t = None, padding: _size_1_t = 0, ceil_mode: bool = False,
  406. count_include_pad: bool = True) -> None:
  407. super(AvgPool1d, self).__init__()
  408. self.kernel_size = _single(kernel_size)
  409. self.stride = _single(stride if stride is not None else kernel_size)
  410. self.padding = _single(padding)
  411. self.ceil_mode = ceil_mode
  412. self.count_include_pad = count_include_pad
  413. def forward(self, input: Tensor) -> Tensor:
  414. return F.avg_pool1d(
  415. input, self.kernel_size, self.stride, self.padding, self.ceil_mode,
  416. self.count_include_pad)
  417. class AvgPool2d(_AvgPoolNd):
  418. r"""Applies a 2D average pooling over an input signal composed of several input
  419. planes.
  420. In the simplest case, the output value of the layer with input size :math:`(N, C, H, W)`,
  421. output :math:`(N, C, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kH, kW)`
  422. can be precisely described as:
  423. .. math::
  424. out(N_i, C_j, h, w) = \frac{1}{kH * kW} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1}
  425. input(N_i, C_j, stride[0] \times h + m, stride[1] \times w + n)
  426. If :attr:`padding` is non-zero, then the input is implicitly zero-padded on both sides
  427. for :attr:`padding` number of points.
  428. Note:
  429. When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
  430. or the input. Sliding windows that would start in the right padded region are ignored.
  431. The parameters :attr:`kernel_size`, :attr:`stride`, :attr:`padding` can either be:
  432. - a single ``int`` -- in which case the same value is used for the height and width dimension
  433. - a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
  434. and the second `int` for the width dimension
  435. Args:
  436. kernel_size: the size of the window
  437. stride: the stride of the window. Default value is :attr:`kernel_size`
  438. padding: implicit zero padding to be added on both sides
  439. ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
  440. count_include_pad: when True, will include the zero-padding in the averaging calculation
  441. divisor_override: if specified, it will be used as divisor, otherwise size of the pooling region will be used.
  442. Shape:
  443. - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
  444. - Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
  445. .. math::
  446. H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[0] -
  447. \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor
  448. .. math::
  449. W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[1] -
  450. \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
  451. Examples::
  452. >>> # pool of square window of size=3, stride=2
  453. >>> m = nn.AvgPool2d(3, stride=2)
  454. >>> # pool of non-square window
  455. >>> m = nn.AvgPool2d((3, 2), stride=(2, 1))
  456. >>> input = torch.randn(20, 16, 50, 32)
  457. >>> output = m(input)
  458. """
  459. __constants__ = ['kernel_size', 'stride', 'padding', 'ceil_mode', 'count_include_pad', 'divisor_override']
  460. kernel_size: _size_2_t
  461. stride: _size_2_t
  462. padding: _size_2_t
  463. ceil_mode: bool
  464. count_include_pad: bool
  465. def __init__(self, kernel_size: _size_2_t, stride: Optional[_size_2_t] = None, padding: _size_2_t = 0,
  466. ceil_mode: bool = False, count_include_pad: bool = True, divisor_override: Optional[int] = None) -> None:
  467. super(AvgPool2d, self).__init__()
  468. self.kernel_size = kernel_size
  469. self.stride = stride if (stride is not None) else kernel_size
  470. self.padding = padding
  471. self.ceil_mode = ceil_mode
  472. self.count_include_pad = count_include_pad
  473. self.divisor_override = divisor_override
  474. def forward(self, input: Tensor) -> Tensor:
  475. return F.avg_pool2d(input, self.kernel_size, self.stride,
  476. self.padding, self.ceil_mode, self.count_include_pad, self.divisor_override)
  477. class AvgPool3d(_AvgPoolNd):
  478. r"""Applies a 3D average pooling over an input signal composed of several input
  479. planes.
  480. In the simplest case, the output value of the layer with input size :math:`(N, C, D, H, W)`,
  481. output :math:`(N, C, D_{out}, H_{out}, W_{out})` and :attr:`kernel_size` :math:`(kD, kH, kW)`
  482. can be precisely described as:
  483. .. math::
  484. \begin{aligned}
  485. \text{out}(N_i, C_j, d, h, w) ={} & \sum_{k=0}^{kD-1} \sum_{m=0}^{kH-1} \sum_{n=0}^{kW-1} \\
  486. & \frac{\text{input}(N_i, C_j, \text{stride}[0] \times d + k,
  487. \text{stride}[1] \times h + m, \text{stride}[2] \times w + n)}
  488. {kD \times kH \times kW}
  489. \end{aligned}
  490. If :attr:`padding` is non-zero, then the input is implicitly zero-padded on all three sides
  491. for :attr:`padding` number of points.
  492. Note:
  493. When ceil_mode=True, sliding windows are allowed to go off-bounds if they start within the left padding
  494. or the input. Sliding windows that would start in the right padded region are ignored.
  495. The parameters :attr:`kernel_size`, :attr:`stride` can either be:
  496. - a single ``int`` -- in which case the same value is used for the depth, height and width dimension
  497. - a ``tuple`` of three ints -- in which case, the first `int` is used for the depth dimension,
  498. the second `int` for the height dimension and the third `int` for the width dimension
  499. Args:
  500. kernel_size: the size of the window
  501. stride: the stride of the window. Default value is :attr:`kernel_size`
  502. padding: implicit zero padding to be added on all three sides
  503. ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
  504. count_include_pad: when True, will include the zero-padding in the averaging calculation
  505. divisor_override: if specified, it will be used as divisor, otherwise :attr:`kernel_size` will be used
  506. Shape:
  507. - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
  508. - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or
  509. :math:`(C, D_{out}, H_{out}, W_{out})`, where
  510. .. math::
  511. D_{out} = \left\lfloor\frac{D_{in} + 2 \times \text{padding}[0] -
  512. \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor
  513. .. math::
  514. H_{out} = \left\lfloor\frac{H_{in} + 2 \times \text{padding}[1] -
  515. \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
  516. .. math::
  517. W_{out} = \left\lfloor\frac{W_{in} + 2 \times \text{padding}[2] -
  518. \text{kernel\_size}[2]}{\text{stride}[2]} + 1\right\rfloor
  519. Examples::
  520. >>> # pool of square window of size=3, stride=2
  521. >>> m = nn.AvgPool3d(3, stride=2)
  522. >>> # pool of non-square window
  523. >>> m = nn.AvgPool3d((3, 2, 2), stride=(2, 1, 2))
  524. >>> input = torch.randn(20, 16, 50,44, 31)
  525. >>> output = m(input)
  526. """
  527. __constants__ = ['kernel_size', 'stride', 'padding', 'ceil_mode', 'count_include_pad', 'divisor_override']
  528. kernel_size: _size_3_t
  529. stride: _size_3_t
  530. padding: _size_3_t
  531. ceil_mode: bool
  532. count_include_pad: bool
  533. def __init__(self, kernel_size: _size_3_t, stride: Optional[_size_3_t] = None, padding: _size_3_t = 0,
  534. ceil_mode: bool = False, count_include_pad: bool = True, divisor_override: Optional[int] = None) -> None:
  535. super(AvgPool3d, self).__init__()
  536. self.kernel_size = kernel_size
  537. self.stride = stride if (stride is not None) else kernel_size
  538. self.padding = padding
  539. self.ceil_mode = ceil_mode
  540. self.count_include_pad = count_include_pad
  541. self.divisor_override = divisor_override
  542. def forward(self, input: Tensor) -> Tensor:
  543. return F.avg_pool3d(input, self.kernel_size, self.stride,
  544. self.padding, self.ceil_mode, self.count_include_pad, self.divisor_override)
  545. def __setstate__(self, d):
  546. super(AvgPool3d, self).__setstate__(d)
  547. self.__dict__.setdefault('padding', 0)
  548. self.__dict__.setdefault('ceil_mode', False)
  549. self.__dict__.setdefault('count_include_pad', True)
  550. class FractionalMaxPool2d(Module):
  551. r"""Applies a 2D fractional max pooling over an input signal composed of several input planes.
  552. Fractional MaxPooling is described in detail in the paper `Fractional MaxPooling`_ by Ben Graham
  553. The max-pooling operation is applied in :math:`kH \times kW` regions by a stochastic
  554. step size determined by the target output size.
  555. The number of output features is equal to the number of input planes.
  556. Args:
  557. kernel_size: the size of the window to take a max over.
  558. Can be a single number k (for a square kernel of k x k) or a tuple `(kh, kw)`
  559. output_size: the target output size of the image of the form `oH x oW`.
  560. Can be a tuple `(oH, oW)` or a single number oH for a square image `oH x oH`
  561. output_ratio: If one wants to have an output size as a ratio of the input size, this option can be given.
  562. This has to be a number or tuple in the range (0, 1)
  563. return_indices: if ``True``, will return the indices along with the outputs.
  564. Useful to pass to :meth:`nn.MaxUnpool2d`. Default: ``False``
  565. Shape:
  566. - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
  567. - Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
  568. :math:`(H_{out}, W_{out})=\text{output\_size}` or
  569. :math:`(H_{out}, W_{out})=\text{output\_ratio} \times (H_{in}, W_{in})`.
  570. Examples:
  571. >>> # pool of square window of size=3, and target output size 13x12
  572. >>> m = nn.FractionalMaxPool2d(3, output_size=(13, 12))
  573. >>> # pool of square window and target output size being half of input image size
  574. >>> m = nn.FractionalMaxPool2d(3, output_ratio=(0.5, 0.5))
  575. >>> input = torch.randn(20, 16, 50, 32)
  576. >>> output = m(input)
  577. .. _Fractional MaxPooling:
  578. https://arxiv.org/abs/1412.6071
  579. """
  580. __constants__ = ['kernel_size', 'return_indices', 'output_size',
  581. 'output_ratio']
  582. kernel_size: _size_2_t
  583. return_indices: bool
  584. output_size: _size_2_t
  585. output_ratio: _ratio_2_t
  586. def __init__(self, kernel_size: _size_2_t, output_size: Optional[_size_2_t] = None,
  587. output_ratio: Optional[_ratio_2_t] = None,
  588. return_indices: bool = False, _random_samples=None) -> None:
  589. super(FractionalMaxPool2d, self).__init__()
  590. self.kernel_size = _pair(kernel_size)
  591. self.return_indices = return_indices
  592. self.register_buffer('_random_samples', _random_samples)
  593. self.output_size = _pair(output_size) if output_size is not None else None
  594. self.output_ratio = _pair(output_ratio) if output_ratio is not None else None
  595. if output_size is None and output_ratio is None:
  596. raise ValueError("FractionalMaxPool2d requires specifying either "
  597. "an output size, or a pooling ratio")
  598. if output_size is not None and output_ratio is not None:
  599. raise ValueError("only one of output_size and output_ratio may be specified")
  600. if self.output_ratio is not None:
  601. if not (0 < self.output_ratio[0] < 1 and 0 < self.output_ratio[1] < 1):
  602. raise ValueError("output_ratio must be between 0 and 1 (got {})"
  603. .format(output_ratio))
  604. def forward(self, input: Tensor):
  605. return F.fractional_max_pool2d(
  606. input, self.kernel_size, self.output_size, self.output_ratio,
  607. self.return_indices,
  608. _random_samples=self._random_samples)
  609. class FractionalMaxPool3d(Module):
  610. r"""Applies a 3D fractional max pooling over an input signal composed of several input planes.
  611. Fractional MaxPooling is described in detail in the paper `Fractional MaxPooling`_ by Ben Graham
  612. The max-pooling operation is applied in :math:`kT \times kH \times kW` regions by a stochastic
  613. step size determined by the target output size.
  614. The number of output features is equal to the number of input planes.
  615. Args:
  616. kernel_size: the size of the window to take a max over.
  617. Can be a single number k (for a square kernel of k x k x k) or a tuple `(kt x kh x kw)`
  618. output_size: the target output size of the image of the form `oT x oH x oW`.
  619. Can be a tuple `(oT, oH, oW)` or a single number oH for a square image `oH x oH x oH`
  620. output_ratio: If one wants to have an output size as a ratio of the input size, this option can be given.
  621. This has to be a number or tuple in the range (0, 1)
  622. return_indices: if ``True``, will return the indices along with the outputs.
  623. Useful to pass to :meth:`nn.MaxUnpool3d`. Default: ``False``
  624. Shape:
  625. - Input: :math:`(N, C, T_{in}, H_{in}, W_{in})` or :math:`(C, T_{in}, H_{in}, W_{in})`.
  626. - Output: :math:`(N, C, T_{out}, H_{out}, W_{out})` or :math:`(C, T_{out}, H_{out}, W_{out})`, where
  627. :math:`(T_{out}, H_{out}, W_{out})=\text{output\_size}` or
  628. :math:`(T_{out}, H_{out}, W_{out})=\text{output\_ratio} \times (T_{in}, H_{in}, W_{in})`
  629. Examples:
  630. >>> # pool of cubic window of size=3, and target output size 13x12x11
  631. >>> m = nn.FractionalMaxPool3d(3, output_size=(13, 12, 11))
  632. >>> # pool of cubic window and target output size being half of input size
  633. >>> m = nn.FractionalMaxPool3d(3, output_ratio=(0.5, 0.5, 0.5))
  634. >>> input = torch.randn(20, 16, 50, 32, 16)
  635. >>> output = m(input)
  636. .. _Fractional MaxPooling:
  637. https://arxiv.org/abs/1412.6071
  638. """
  639. __constants__ = ['kernel_size', 'return_indices', 'output_size',
  640. 'output_ratio']
  641. kernel_size: _size_3_t
  642. return_indices: bool
  643. output_size: _size_3_t
  644. output_ratio: _ratio_3_t
  645. def __init__(self, kernel_size: _size_3_t, output_size: Optional[_size_3_t] = None,
  646. output_ratio: Optional[_ratio_3_t] = None,
  647. return_indices: bool = False, _random_samples=None) -> None:
  648. super(FractionalMaxPool3d, self).__init__()
  649. self.kernel_size = _triple(kernel_size)
  650. self.return_indices = return_indices
  651. self.register_buffer('_random_samples', _random_samples)
  652. self.output_size = _triple(output_size) if output_size is not None else None
  653. self.output_ratio = _triple(output_ratio) if output_ratio is not None else None
  654. if output_size is None and output_ratio is None:
  655. raise ValueError("FractionalMaxPool3d requires specifying either "
  656. "an output size, or a pooling ratio")
  657. if output_size is not None and output_ratio is not None:
  658. raise ValueError("only one of output_size and output_ratio may be specified")
  659. if self.output_ratio is not None:
  660. if not (0 < self.output_ratio[0] < 1 and 0 < self.output_ratio[1] < 1 and 0 < self.output_ratio[2] < 1):
  661. raise ValueError("output_ratio must be between 0 and 1 (got {})"
  662. .format(output_ratio))
  663. def forward(self, input: Tensor):
  664. return F.fractional_max_pool3d(
  665. input, self.kernel_size, self.output_size, self.output_ratio,
  666. self.return_indices,
  667. _random_samples=self._random_samples)
  668. class _LPPoolNd(Module):
  669. __constants__ = ['norm_type', 'kernel_size', 'stride', 'ceil_mode']
  670. norm_type: float
  671. ceil_mode: bool
  672. def __init__(self, norm_type: float, kernel_size: _size_any_t, stride: Optional[_size_any_t] = None,
  673. ceil_mode: bool = False) -> None:
  674. super(_LPPoolNd, self).__init__()
  675. self.norm_type = norm_type
  676. self.kernel_size = kernel_size
  677. self.stride = stride
  678. self.ceil_mode = ceil_mode
  679. def extra_repr(self) -> str:
  680. return 'norm_type={norm_type}, kernel_size={kernel_size}, stride={stride}, ' \
  681. 'ceil_mode={ceil_mode}'.format(**self.__dict__)
  682. class LPPool1d(_LPPoolNd):
  683. r"""Applies a 1D power-average pooling over an input signal composed of several input
  684. planes.
  685. On each window, the function computed is:
  686. .. math::
  687. f(X) = \sqrt[p]{\sum_{x \in X} x^{p}}
  688. - At p = :math:`\infty`, one gets Max Pooling
  689. - At p = 1, one gets Sum Pooling (which is proportional to Average Pooling)
  690. .. note:: If the sum to the power of `p` is zero, the gradient of this function is
  691. not defined. This implementation will set the gradient to zero in this case.
  692. Args:
  693. kernel_size: a single int, the size of the window
  694. stride: a single int, the stride of the window. Default value is :attr:`kernel_size`
  695. ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
  696. Shape:
  697. - Input: :math:`(N, C, L_{in})` or :math:`(C, L_{in})`.
  698. - Output: :math:`(N, C, L_{out})` or :math:`(C, L_{out})`, where
  699. .. math::
  700. L_{out} = \left\lfloor\frac{L_{in} - \text{kernel\_size}}{\text{stride}} + 1\right\rfloor
  701. Examples::
  702. >>> # power-2 pool of window of length 3, with stride 2.
  703. >>> m = nn.LPPool1d(2, 3, stride=2)
  704. >>> input = torch.randn(20, 16, 50)
  705. >>> output = m(input)
  706. """
  707. kernel_size: _size_1_t
  708. stride: _size_1_t
  709. def forward(self, input: Tensor) -> Tensor:
  710. return F.lp_pool1d(input, float(self.norm_type), self.kernel_size,
  711. self.stride, self.ceil_mode)
  712. class LPPool2d(_LPPoolNd):
  713. r"""Applies a 2D power-average pooling over an input signal composed of several input
  714. planes.
  715. On each window, the function computed is:
  716. .. math::
  717. f(X) = \sqrt[p]{\sum_{x \in X} x^{p}}
  718. - At p = :math:`\infty`, one gets Max Pooling
  719. - At p = 1, one gets Sum Pooling (which is proportional to average pooling)
  720. The parameters :attr:`kernel_size`, :attr:`stride` can either be:
  721. - a single ``int`` -- in which case the same value is used for the height and width dimension
  722. - a ``tuple`` of two ints -- in which case, the first `int` is used for the height dimension,
  723. and the second `int` for the width dimension
  724. .. note:: If the sum to the power of `p` is zero, the gradient of this function is
  725. not defined. This implementation will set the gradient to zero in this case.
  726. Args:
  727. kernel_size: the size of the window
  728. stride: the stride of the window. Default value is :attr:`kernel_size`
  729. ceil_mode: when True, will use `ceil` instead of `floor` to compute the output shape
  730. Shape:
  731. - Input: :math:`(N, C, H_{in}, W_{in})`
  732. - Output: :math:`(N, C, H_{out}, W_{out})`, where
  733. .. math::
  734. H_{out} = \left\lfloor\frac{H_{in} - \text{kernel\_size}[0]}{\text{stride}[0]} + 1\right\rfloor
  735. .. math::
  736. W_{out} = \left\lfloor\frac{W_{in} - \text{kernel\_size}[1]}{\text{stride}[1]} + 1\right\rfloor
  737. Examples::
  738. >>> # power-2 pool of square window of size=3, stride=2
  739. >>> m = nn.LPPool2d(2, 3, stride=2)
  740. >>> # pool of non-square window of power 1.2
  741. >>> m = nn.LPPool2d(1.2, (3, 2), stride=(2, 1))
  742. >>> input = torch.randn(20, 16, 50, 32)
  743. >>> output = m(input)
  744. """
  745. kernel_size: _size_2_t
  746. stride: _size_2_t
  747. def forward(self, input: Tensor) -> Tensor:
  748. return F.lp_pool2d(input, float(self.norm_type), self.kernel_size,
  749. self.stride, self.ceil_mode)
  750. class _AdaptiveMaxPoolNd(Module):
  751. __constants__ = ['output_size', 'return_indices']
  752. return_indices: bool
  753. def __init__(self, output_size: _size_any_opt_t, return_indices: bool = False) -> None:
  754. super(_AdaptiveMaxPoolNd, self).__init__()
  755. self.output_size = output_size
  756. self.return_indices = return_indices
  757. def extra_repr(self) -> str:
  758. return 'output_size={}'.format(self.output_size)
  759. # FIXME (by @ssnl): Improve adaptive pooling docs: specify what the input and
  760. # output shapes are, and how the operation computes output.
  761. class AdaptiveMaxPool1d(_AdaptiveMaxPoolNd):
  762. r"""Applies a 1D adaptive max pooling over an input signal composed of several input planes.
  763. The output size is :math:`L_{out}`, for any input size.
  764. The number of output features is equal to the number of input planes.
  765. Args:
  766. output_size: the target output size :math:`L_{out}`.
  767. return_indices: if ``True``, will return the indices along with the outputs.
  768. Useful to pass to nn.MaxUnpool1d. Default: ``False``
  769. Shape:
  770. - Input: :math:`(N, C, L_{in})` or :math:`(C, L_{in})`.
  771. - Output: :math:`(N, C, L_{out})` or :math:`(C, L_{out})`, where
  772. :math:`L_{out}=\text{output\_size}`.
  773. Examples:
  774. >>> # target output size of 5
  775. >>> m = nn.AdaptiveMaxPool1d(5)
  776. >>> input = torch.randn(1, 64, 8)
  777. >>> output = m(input)
  778. """
  779. output_size: _size_1_t
  780. def forward(self, input: Tensor) -> Tensor:
  781. return F.adaptive_max_pool1d(input, self.output_size, self.return_indices)
  782. class AdaptiveMaxPool2d(_AdaptiveMaxPoolNd):
  783. r"""Applies a 2D adaptive max pooling over an input signal composed of several input planes.
  784. The output is of size :math:`H_{out} \times W_{out}`, for any input size.
  785. The number of output features is equal to the number of input planes.
  786. Args:
  787. output_size: the target output size of the image of the form :math:`H_{out} \times W_{out}`.
  788. Can be a tuple :math:`(H_{out}, W_{out})` or a single :math:`H_{out}` for a
  789. square image :math:`H_{out} \times H_{out}`. :math:`H_{out}` and :math:`W_{out}`
  790. can be either a ``int``, or ``None`` which means the size will be the same as that
  791. of the input.
  792. return_indices: if ``True``, will return the indices along with the outputs.
  793. Useful to pass to nn.MaxUnpool2d. Default: ``False``
  794. Shape:
  795. - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
  796. - Output: :math:`(N, C, H_{out}, W_{out})` or :math:`(C, H_{out}, W_{out})`, where
  797. :math:`(H_{out}, W_{out})=\text{output\_size}`.
  798. Examples:
  799. >>> # target output size of 5x7
  800. >>> m = nn.AdaptiveMaxPool2d((5,7))
  801. >>> input = torch.randn(1, 64, 8, 9)
  802. >>> output = m(input)
  803. >>> # target output size of 7x7 (square)
  804. >>> m = nn.AdaptiveMaxPool2d(7)
  805. >>> input = torch.randn(1, 64, 10, 9)
  806. >>> output = m(input)
  807. >>> # target output size of 10x7
  808. >>> m = nn.AdaptiveMaxPool2d((None, 7))
  809. >>> input = torch.randn(1, 64, 10, 9)
  810. >>> output = m(input)
  811. """
  812. output_size: _size_2_opt_t
  813. def forward(self, input: Tensor):
  814. return F.adaptive_max_pool2d(input, self.output_size, self.return_indices)
  815. class AdaptiveMaxPool3d(_AdaptiveMaxPoolNd):
  816. r"""Applies a 3D adaptive max pooling over an input signal composed of several input planes.
  817. The output is of size :math:`D_{out} \times H_{out} \times W_{out}`, for any input size.
  818. The number of output features is equal to the number of input planes.
  819. Args:
  820. output_size: the target output size of the image of the form :math:`D_{out} \times H_{out} \times W_{out}`.
  821. Can be a tuple :math:`(D_{out}, H_{out}, W_{out})` or a single
  822. :math:`D_{out}` for a cube :math:`D_{out} \times D_{out} \times D_{out}`.
  823. :math:`D_{out}`, :math:`H_{out}` and :math:`W_{out}` can be either a
  824. ``int``, or ``None`` which means the size will be the same as that of the input.
  825. return_indices: if ``True``, will return the indices along with the outputs.
  826. Useful to pass to nn.MaxUnpool3d. Default: ``False``
  827. Shape:
  828. - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
  829. - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})` or :math:`(C, D_{out}, H_{out}, W_{out})`,
  830. where :math:`(D_{out}, H_{out}, W_{out})=\text{output\_size}`.
  831. Examples:
  832. >>> # target output size of 5x7x9
  833. >>> m = nn.AdaptiveMaxPool3d((5,7,9))
  834. >>> input = torch.randn(1, 64, 8, 9, 10)
  835. >>> output = m(input)
  836. >>> # target output size of 7x7x7 (cube)
  837. >>> m = nn.AdaptiveMaxPool3d(7)
  838. >>> input = torch.randn(1, 64, 10, 9, 8)
  839. >>> output = m(input)
  840. >>> # target output size of 7x9x8
  841. >>> m = nn.AdaptiveMaxPool3d((7, None, None))
  842. >>> input = torch.randn(1, 64, 10, 9, 8)
  843. >>> output = m(input)
  844. """
  845. output_size: _size_3_opt_t
  846. def forward(self, input: Tensor):
  847. return F.adaptive_max_pool3d(input, self.output_size, self.return_indices)
  848. class _AdaptiveAvgPoolNd(Module):
  849. __constants__ = ['output_size']
  850. def __init__(self, output_size: _size_any_opt_t) -> None:
  851. super(_AdaptiveAvgPoolNd, self).__init__()
  852. self.output_size = output_size
  853. def extra_repr(self) -> str:
  854. return 'output_size={}'.format(self.output_size)
  855. class AdaptiveAvgPool1d(_AdaptiveAvgPoolNd):
  856. r"""Applies a 1D adaptive average pooling over an input signal composed of several input planes.
  857. The output size is :math:`L_{out}`, for any input size.
  858. The number of output features is equal to the number of input planes.
  859. Args:
  860. output_size: the target output size :math:`L_{out}`.
  861. Shape:
  862. - Input: :math:`(N, C, L_{in})` or :math:`(C, L_{in})`.
  863. - Output: :math:`(N, C, L_{out})` or :math:`(C, L_{out})`, where
  864. :math:`L_{out}=\text{output\_size}`.
  865. Examples:
  866. >>> # target output size of 5
  867. >>> m = nn.AdaptiveAvgPool1d(5)
  868. >>> input = torch.randn(1, 64, 8)
  869. >>> output = m(input)
  870. """
  871. output_size: _size_1_t
  872. def forward(self, input: Tensor) -> Tensor:
  873. return F.adaptive_avg_pool1d(input, self.output_size)
  874. class AdaptiveAvgPool2d(_AdaptiveAvgPoolNd):
  875. r"""Applies a 2D adaptive average pooling over an input signal composed of several input planes.
  876. The output is of size H x W, for any input size.
  877. The number of output features is equal to the number of input planes.
  878. Args:
  879. output_size: the target output size of the image of the form H x W.
  880. Can be a tuple (H, W) or a single H for a square image H x H.
  881. H and W can be either a ``int``, or ``None`` which means the size will
  882. be the same as that of the input.
  883. Shape:
  884. - Input: :math:`(N, C, H_{in}, W_{in})` or :math:`(C, H_{in}, W_{in})`.
  885. - Output: :math:`(N, C, S_{0}, S_{1})` or :math:`(C, S_{0}, S_{1})`, where
  886. :math:`S=\text{output\_size}`.
  887. Examples:
  888. >>> # target output size of 5x7
  889. >>> m = nn.AdaptiveAvgPool2d((5,7))
  890. >>> input = torch.randn(1, 64, 8, 9)
  891. >>> output = m(input)
  892. >>> # target output size of 7x7 (square)
  893. >>> m = nn.AdaptiveAvgPool2d(7)
  894. >>> input = torch.randn(1, 64, 10, 9)
  895. >>> output = m(input)
  896. >>> # target output size of 10x7
  897. >>> m = nn.AdaptiveAvgPool2d((None, 7))
  898. >>> input = torch.randn(1, 64, 10, 9)
  899. >>> output = m(input)
  900. """
  901. output_size: _size_2_opt_t
  902. def forward(self, input: Tensor) -> Tensor:
  903. return F.adaptive_avg_pool2d(input, self.output_size)
  904. class AdaptiveAvgPool3d(_AdaptiveAvgPoolNd):
  905. r"""Applies a 3D adaptive average pooling over an input signal composed of several input planes.
  906. The output is of size D x H x W, for any input size.
  907. The number of output features is equal to the number of input planes.
  908. Args:
  909. output_size: the target output size of the form D x H x W.
  910. Can be a tuple (D, H, W) or a single number D for a cube D x D x D.
  911. D, H and W can be either a ``int``, or ``None`` which means the size will
  912. be the same as that of the input.
  913. Shape:
  914. - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})` or :math:`(C, D_{in}, H_{in}, W_{in})`.
  915. - Output: :math:`(N, C, S_{0}, S_{1}, S_{2})` or :math:`(C, S_{0}, S_{1}, S_{2})`,
  916. where :math:`S=\text{output\_size}`.
  917. Examples:
  918. >>> # target output size of 5x7x9
  919. >>> m = nn.AdaptiveAvgPool3d((5,7,9))
  920. >>> input = torch.randn(1, 64, 8, 9, 10)
  921. >>> output = m(input)
  922. >>> # target output size of 7x7x7 (cube)
  923. >>> m = nn.AdaptiveAvgPool3d(7)
  924. >>> input = torch.randn(1, 64, 10, 9, 8)
  925. >>> output = m(input)
  926. >>> # target output size of 7x9x8
  927. >>> m = nn.AdaptiveAvgPool3d((7, None, None))
  928. >>> input = torch.randn(1, 64, 10, 9, 8)
  929. >>> output = m(input)
  930. """
  931. output_size: _size_3_opt_t
  932. def forward(self, input: Tensor) -> Tensor:
  933. return F.adaptive_avg_pool3d(input, self.output_size)