pooling.py 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import numpy as np
  15. from paddle import _C_ops, in_dynamic_mode
  16. from paddle.base.framework import (
  17. Variable,
  18. in_dygraph_mode,
  19. in_dynamic_or_pir_mode,
  20. )
  21. from ...base.data_feeder import check_type, check_variable_and_dtype
  22. from ...base.layer_helper import LayerHelper
  23. from ...tensor.manipulation import squeeze, unsqueeze
  24. # TODO: define pooling functions
  25. from ...utils import (
  26. _contain_var,
  27. _convert_to_tensor_list,
  28. _is_symmetric_padding,
  29. convert_to_list,
  30. )
  31. __all__ = []
  32. def _is_list_or_tuple(input):
  33. return isinstance(input, (list, tuple))
  34. def _check_input(x, dimension):
  35. if len(x.shape) != dimension:
  36. raise ValueError(
  37. f"Excepted Input X is {dimension}-D tensor, but received {len(x.shape)}-D {type(x)}"
  38. )
  39. def _check_instance(x, x_name, types=(int, float)):
  40. if not isinstance(x, types):
  41. raise ValueError(
  42. f"Excepted {types} type for {x_name} but received type: {type(x)}. "
  43. )
  44. def _check_value_limitation(x, x_name, min_limit=1e-3):
  45. def _check_value(x, x_name, min_limit=1e-3):
  46. if isinstance(x, int) and min_limit is not None and x < min_limit:
  47. raise ValueError(
  48. f"Excepted the input {x_name} to be greater than {min_limit} but received x: {x}. "
  49. )
  50. for ele in x:
  51. _check_value(ele, x_name)
  52. def _zero_padding_in_batch_and_channel(padding, channel_last):
  53. if channel_last:
  54. return list(padding[0]) == [0, 0] and list(padding[-1]) == [0, 0]
  55. else:
  56. return list(padding[0]) == [0, 0] and list(padding[1]) == [0, 0]
  57. def _exclude_padding_in_batch_and_channel(padding, channel_last):
  58. padding_ = padding[1:-1] if channel_last else padding[2:]
  59. padding_ = [elem for pad_a_dim in padding_ for elem in pad_a_dim]
  60. return padding_
  61. def _channel_last(data_format, num_dims):
  62. if num_dims == 1:
  63. if data_format not in ['NCL', 'NLC']:
  64. raise ValueError(
  65. "Attr(data_format) should be 'NCL' or 'NLC'. Received "
  66. "Attr(data_format): %s" % str(data_format)
  67. )
  68. else:
  69. return True if data_format == "NLC" else False
  70. if num_dims == 2:
  71. if data_format not in ['NCHW', 'NHWC']:
  72. raise ValueError(
  73. "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
  74. "Attr(data_format): %s" % str(data_format)
  75. )
  76. else:
  77. return True if data_format == "NHWC" else False
  78. if num_dims == 3:
  79. if data_format not in ['NCDHW', 'NDHWC']:
  80. raise ValueError(
  81. "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received "
  82. "Attr(data_format): %s" % str(data_format)
  83. )
  84. else:
  85. return True if data_format == "NDHWC" else False
  86. def _update_padding_nd(padding, num_dims, channel_last=False, ceil_mode=False):
  87. if isinstance(padding, str):
  88. padding = padding.upper()
  89. if padding not in ["SAME", "VALID"]:
  90. raise ValueError(
  91. f"Unknown padding: '{padding}'. It can only be 'SAME' or 'VALID'."
  92. )
  93. if padding == "VALID":
  94. if ceil_mode is not False:
  95. raise ValueError(
  96. "When Attr(padding) is \"VALID\", Attr(ceil_mode) must be False. "
  97. "Received ceil_mode: True."
  98. )
  99. padding_algorithm = "VALID"
  100. padding = [0] * num_dims
  101. else:
  102. padding_algorithm = "SAME"
  103. padding = [0] * num_dims
  104. elif _is_list_or_tuple(padding):
  105. # for padding like
  106. # [(pad_before, pad_after), (pad_before, pad_after), ...]
  107. # padding for batch_dim and channel_dim included
  108. if len(padding) == 2 + num_dims and _is_list_or_tuple(padding[0]):
  109. if not _zero_padding_in_batch_and_channel(padding, channel_last):
  110. raise ValueError(
  111. f"Non-zero padding({padding}) in the batch or channel dimensions "
  112. "is not supported."
  113. )
  114. padding_algorithm = "EXPLICIT"
  115. padding = _exclude_padding_in_batch_and_channel(
  116. padding, channel_last
  117. )
  118. if _is_symmetric_padding(padding, num_dims):
  119. padding = padding[0::2]
  120. # for padding like [pad_before, pad_after, pad_before, pad_after, ...]
  121. elif len(padding) == 2 * num_dims and isinstance(padding[0], int):
  122. padding_algorithm = "EXPLICIT"
  123. padding = convert_to_list(padding, 2 * num_dims, 'padding')
  124. if _is_symmetric_padding(padding, num_dims):
  125. padding = padding[0::2]
  126. # for padding like [pad_d1, pad_d2, ...]
  127. elif len(padding) == num_dims and isinstance(padding[0], int):
  128. padding_algorithm = "EXPLICIT"
  129. padding = convert_to_list(padding, num_dims, 'padding')
  130. else:
  131. raise ValueError(f"Invalid padding: {padding}")
  132. # for integer padding
  133. else:
  134. padding_algorithm = "EXPLICIT"
  135. padding = convert_to_list(padding, num_dims, 'padding')
  136. return padding, padding_algorithm
  137. def _expand_low_nd_padding(padding):
  138. # 1d to 2d fake input
  139. if len(padding) == 2:
  140. padding = [0] * 2 + padding
  141. elif len(padding) == 1:
  142. padding = [0] + padding
  143. else:
  144. raise ValueError(
  145. f"The size of padding's dimension should be 1 or 2. But got padding={padding}"
  146. )
  147. return padding
  148. def avg_pool1d(
  149. x,
  150. kernel_size,
  151. stride=None,
  152. padding=0,
  153. exclusive=True,
  154. ceil_mode=False,
  155. name=None,
  156. ):
  157. """
  158. This API implements average pooling 1d operation,
  159. See more details in :ref:`api_paddle_nn_AvgPool1d` .
  160. Args:
  161. x (Tensor): The input tensor of pooling operator which is a 3-D tensor with
  162. shape [N, C, L]. where `N` is batch size, `C` is the number of channels,
  163. `L` is the length of the feature. The data type is float16, float32 or float64.
  164. kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
  165. it must contain an integer.
  166. stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
  167. it must contain an integer.
  168. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
  169. 1. A string in ['valid', 'same'].
  170. 2. An int, which means the feature map is zero padded by size of `padding` on every sides.
  171. 3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides.
  172. 4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after].
  173. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
  174. The default value is 0.
  175. exclusive (bool): Whether to exclude padding points in average pooling
  176. mode, default is `True`.
  177. ceil_mode (bool): ${ceil_mode_comment}Whether to use the ceil function to calculate output height and width.
  178. If it is set to False, the floor function will be used. The default value is False.
  179. name(str, optional): For detailed information, please refer
  180. to :ref:`api_guide_Name`. Usually name is no need to set and
  181. None by default.
  182. Returns:
  183. Tensor: The output tensor of pooling result. The data type is same as input tensor.
  184. Examples:
  185. .. code-block:: python
  186. >>> import paddle
  187. >>> import paddle.nn as nn
  188. >>> data = paddle.uniform([1, 3, 32], paddle.float32)
  189. >>> AvgPool1D = nn.AvgPool1D(kernel_size=2, stride=2, padding=0)
  190. >>> pool_out = AvgPool1D(data)
  191. >>> print(pool_out.shape)
  192. [1, 3, 16]
  193. """
  194. """NCL to NCHW"""
  195. data_format = "NCHW"
  196. if not in_dynamic_mode():
  197. check_variable_and_dtype(
  198. x, 'x', ['float16', 'float32', 'float64'], 'avg_pool1d'
  199. )
  200. _check_input(x, 3)
  201. x = unsqueeze(x, [2])
  202. kernel_size = convert_to_list(kernel_size, 1, 'kernel_size')
  203. kernel_size = [1] + kernel_size
  204. if stride is None:
  205. stride = kernel_size
  206. else:
  207. stride = convert_to_list(stride, 1, 'pool_stride')
  208. stride = [1] + stride
  209. _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
  210. _check_value_limitation(stride, "stride", min_limit=1e-3)
  211. channel_last = _channel_last("NCL", 1)
  212. padding, padding_algorithm = _update_padding_nd(
  213. padding, 1, channel_last=channel_last, ceil_mode=ceil_mode
  214. )
  215. # use 2d to implement 1d should expand padding in advance.
  216. padding = _expand_low_nd_padding(padding)
  217. if in_dynamic_or_pir_mode():
  218. output = _C_ops.pool2d(
  219. x,
  220. kernel_size,
  221. stride,
  222. padding,
  223. ceil_mode,
  224. exclusive,
  225. data_format,
  226. 'avg',
  227. False,
  228. False,
  229. padding_algorithm,
  230. )
  231. return squeeze(output, [2])
  232. else:
  233. op_type = 'pool2d'
  234. helper = LayerHelper(op_type, **locals())
  235. dtype = helper.input_dtype(input_param_name='x')
  236. pool_out = helper.create_variable_for_type_inference(dtype)
  237. helper.append_op(
  238. type=op_type,
  239. inputs={"X": x},
  240. outputs={"Out": pool_out},
  241. attrs={
  242. "pooling_type": 'avg',
  243. "ksize": kernel_size,
  244. "global_pooling": False,
  245. "strides": stride,
  246. "paddings": padding,
  247. "padding_algorithm": padding_algorithm,
  248. "use_cudnn": True,
  249. "ceil_mode": ceil_mode,
  250. "exclusive": exclusive,
  251. "data_format": data_format,
  252. },
  253. )
  254. return squeeze(pool_out, [2])
  255. def avg_pool2d(
  256. x,
  257. kernel_size,
  258. stride=None,
  259. padding=0,
  260. ceil_mode=False,
  261. exclusive=True,
  262. divisor_override=None,
  263. data_format="NCHW",
  264. name=None,
  265. ):
  266. """
  267. This API implements average pooling 2d operation.
  268. See more details in :ref:`api_paddle_nn_AvgPool2d` .
  269. Args:
  270. x (Tensor): The input tensor of pooling operator which is a 4-D tensor with
  271. shape [N, C, H, W]. The format of input tensor is `"NCHW"` or
  272. `"NHWC"`, where `N` is batch size, `C` is the number of channels,
  273. `H` is the height of the feature, and `W` is the width of the
  274. feature. The data type if float32 or float64.
  275. kernel_size (int|list|tuple): The pool kernel size. If it is a tuple or list,
  276. it must contain two integers, (kernel_size_Height, kernel_size_Width).
  277. Otherwise, the pool kernel size will be a square of an int.
  278. stride (int|list|tuple): The stride size. If it is a tuple or list,
  279. it must contain two integers, (stride_Height, stride_Width).
  280. Otherwise, the stride size will be a square of an int.
  281. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
  282. 1. A string in ['valid', 'same'].
  283. 2. An int, which means the feature map is zero padded by size of `padding` on every sides.
  284. 3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension.
  285. 4. A list[int] or tuple(int) whose length is 4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
  286. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
  287. The default value is 0.
  288. ceil_mode (bool): when True, will use `ceil` instead of `floor` to compute the output shape
  289. exclusive (bool): Whether to exclude padding points in average pooling
  290. mode, default is `true`.
  291. divisor_override (float): if specified, it will be used as divisor, otherwise kernel_size will be used. Default None.
  292. data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`.
  293. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
  294. `[batch_size, input_channels, input_height, input_width]`.
  295. name(str, optional): For detailed information, please refer
  296. to :ref:`api_guide_Name`. Usually name is no need to set and
  297. None by default.
  298. Returns:
  299. Tensor: The output tensor of pooling result. The data type is same as input tensor.
  300. Examples:
  301. .. code-block:: python
  302. >>> import paddle
  303. >>> import paddle.nn.functional as F
  304. >>> # avg pool2d
  305. >>> x = paddle.uniform([1, 3, 32, 32], paddle.float32)
  306. >>> out = F.avg_pool2d(x,
  307. ... kernel_size=2,
  308. ... stride=2, padding=0)
  309. >>> print(out.shape)
  310. [1, 3, 16, 16]
  311. """
  312. kernel_size = convert_to_list(kernel_size, 2, 'pool_size')
  313. if stride is None:
  314. stride = kernel_size
  315. else:
  316. stride = convert_to_list(stride, 2, 'pool_stride')
  317. _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
  318. _check_value_limitation(stride, "stride", min_limit=1e-3)
  319. channel_last = _channel_last(data_format, 2)
  320. padding, padding_algorithm = _update_padding_nd(
  321. padding, 2, channel_last, ceil_mode=ceil_mode
  322. )
  323. if in_dynamic_or_pir_mode():
  324. output = _C_ops.pool2d(
  325. x,
  326. kernel_size,
  327. stride,
  328. padding,
  329. ceil_mode,
  330. exclusive,
  331. data_format,
  332. 'avg',
  333. False,
  334. False,
  335. padding_algorithm,
  336. )
  337. if divisor_override is None:
  338. return output
  339. else:
  340. _check_instance(divisor_override, "divisor_override")
  341. return output * (kernel_size[0] * kernel_size[1]) / divisor_override
  342. else:
  343. op_type = 'pool2d'
  344. helper = LayerHelper(op_type, **locals())
  345. check_variable_and_dtype(
  346. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'avg_pool2d'
  347. )
  348. dtype = helper.input_dtype(input_param_name='x')
  349. pool_out = helper.create_variable_for_type_inference(dtype)
  350. helper.append_op(
  351. type=op_type,
  352. inputs={"X": x},
  353. outputs={"Out": pool_out},
  354. attrs={
  355. "pooling_type": "avg",
  356. "ksize": kernel_size,
  357. "global_pooling": False,
  358. "strides": stride,
  359. "paddings": padding,
  360. "padding_algorithm": padding_algorithm,
  361. "use_cudnn": True,
  362. "ceil_mode": ceil_mode,
  363. "exclusive": exclusive,
  364. "data_format": data_format,
  365. },
  366. )
  367. if divisor_override is None:
  368. return pool_out
  369. else:
  370. _check_instance(divisor_override, "divisor_override")
  371. return (
  372. pool_out * (kernel_size[0] * kernel_size[1]) / divisor_override
  373. )
  374. def avg_pool3d(
  375. x,
  376. kernel_size,
  377. stride=None,
  378. padding=0,
  379. ceil_mode=False,
  380. exclusive=True,
  381. divisor_override=None,
  382. data_format="NCDHW",
  383. name=None,
  384. ):
  385. """
  386. This API implements average pooling 3d operation.
  387. See more details in :ref:`api_paddle_nn_AvgPool3d` .
  388. Args:
  389. x (Tensor): The input tensor of pooling operator, which is a 5-D tensor with
  390. shape [N, C, D, H, W], where `N` represents the batch size, `C` represents
  391. the number of channels, `D`, `H` and `W` represent the depth, height and width of the feature respectively.
  392. kernel_size (int|list|tuple): The pool kernel size. If pool kernel size
  393. is a tuple or list, it must contain three integers,
  394. (kernel_size_Depth, kernel_size_Height, kernel_size_Width).
  395. Otherwise, the pool kernel size will be the cube of an int.
  396. stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
  397. it must contain three integers, [stride_Depth, stride_Height, stride_Width).
  398. Otherwise, the pool stride size will be a cube of an int.
  399. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
  400. 1. A string in ['valid', 'same'].
  401. 2. An int, which means the feature map is zero padded by size of `padding` on every sides.
  402. 3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension.
  403. 4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
  404. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
  405. The default value is 0.
  406. ceil_mode (bool): ${ceil_mode_comment}
  407. exclusive (bool): Whether to exclude padding points in average pooling
  408. mode, default is True.
  409. divisor_override (int|float) if specified, it will be used as divisor, otherwise kernel_size will be used. Default None.
  410. data_format (string): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`.
  411. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of:
  412. `[batch_size, input_channels, input_depth, input_height, input_width]`.
  413. name(str, optional): For detailed information, please refer
  414. to :ref:`api_guide_Name`. Usually name is no need to set and
  415. None by default.
  416. Returns:
  417. Tensor: The output tensor of pooling result. The data type is same as input tensor.
  418. Examples:
  419. .. code-block:: python
  420. >>> import paddle
  421. >>> x = paddle.uniform([1, 3, 32, 32, 32], paddle.float32)
  422. >>> # avg pool3d
  423. >>> out = paddle.nn.functional.avg_pool3d(x,
  424. ... kernel_size = 2,
  425. ... stride = 2,
  426. ... padding=0)
  427. >>> print(out.shape)
  428. [1, 3, 16, 16, 16]
  429. """
  430. kernel_size = convert_to_list(kernel_size, 3, 'pool_size')
  431. if stride is None:
  432. stride = kernel_size
  433. else:
  434. stride = convert_to_list(stride, 3, 'pool_stride')
  435. channel_last = _channel_last(data_format, 3)
  436. padding, padding_algorithm = _update_padding_nd(
  437. padding, 3, channel_last=channel_last, ceil_mode=ceil_mode
  438. )
  439. _check_value_limitation(kernel_size, "kernel_size", min_limit=1e-3)
  440. _check_value_limitation(stride, "stride", min_limit=1e-3)
  441. if in_dynamic_or_pir_mode():
  442. pool_out = _C_ops.pool3d(
  443. x,
  444. kernel_size,
  445. stride,
  446. padding,
  447. ceil_mode,
  448. exclusive,
  449. data_format,
  450. 'avg',
  451. False,
  452. False,
  453. padding_algorithm,
  454. )
  455. else:
  456. op_type = "pool3d"
  457. helper = LayerHelper(op_type, **locals())
  458. check_variable_and_dtype(
  459. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'avg_pool3d'
  460. )
  461. dtype = helper.input_dtype(input_param_name='x')
  462. pool_out = helper.create_variable_for_type_inference(dtype)
  463. outputs = {"Out": pool_out}
  464. helper.append_op(
  465. type=op_type,
  466. inputs={"X": x},
  467. outputs=outputs,
  468. attrs={
  469. "pooling_type": 'avg',
  470. "ksize": kernel_size,
  471. "global_pooling": False,
  472. "strides": stride,
  473. "paddings": padding,
  474. "padding_algorithm": padding_algorithm,
  475. "use_cudnn": True,
  476. "ceil_mode": ceil_mode,
  477. "exclusive": exclusive,
  478. "data_format": data_format,
  479. },
  480. )
  481. if divisor_override is None:
  482. return pool_out
  483. else:
  484. _check_instance(divisor_override, "divisor_override")
  485. return (
  486. pool_out
  487. * (kernel_size[0] * kernel_size[1] * kernel_size[2])
  488. / divisor_override
  489. )
  490. def max_pool1d(
  491. x,
  492. kernel_size,
  493. stride=None,
  494. padding=0,
  495. return_mask=False,
  496. ceil_mode=False,
  497. name=None,
  498. ):
  499. """
  500. This API implements max pooling 1d operation.
  501. See more details in :ref:`api_paddle_nn_MaxPool1d` .
  502. Args:
  503. x (Tensor): The input tensor of pooling operator which is a 3-D tensor with
  504. shape [N, C, L], where `N` is batch size, `C` is the number of channels,
  505. `L` is the length of the feature. The data type if float32 or float64.
  506. kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
  507. it must contain an integer.
  508. stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
  509. it must contain an integer.
  510. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
  511. 1. A string in ['valid', 'same'].
  512. 2. An integer, which means the feature map is zero padded by size of `padding` on every sides.
  513. 3. A list[int] or tuple(int) whose length is 1, which means the feature map is zero padded by the size of `padding[0]` on every sides.
  514. 4. A list[int] or tuple(int) whose length is 2. It has the form [pad_before, pad_after].
  515. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
  516. The default value is 0.
  517. return_mask (bool): Whether return the max indices along with the outputs. default is `False`.
  518. ceil_mode (bool): Whether to use the ceil function to calculate output height and width. False is the default.
  519. If it is set to False, the floor function will be used. Default False.
  520. name(str, optional): For detailed information, please refer
  521. to :ref:`api_guide_Name`. Usually name is no need to set and
  522. None by default.
  523. Returns:
  524. Tensor: The output tensor of pooling result. The data type is same as input tensor.
  525. Examples:
  526. .. code-block:: python
  527. >>> import paddle
  528. >>> import paddle.nn.functional as F
  529. >>> data = paddle.uniform([1, 3, 32], paddle.float32)
  530. >>> pool_out = F.max_pool1d(data, kernel_size=2, stride=2, padding=0)
  531. >>> print(pool_out.shape)
  532. [1, 3, 16]
  533. >>> pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
  534. >>> print(pool_out.shape)
  535. [1, 3, 16]
  536. >>> print(indices.shape)
  537. [1, 3, 16]
  538. """
  539. """NCL to NCHW"""
  540. data_format = "NCHW"
  541. _check_input(x, 3)
  542. x = unsqueeze(x, [2])
  543. kernel_size = [1] + convert_to_list(kernel_size, 1, 'pool_size')
  544. if stride is None:
  545. stride = kernel_size
  546. else:
  547. stride = [1] + convert_to_list(stride, 1, 'pool_stride')
  548. padding, padding_algorithm = _update_padding_nd(
  549. padding, 1, ceil_mode=ceil_mode
  550. )
  551. # use 2d to implenment 1d should expand padding in advance.
  552. padding = _expand_low_nd_padding(padding)
  553. if in_dynamic_or_pir_mode():
  554. if return_mask:
  555. pool_out = _C_ops.max_pool2d_with_index(
  556. x, kernel_size, stride, padding, False, False
  557. )
  558. return (
  559. (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2]))
  560. if return_mask
  561. else squeeze(pool_out[0], [2])
  562. )
  563. else:
  564. pool_out = _C_ops.pool2d(
  565. x,
  566. kernel_size,
  567. stride,
  568. padding,
  569. ceil_mode,
  570. True,
  571. data_format,
  572. 'max',
  573. False,
  574. False,
  575. padding_algorithm,
  576. )
  577. return squeeze(pool_out, [2])
  578. else:
  579. check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'max_pool1d')
  580. op_type = 'max_pool2d_with_index' if return_mask else "pool2d"
  581. helper = LayerHelper(op_type, **locals())
  582. dtype = helper.input_dtype(input_param_name='x')
  583. pool_out = helper.create_variable_for_type_inference(dtype)
  584. mask = helper.create_variable_for_type_inference('int32')
  585. outputs = {"Out": pool_out, "Mask": mask}
  586. helper.append_op(
  587. type=op_type,
  588. inputs={"X": x},
  589. outputs=outputs,
  590. attrs={
  591. "pooling_type": 'max',
  592. "ksize": kernel_size,
  593. "global_pooling": False,
  594. "strides": stride,
  595. "paddings": padding,
  596. "padding_algorithm": padding_algorithm,
  597. "use_cudnn": True,
  598. "ceil_mode": ceil_mode,
  599. "exclusive": True,
  600. "data_format": data_format,
  601. },
  602. )
  603. return (
  604. (squeeze(pool_out, [2]), squeeze(mask, [2]))
  605. if return_mask
  606. else squeeze(pool_out, [2])
  607. )
  608. def _unpool_output_size(x, kernel_size, stride, padding, output_size):
  609. assert output_size is None or isinstance(output_size, (list, tuple)), (
  610. "Required output_size is None|list|tuple, but received %s" % output_size
  611. )
  612. input_size = x.shape
  613. default_size = []
  614. for d in range(len(kernel_size)):
  615. default_size.append(
  616. (input_size[-len(kernel_size) + d] - 1) * stride[d]
  617. + kernel_size[d]
  618. - 2 * padding[d]
  619. )
  620. has_static_var = False
  621. if output_size is None:
  622. return default_size
  623. elif _contain_var(output_size):
  624. if not in_dygraph_mode():
  625. has_static_var = True
  626. output_size = _convert_to_tensor_list(output_size)
  627. else:
  628. for i, var in enumerate(output_size):
  629. if isinstance(var, Variable):
  630. output_size[i] = np.array(var).item()
  631. if len(output_size) == len(kernel_size) + 2:
  632. output_size = output_size[2:]
  633. if len(output_size) != len(kernel_size):
  634. raise ValueError(
  635. "output_size should be a sequence containing "
  636. f"{len(kernel_size)} or {len(kernel_size) + 2} elements, but it has a length of '{len(output_size)}'"
  637. )
  638. if not has_static_var:
  639. for d in range(len(kernel_size)):
  640. min_size = default_size[d] - stride[d]
  641. max_size = default_size[d] + stride[d]
  642. if not (min_size < output_size[d] < max_size):
  643. raise ValueError(
  644. f'invalid output_size "{output_size}" (dim {d} must be between {min_size} and {max_size})'
  645. )
  646. return output_size
  647. def max_unpool1d(
  648. x,
  649. indices,
  650. kernel_size,
  651. stride=None,
  652. padding=0,
  653. data_format="NCL",
  654. output_size=None,
  655. name=None,
  656. ):
  657. r"""
  658. This API implements max unpooling 1d operation.
  659. `max_unpool1d` accepts the output of `max_pool1d` as input,
  660. including the indices of the maximum value and calculate the partial inverse.
  661. All non-maximum values are set to zero.
  662. - Input: :math:`(N, C, L_{in})`
  663. - Output: :math:`(N, C, L_{out})`, where
  664. .. math::
  665. L_{out} = (L_{in} - 1) * stride - 2 * padding + kernel\_size
  666. or as given by :attr:`output_size` in the call operator.
  667. Args:
  668. x (Tensor): The input tensor of unpooling operator which is a 3-D tensor with
  669. shape [N, C, L]. The format of input tensor is `"NCL"`,
  670. where `N` is batch size, `C` is the number of channels, `L` is
  671. the length of the feature. The data type is float32, float64 or int64.
  672. indices (Tensor): The indices given out by maxpooling1d which is a 3-D tensor with
  673. shape [N, C, L]. The format of input tensor is `"NCL"` ,
  674. where `N` is batch size, `C` is the number of channels, `L` is
  675. the length of the feature. The data type is float32 or float64.
  676. kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list,
  677. it must contain an integer.
  678. stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list,
  679. it must contain an integer.
  680. padding (int | tuple): Padding that was added to the input.
  681. output_size(list|tuple, optional): The target output size. If output_size is not specified,
  682. the actual output shape will be automatically calculated by (input_shape,
  683. kernel_size, stride, padding).
  684. data_format (string): The data format of the input and output data.
  685. The default is `"NCL"`. When it is `"NCL"`, the data is stored in the order of:
  686. `[batch_size, input_channels, input_length]`.
  687. name(str, optional): For detailed information, please refer
  688. to :ref:`api_guide_Name`. Usually name is no need to set and
  689. None by default.
  690. Returns:
  691. Tensor: The output tensor of unpooling result.
  692. Examples:
  693. .. code-block:: python
  694. >>> import paddle
  695. >>> import paddle.nn.functional as F
  696. >>> data = paddle.rand(shape=[1, 3, 16])
  697. >>> pool_out, indices = F.max_pool1d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
  698. >>> print(pool_out.shape)
  699. [1, 3, 8]
  700. >>> print(indices.shape)
  701. [1, 3, 8]
  702. >>> unpool_out = F.max_unpool1d(pool_out, indices, kernel_size=2, padding=0)
  703. >>> print(unpool_out.shape)
  704. [1, 3, 16]
  705. """
  706. """NCL to NCHW"""
  707. if data_format not in ["NCL"]:
  708. raise ValueError(
  709. "Attr(data_format) should be 'NCL'. Received "
  710. "Attr(data_format): %s." % str(data_format)
  711. )
  712. data_format = "NCHW"
  713. x = unsqueeze(x, [2])
  714. indices = unsqueeze(indices, [2])
  715. kernel_size = [1] + convert_to_list(kernel_size, 1, 'pool_size')
  716. if stride is None:
  717. stride = kernel_size
  718. else:
  719. stride = [1] + convert_to_list(stride, 1, 'pool_stride')
  720. padding, padding_algorithm = _update_padding_nd(padding, 1)
  721. # use 2d to implenment 1d should expand padding in advance.
  722. padding = _expand_low_nd_padding(padding)
  723. if output_size is not None:
  724. output_size = output_size[:2] + [1] + output_size[2:]
  725. output_size = _unpool_output_size(
  726. x, kernel_size, stride, padding, output_size
  727. )
  728. if in_dynamic_or_pir_mode():
  729. output = _C_ops.unpool(
  730. x, indices, kernel_size, stride, padding, output_size, data_format
  731. )
  732. return squeeze(output, [2])
  733. op_type = "unpool"
  734. helper = LayerHelper(op_type, **locals())
  735. dtype = helper.input_dtype(input_param_name="x")
  736. unpool_out = helper.create_variable_for_type_inference(dtype)
  737. helper.append_op(
  738. type=op_type,
  739. inputs={"X": x, "Indices": indices},
  740. outputs={"Out": unpool_out},
  741. attrs={
  742. "unpooling_type": "max",
  743. "ksize": kernel_size,
  744. "strides": stride,
  745. "paddings": padding,
  746. "output_size": output_size,
  747. },
  748. )
  749. return squeeze(unpool_out, [2])
  750. def max_unpool2d(
  751. x,
  752. indices,
  753. kernel_size,
  754. stride=None,
  755. padding=0,
  756. data_format="NCHW",
  757. output_size=None,
  758. name=None,
  759. ):
  760. r"""
  761. This API implements max unpooling 2d operation.
  762. See more details in :ref:`api_paddle_nn_MaxUnPool2D` .
  763. Args:
  764. x (Tensor): The input tensor of unpooling operator which is a 4-D tensor with
  765. shape [N, C, H, W]. The format of input tensor is `"NCHW"`,
  766. where `N` is batch size, `C` is the number of channels,
  767. `H` is the height of the feature, and `W` is the width of the
  768. feature. The data type is float32, float64 or int64.
  769. indices (Tensor): The indices given out by maxpooling2d which is a 4-D tensor with
  770. shape [N, C, H, W]. The format of input tensor is `"NCHW"` ,
  771. where `N` is batch size, `C` is the number of channels,
  772. `H` is the height of the feature, and `W` is the width of the
  773. feature. The data type is float32 or float64.
  774. kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list,
  775. it must contain an integer.
  776. stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list,
  777. it must contain an integer.
  778. padding (int | tuple): Padding that was added to the input.
  779. output_size(list|tuple, optional): The target output size. If output_size is not specified,
  780. the actual output shape will be automatically calculated by (input_shape,
  781. kernel_size, padding).
  782. name(str, optional): For detailed information, please refer
  783. to :ref:`api_guide_Name`. Usually name is no need to set and
  784. None by default.
  785. - Input: :math:`(N, C, H_{in}, W_{in})`
  786. - Output: :math:`(N, C, H_{out}, W_{out})`, where
  787. .. math::
  788. H_{out} = (H_{in} - 1) \times \text{stride[0]} - 2 \times \text{padding[0]} + \text{kernel\_size[0]}
  789. .. math::
  790. W_{out} = (W_{in} - 1) \times \text{stride[1]} - 2 \times \text{padding[1]} + \text{kernel\_size[1]}
  791. or as given by :attr:`output_size` in the call operator
  792. Returns:
  793. Tensor: The output tensor of unpooling result.
  794. Raises:
  795. ValueError: If the input is not a 4-D tensor.
  796. ValueError: If indices shape is not equal input shape.
  797. Examples:
  798. .. code-block:: python
  799. >>> import paddle
  800. >>> import paddle.nn.functional as F
  801. >>> data = paddle.rand(shape=[1, 1, 6, 6])
  802. >>> pool_out, indices = F.max_pool2d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
  803. >>> print(pool_out.shape)
  804. [1, 1, 3, 3]
  805. >>> print(indices.shape)
  806. [1, 1, 3, 3]
  807. >>> unpool_out = F.max_unpool2d(pool_out, indices, kernel_size=2, padding=0)
  808. >>> print(unpool_out.shape)
  809. [1, 1, 6, 6]
  810. >>> # specify a different output size than input size
  811. >>> unpool_out = F.max_unpool2d(pool_out, indices, kernel_size=2, padding=0, output_size=[7, 7])
  812. >>> print(unpool_out.shape)
  813. [1, 1, 7, 7]
  814. """
  815. if x.ndim != 4:
  816. raise ValueError(
  817. f'The x should have [N, C, H, W] format, but received {x.shape}.'
  818. )
  819. if indices.ndim != 4:
  820. raise ValueError(
  821. f'The indices should have [N, C, H, W] format, but received {indices.shape}.'
  822. )
  823. kernel_size = convert_to_list(kernel_size, 2, 'pool_size')
  824. if stride is None:
  825. stride = kernel_size
  826. else:
  827. stride = convert_to_list(stride, 2, 'pool_stride')
  828. padding = convert_to_list(padding, 2, 'padding')
  829. if data_format not in ["NCHW"]:
  830. raise ValueError(
  831. "Attr(data_format) should be 'NCHW'. Received "
  832. "Attr(data_format): %s." % str(data_format)
  833. )
  834. output_size = _unpool_output_size(
  835. x, kernel_size, stride, padding, output_size
  836. )
  837. if in_dynamic_or_pir_mode():
  838. output = _C_ops.unpool(
  839. x, indices, kernel_size, stride, padding, output_size, data_format
  840. )
  841. return output
  842. op_type = "unpool"
  843. helper = LayerHelper(op_type, **locals())
  844. dtype = helper.input_dtype(input_param_name="x")
  845. unpool_out = helper.create_variable_for_type_inference(dtype)
  846. helper.append_op(
  847. type=op_type,
  848. inputs={"X": x, "Indices": indices},
  849. outputs={"Out": unpool_out},
  850. attrs={
  851. "unpooling_type": "max",
  852. "ksize": kernel_size,
  853. "strides": stride,
  854. "paddings": padding,
  855. "output_size": output_size,
  856. },
  857. )
  858. return unpool_out
  859. def max_unpool3d(
  860. x,
  861. indices,
  862. kernel_size,
  863. stride=None,
  864. padding=0,
  865. data_format="NCDHW",
  866. output_size=None,
  867. name=None,
  868. ):
  869. r"""
  870. This API implements max unpooling 3d operation.
  871. `max_unpool3d` accepts the output of `max_pool3d` as input,
  872. including the indices of the maximum value and calculate the partial inverse.
  873. All non-maximum values are set to zero.
  874. - Input: :math:`(N, C, D_{in}, H_{in}, W_{in})`
  875. - Output: :math:`(N, C, D_{out}, H_{out}, W_{out})`, where
  876. .. math::
  877. D_{out} = (D_{in} - 1) * stride[0] - 2 * padding[0] + kernel\_size[0]
  878. .. math::
  879. H_{out} = (H_{in} - 1) * stride[1] - 2 * padding[1] + kernel\_size[1]
  880. .. math::
  881. W_{out} = (W_{in} - 1) * stride[2] - 2 * padding[2] + kernel\_size[2]
  882. or as given by :attr:`output_size` in the call operator
  883. Args:
  884. x (Tensor): The input tensor of unpooling operator which is a 5-D tensor with
  885. shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"`,
  886. where `N` is batch size, `C` is the number of channels, `D` is
  887. the depth of the feature, `H` is the height of the feature,
  888. and `W` is the width of the feature. The data type is float32, float64 or int64.
  889. indices (Tensor): The indices given out by maxpooling3d which is a 5-D tensor with
  890. shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` ,
  891. where `N` is batch size, `C` is the number of channels, `D` is
  892. the depth of the feature, `H` is the height of the feature,
  893. and `W` is the width of the feature. The data type is float32 or float64.
  894. kernel_size (int|list|tuple): The unpool kernel size. If unpool kernel size is a tuple or list,
  895. it must contain an integer.
  896. stride (int|list|tuple): The unpool stride size. If unpool stride size is a tuple or list,
  897. it must contain an integer.
  898. padding (int | tuple): Padding that was added to the input.
  899. output_size(list|tuple, optional): The target output size. If output_size is not specified,
  900. the actual output shape will be automatically calculated by (input_shape,
  901. kernel_size, stride, padding).
  902. data_format (string): The data format of the input and output data.
  903. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of:
  904. `[batch_size, input_channels, input_depth, input_height, input_width]`.
  905. name(str, optional): For detailed information, please refer
  906. to :ref:`api_guide_Name`. Usually name is no need to set and
  907. None by default.
  908. Returns:
  909. Tensor: The output tensor of unpooling result.
  910. Examples:
  911. .. code-block:: python
  912. >>> import paddle
  913. >>> import paddle.nn.functional as F
  914. >>> data = paddle.rand(shape=[1, 1, 4, 4, 6])
  915. >>> pool_out, indices = F.max_pool3d(data, kernel_size=2, stride=2, padding=0, return_mask=True)
  916. >>> print(pool_out.shape)
  917. [1, 1, 2, 2, 3]
  918. >>> print(indices.shape)
  919. [1, 1, 2, 2, 3]
  920. >>> unpool_out = F.max_unpool3d(pool_out, indices, kernel_size=2, padding=0)
  921. >>> print(unpool_out.shape)
  922. [1, 1, 4, 4, 6]
  923. """
  924. if x.ndim != 5:
  925. raise ValueError(
  926. f'The x should have [N, C, D, H, W] format, but received {x.shape}.'
  927. )
  928. if indices.ndim != 5:
  929. raise ValueError(
  930. f'The indices should have [N, C, D, H, W] format, but received {indices.shape}.'
  931. )
  932. kernel_size = convert_to_list(kernel_size, 3, 'pool_size')
  933. if stride is None:
  934. stride = kernel_size
  935. else:
  936. stride = convert_to_list(stride, 3, 'pool_stride')
  937. padding = convert_to_list(padding, 3, 'padding')
  938. if data_format not in ["NCDHW"]:
  939. raise ValueError(
  940. "Attr(data_format) should be 'NCDHW'. Received "
  941. "Attr(data_format): %s." % str(data_format)
  942. )
  943. output_size = _unpool_output_size(
  944. x, kernel_size, stride, padding, output_size
  945. )
  946. if in_dynamic_or_pir_mode():
  947. output = _C_ops.unpool3d(
  948. x, indices, kernel_size, stride, padding, output_size, data_format
  949. )
  950. return output
  951. op_type = "unpool3d"
  952. helper = LayerHelper(op_type, **locals())
  953. dtype = helper.input_dtype(input_param_name="x")
  954. unpool_out = helper.create_variable_for_type_inference(dtype)
  955. helper.append_op(
  956. type=op_type,
  957. inputs={"X": x, "Indices": indices},
  958. outputs={"Out": unpool_out},
  959. attrs={
  960. "unpooling_type": "max",
  961. "ksize": kernel_size,
  962. "strides": stride,
  963. "paddings": padding,
  964. "output_size": output_size,
  965. },
  966. )
  967. return unpool_out
  968. def max_pool2d(
  969. x,
  970. kernel_size,
  971. stride=None,
  972. padding=0,
  973. return_mask=False,
  974. ceil_mode=False,
  975. data_format="NCHW",
  976. name=None,
  977. ):
  978. """
  979. This API implements max pooling 2d operation.
  980. See more details in :ref:`api_paddle_nn_MaxPool2d` .
  981. Args:
  982. x (Tensor): The input tensor of pooling operator which is a 4-D tensor with
  983. shape [N, C, H, W]. The format of input tensor is `"NCHW"` or
  984. `"NHWC"`, where `N` is batch size, `C` is the number of channels,
  985. `H` is the height of the feature, and `W` is the width of the
  986. feature. The data type if float32 or float64.
  987. kernel_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
  988. it must contain two integers, (kernel_size_Height, kernel_size_Width).
  989. Otherwise, the pool kernel size will be a square of an int.
  990. stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
  991. it must contain two integers, (stride_Height, stride_Width).
  992. Otherwise, the pool stride size will be a square of an int.
  993. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
  994. 1. A string in ['valid', 'same'].
  995. 2. An int, which means the feature map is zero padded by size of `padding` on every sides.
  996. 3. A list[int] or tuple(int) whose length is 2, [pad_height, pad_weight] whose value means the padding size of each dimension.
  997. 4. A list[int] or tuple(int) whose length is 4. [pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
  998. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
  999. The default value is 0.
  1000. ceil_mode (bool): when True, will use `ceil` instead of `floor` to compute the output shape
  1001. return_mask (bool): Whether to return the max indices along with the outputs. Default False, only support `"NCHW"` data format
  1002. data_format (string): The data format of the input and output data. An optional string from: `"NCHW"`, `"NHWC"`.
  1003. The default is `"NCHW"`. When it is `"NCHW"`, the data is stored in the order of:
  1004. `[batch_size, input_channels, input_height, input_width]`.
  1005. name(str, optional): For detailed information, please refer
  1006. to :ref:`api_guide_Name`. Usually name is no need to set and
  1007. None by default.
  1008. Returns:
  1009. Tensor: The output tensor of pooling result. The data type is same as input tensor.
  1010. Examples:
  1011. .. code-block:: python
  1012. >>> import paddle
  1013. >>> import paddle.nn.functional as F
  1014. >>> # max pool2d
  1015. >>> x = paddle.uniform([1, 3, 32, 32], paddle.float32)
  1016. >>> out = F.max_pool2d(x, kernel_size=2, stride=2, padding=0)
  1017. >>> print(out.shape)
  1018. [1, 3, 16, 16]
  1019. >>> # for return_mask=True
  1020. >>> out, max_indices = F.max_pool2d(x, kernel_size=2, stride=2, padding=0, return_mask=True)
  1021. >>> print(out.shape)
  1022. [1, 3, 16, 16]
  1023. >>> print(max_indices.shape)
  1024. [1, 3, 16, 16]
  1025. """
  1026. kernel_size = convert_to_list(kernel_size, 2, 'pool_size')
  1027. if stride is None:
  1028. stride = kernel_size
  1029. else:
  1030. stride = convert_to_list(stride, 2, 'pool_stride')
  1031. if data_format not in ["NCHW", "NHWC"]:
  1032. raise ValueError(
  1033. "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
  1034. "Attr(data_format): %s." % str(data_format)
  1035. )
  1036. channel_last = True if data_format == "NHWC" else False
  1037. padding, padding_algorithm = _update_padding_nd(
  1038. padding, num_dims=2, channel_last=channel_last, ceil_mode=ceil_mode
  1039. )
  1040. if data_format == "NHWC" and return_mask:
  1041. raise ValueError(
  1042. "When setting return_mask to true, data_format must be set to NCHW in API:max_pool2d"
  1043. )
  1044. if in_dynamic_or_pir_mode():
  1045. if return_mask:
  1046. output = _C_ops.max_pool2d_with_index(
  1047. x, kernel_size, stride, padding, False, False
  1048. )
  1049. return output if return_mask else output[0]
  1050. else:
  1051. return _C_ops.pool2d(
  1052. x,
  1053. kernel_size,
  1054. stride,
  1055. padding,
  1056. ceil_mode,
  1057. True,
  1058. data_format,
  1059. 'max',
  1060. False,
  1061. False,
  1062. padding_algorithm,
  1063. )
  1064. else:
  1065. op_type = 'max_pool2d_with_index' if return_mask else "pool2d"
  1066. helper = LayerHelper(op_type, **locals())
  1067. check_variable_and_dtype(
  1068. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'max_pool2d'
  1069. )
  1070. dtype = helper.input_dtype(input_param_name='x')
  1071. pool_out = helper.create_variable_for_type_inference(dtype)
  1072. if return_mask:
  1073. mask = helper.create_variable_for_type_inference("int32")
  1074. outputs = {"Out": pool_out, "Mask": mask}
  1075. helper.append_op(
  1076. type="max_pool2d_with_index",
  1077. inputs={"X": x},
  1078. outputs=outputs,
  1079. attrs={
  1080. "pooling_type": 'max',
  1081. "ksize": kernel_size,
  1082. "global_pooling": False,
  1083. "strides": stride,
  1084. "paddings": padding,
  1085. "padding_algorithm": padding_algorithm,
  1086. "use_cudnn": True,
  1087. "ceil_mode": ceil_mode,
  1088. "exclusive": True,
  1089. "data_format": data_format,
  1090. },
  1091. )
  1092. return (pool_out, mask)
  1093. else:
  1094. outputs = {"Out": pool_out}
  1095. helper.append_op(
  1096. type="pool2d",
  1097. inputs={"X": x},
  1098. outputs=outputs,
  1099. attrs={
  1100. "pooling_type": 'max',
  1101. "ksize": kernel_size,
  1102. "global_pooling": False,
  1103. "strides": stride,
  1104. "paddings": padding,
  1105. "padding_algorithm": padding_algorithm,
  1106. "use_cudnn": True,
  1107. "ceil_mode": ceil_mode,
  1108. "exclusive": True,
  1109. "data_format": data_format,
  1110. },
  1111. )
  1112. return pool_out
  1113. def max_pool3d(
  1114. x,
  1115. kernel_size,
  1116. stride=None,
  1117. padding=0,
  1118. return_mask=False,
  1119. ceil_mode=False,
  1120. data_format="NCDHW",
  1121. name=None,
  1122. ):
  1123. """
  1124. This API implements max pooling 3d operation.
  1125. See more details in :ref:`api_paddle_nn_MaxPool3D` .
  1126. Args:
  1127. x (Tensor): The input tensor of pooling operator, which is a 5-D tensor with
  1128. shape [N, C, D, H, W]. The format of input tensor is `"NCDHW"` or `"NDHWC"`, where N represents batch size, C represents the number of channels, D, H and W represent the depth, height and width of the feature respectively.
  1129. kernel_size (int|list|tuple): The pool kernel size. If the kernel size
  1130. is a tuple or list, it must contain three integers,
  1131. (kernel_size_Depth, kernel_size_Height, kernel_size_Width).
  1132. Otherwise, the pool kernel size will be the cube of an int.
  1133. stride (int|list|tuple): The pool stride size. If pool stride size is a tuple or list,
  1134. it must contain three integers, [stride_Depth, stride_Height, stride_Width).
  1135. Otherwise, the pool stride size will be a cube of an int.
  1136. padding (string|int|list|tuple): The padding size. Padding could be in one of the following forms.
  1137. 1. A string in ['valid', 'same'].
  1138. 2. An int, which means the feature map is zero padded by size of `padding` on every sides.
  1139. 3. A list[int] or tuple(int) whose length is 3, [pad_depth, pad_height, pad_weight] whose value means the padding size of each dimension.
  1140. 4. A list[int] or tuple(int) whose length is 6. [pad_depth_front, pad_depth_back, pad_height_top, pad_height_bottom, pad_width_left, pad_width_right] whose value means the padding size of each side.
  1141. 5. A list or tuple of pairs of integers. It has the form [[pad_before, pad_after], [pad_before, pad_after], ...]. Note that, the batch dimension and channel dimension should be [0,0] or (0,0).
  1142. The default value is 0.
  1143. ceil_mode (bool): ${ceil_mode_comment}
  1144. return_mask (bool): Whether to return the max indices along with the outputs. Default False. Only support "NDCHW" data_format.
  1145. data_format (string): The data format of the input and output data. An optional string from: `"NCDHW"`, `"NDHWC"`.
  1146. The default is `"NCDHW"`. When it is `"NCDHW"`, the data is stored in the order of:
  1147. `[batch_size, input_channels, input_depth, input_height, input_width]`.
  1148. name(str, optional): For detailed information, please refer
  1149. to :ref:`api_guide_Name`. Usually name is no need to set and
  1150. None by default.
  1151. Returns:
  1152. Tensor: The output tensor of pooling result. The data type is same as input tensor.
  1153. Examples:
  1154. .. code-block:: python
  1155. >>> import paddle
  1156. >>> import paddle.nn.functional as F
  1157. >>> # max pool3d
  1158. >>> x = paddle.uniform([1, 3, 32, 32, 32])
  1159. >>> output = F.max_pool3d(x,
  1160. ... kernel_size=2,
  1161. ... stride=2,
  1162. ... padding=0)
  1163. >>> print(output.shape)
  1164. [1, 3, 16, 16, 16]
  1165. >>> # for return_mask=True
  1166. >>> x = paddle.uniform([1, 3, 32, 32, 32])
  1167. >>> output, max_indices = paddle.nn.functional.max_pool3d(x,
  1168. ... kernel_size=2,
  1169. ... stride=2,
  1170. ... padding=0,
  1171. ... return_mask=True)
  1172. ...
  1173. >>> print(output.shape)
  1174. [1, 3, 16, 16, 16]
  1175. >>> print(max_indices.shape)
  1176. [1, 3, 16, 16, 16]
  1177. """
  1178. kernel_size = convert_to_list(kernel_size, 3, 'pool_size')
  1179. if stride is None:
  1180. stride = kernel_size
  1181. else:
  1182. stride = convert_to_list(stride, 3, 'pool_stride')
  1183. channel_last = _channel_last(data_format, 3)
  1184. padding, padding_algorithm = _update_padding_nd(
  1185. padding, 3, channel_last=channel_last, ceil_mode=ceil_mode
  1186. )
  1187. if data_format == "NDHWC" and return_mask:
  1188. raise ValueError(
  1189. "When setting return_mask to true, data_format must be set to NCDHW in API:max_pool3d"
  1190. )
  1191. if in_dynamic_or_pir_mode():
  1192. if return_mask:
  1193. output = _C_ops.max_pool3d_with_index(
  1194. x, kernel_size, stride, padding, False, False
  1195. )
  1196. return output if return_mask else output[0]
  1197. else:
  1198. return _C_ops.pool3d(
  1199. x,
  1200. kernel_size,
  1201. stride,
  1202. padding,
  1203. ceil_mode,
  1204. True,
  1205. data_format,
  1206. 'max',
  1207. False,
  1208. False,
  1209. padding_algorithm,
  1210. )
  1211. else:
  1212. op_type = "max_pool3d_with_index" if return_mask else "pool3d"
  1213. helper = LayerHelper(op_type, **locals())
  1214. check_variable_and_dtype(
  1215. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'max_pool3d'
  1216. )
  1217. dtype = helper.input_dtype(input_param_name='x')
  1218. pool_out = helper.create_variable_for_type_inference(dtype)
  1219. mask = helper.create_variable_for_type_inference('int32')
  1220. outputs = {"Out": pool_out, "Mask": mask}
  1221. helper.append_op(
  1222. type=op_type,
  1223. inputs={"X": x},
  1224. outputs=outputs,
  1225. attrs={
  1226. "pooling_type": 'max',
  1227. "ksize": kernel_size,
  1228. "global_pooling": False,
  1229. "strides": stride,
  1230. "paddings": padding,
  1231. "padding_algorithm": padding_algorithm,
  1232. "use_cudnn": True,
  1233. "ceil_mode": ceil_mode,
  1234. "exclusive": False,
  1235. "data_format": data_format,
  1236. },
  1237. )
  1238. return (pool_out, mask) if return_mask else pool_out
  1239. def adaptive_avg_pool1d(x, output_size, name=None):
  1240. """
  1241. Adaptive average pooling 1d operation on :attr:`x` according to :attr:`output_size`.
  1242. Notes:
  1243. See more details in :ref:`api_paddle_nn_AdaptiveAvgPool1d` .
  1244. Args:
  1245. x (Tensor): The input Tensor of pooling, which is a 3-D tensor with shape :math:`[N, C, L]`, where :math:`N` is batch size, :math:`C` is the number of channels and :math:`L` is the length of the feature. The data type is float32 or float64.
  1246. output_size (int): The target output size. Its data type must be int.
  1247. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1248. Returns:
  1249. Tensor: The result of 1D adaptive average pooling. Its data type is same as input.
  1250. Examples:
  1251. .. code-block:: python
  1252. >>> # average adaptive pool1d
  1253. >>> # suppose input data in shape of [N, C, L], `output_size` is m or [m],
  1254. >>> # output shape is [N, C, m], adaptive pool divide L dimension
  1255. >>> # of input data into m grids averagely and performs poolings in each
  1256. >>> # grid to get output.
  1257. >>> # adaptive max pool performs calculations as follow:
  1258. >>> #
  1259. >>> # for i in range(m):
  1260. >>> # lstart = floor(i * L / m)
  1261. >>> # lend = ceil((i + 1) * L / m)
  1262. >>> # output[:, :, i] = sum(input[:, :, lstart: lend])/(lstart - lend)
  1263. >>> #
  1264. >>> import paddle
  1265. >>> import paddle.nn.functional as F
  1266. >>> data = paddle.uniform([1, 3, 32])
  1267. >>> pool_out = F.adaptive_avg_pool1d(data, output_size=16)
  1268. >>> print(pool_out.shape)
  1269. [1, 3, 16]
  1270. """
  1271. pool_type = 'avg'
  1272. _check_input(x, 3)
  1273. pool_size = [1] + convert_to_list(output_size, 1, 'pool_size')
  1274. x = unsqueeze(x, [2])
  1275. if in_dynamic_or_pir_mode():
  1276. if in_dynamic_mode():
  1277. x = x._use_gpudnn(False)
  1278. pool_out = _C_ops.pool2d(
  1279. x,
  1280. pool_size,
  1281. [1, 1],
  1282. [0, 0],
  1283. False,
  1284. True,
  1285. "NCHW",
  1286. pool_type,
  1287. False,
  1288. True,
  1289. "EXPLICIT",
  1290. )
  1291. return squeeze(pool_out, [2])
  1292. else:
  1293. l_type = "pool2d"
  1294. check_variable_and_dtype(
  1295. x, 'x', ['float16', 'float32', 'float64'], 'adaptive_pool2d'
  1296. )
  1297. check_type(output_size, 'pool_size', (int), 'adaptive_pool1d')
  1298. helper = LayerHelper(l_type, **locals())
  1299. dtype = helper.input_dtype(input_param_name='x')
  1300. pool_out = helper.create_variable_for_type_inference(dtype)
  1301. outputs = {"Out": pool_out}
  1302. helper.append_op(
  1303. type=l_type,
  1304. inputs={"X": x},
  1305. outputs=outputs,
  1306. attrs={
  1307. "pooling_type": pool_type,
  1308. "ksize": pool_size,
  1309. "adaptive": True,
  1310. },
  1311. )
  1312. return squeeze(pool_out, [2])
  1313. def adaptive_avg_pool2d(x, output_size, data_format='NCHW', name=None):
  1314. r"""
  1315. Applies 2D adaptive avg pooling on input tensor. The h and w dimensions
  1316. of the output tensor are determined by the parameter output_size.
  1317. For avg adaptive pool2d:
  1318. .. math::
  1319. hstart &= floor(i * H_{in} / H_{out}) \\
  1320. hend &= ceil((i + 1) * H_{in} / H_{out}) \\
  1321. wstart &= floor(j * W_{in} / W_{out}) \\
  1322. wend &= ceil((j + 1) * W_{in} / W_{out}) \\
  1323. Output(i ,j) &= \frac{\sum Input[hstart:hend, wstart:wend]}{(hend - hstart) * (wend - wstart)}
  1324. Args:
  1325. x (Tensor): The input tensor of adaptive avg pool2d operator, which is a 4-D tensor.
  1326. The data type can be float32 or float64.
  1327. output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list,
  1328. it must contain two element, (H, W). H and W can be either a int, or None which means
  1329. the size will be the same as that of the input.
  1330. data_format (str, optional): The data format of the input and output data. An optional string
  1331. from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in
  1332. the order of: [batch_size, input_channels, input_height, input_width].
  1333. name(str, optional): For detailed information, please refer
  1334. to :ref:`api_guide_Name`. Usually name is no need to set and
  1335. None by default.
  1336. Returns:
  1337. Tensor, The output tensor of avg adaptive pool2d result. The data type is same as input tensor.
  1338. Examples:
  1339. .. code-block:: python
  1340. >>> # adaptive avg pool2d
  1341. >>> # suppose input data in shape of [N, C, H, W], `output_size` is [m, n],
  1342. >>> # output shape is [N, C, m, n], adaptive pool divide H and W dimensions
  1343. >>> # of input data into m * n grids averagely and performs poolings in each
  1344. >>> # grid to get output.
  1345. >>> # adaptive avg pool performs calculations as follow:
  1346. >>> #
  1347. >>> # for i in range(m):
  1348. >>> # for j in range(n):
  1349. >>> # hstart = floor(i * H / m)
  1350. >>> # hend = ceil((i + 1) * H / m)
  1351. >>> # wstart = floor(i * W / n)
  1352. >>> # wend = ceil((i + 1) * W / n)
  1353. >>> # output[:, :, i, j] = avg(input[:, :, hstart: hend, wstart: wend])
  1354. >>> #
  1355. >>> import paddle
  1356. >>> x = paddle.rand([2, 3, 32, 32])
  1357. >>> # x.shape is [2, 3, 32, 32]
  1358. >>> out = paddle.nn.functional.adaptive_avg_pool2d(x = x,
  1359. ... output_size=[3, 3])
  1360. >>> print(out.shape)
  1361. [2, 3, 3, 3]
  1362. """
  1363. if data_format not in ["NCHW", "NHWC"]:
  1364. raise ValueError(
  1365. "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
  1366. "Attr(data_format): %s." % str(data_format)
  1367. )
  1368. if data_format == "NCHW":
  1369. in_h, in_w = x.shape[2:4]
  1370. else:
  1371. in_h, in_w = x.shape[1:3]
  1372. if isinstance(output_size, int):
  1373. output_size = convert_to_list(output_size, 2, 'output_size')
  1374. else:
  1375. output_size = list(output_size)
  1376. if output_size[0] is None:
  1377. output_size[0] = in_h
  1378. if output_size[1] is None:
  1379. output_size[1] = in_w
  1380. if in_dygraph_mode():
  1381. output_size = [
  1382. np.array(item).item(0) if isinstance(item, Variable) else item
  1383. for item in output_size
  1384. ]
  1385. # output_size support Variable in static graph mode
  1386. elif _contain_var(output_size):
  1387. output_size = _convert_to_tensor_list(output_size)
  1388. if in_dynamic_or_pir_mode():
  1389. if in_dynamic_mode():
  1390. x = x._use_gpudnn(False)
  1391. return _C_ops.pool2d(
  1392. x,
  1393. output_size,
  1394. [1, 1],
  1395. [0, 0],
  1396. False,
  1397. True,
  1398. data_format,
  1399. 'avg',
  1400. False,
  1401. True,
  1402. "EXPLICIT",
  1403. )
  1404. else:
  1405. l_type = 'pool2d'
  1406. check_variable_and_dtype(
  1407. x, 'x', ['float16', 'float32', 'float64'], 'adaptive_avg_pool2d'
  1408. )
  1409. check_type(data_format, 'data_format', str, 'adaptive_avg_pool2d')
  1410. helper = LayerHelper(l_type, **locals())
  1411. dtype = helper.input_dtype(input_param_name='x')
  1412. pool_out = helper.create_variable_for_type_inference(dtype)
  1413. outputs = {"Out": pool_out}
  1414. helper.append_op(
  1415. type=l_type,
  1416. inputs={"X": x},
  1417. outputs=outputs,
  1418. attrs={
  1419. "pooling_type": "avg",
  1420. "ksize": output_size,
  1421. "adaptive": True,
  1422. "data_format": data_format,
  1423. },
  1424. )
  1425. return pool_out
  1426. def adaptive_avg_pool3d(x, output_size, data_format='NCDHW', name=None):
  1427. r"""
  1428. This operation applies 3D adaptive avg pooling on input tensor. The h and w dimensions
  1429. of the output tensor are determined by the parameter output_size.
  1430. For avg adaptive pool3d:
  1431. .. math::
  1432. dstart &= floor(i * D_{in} / D_{out}) \\
  1433. dend &= ceil((i + 1) * D_{in} / D_{out}) \\
  1434. hstart &= floor(j * H_{in} / H_{out}) \\
  1435. hend &= ceil((j + 1) * H_{in} / H_{out}) \\
  1436. wstart &= floor(k * W_{in} / W_{out}) \\
  1437. wend &= ceil((k + 1) * W_{in} / W_{out}) \\
  1438. Output(i ,j, k) &= \frac{\sum Input[dstart:dend, hstart:hend, wstart:wend]}
  1439. {(dend - dstart) * (hend - hstart) * (wend - wstart)}
  1440. Args:
  1441. x (Tensor): The input tensor of adaptive avg pool3d operator, which is a 5-D tensor.
  1442. The data type can be float32, float64.
  1443. output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or
  1444. list, it must contain three elements, (D, H, W). D, H and W can be either a int,
  1445. or None which means the size will be the same as that of the input.
  1446. data_format (str, optional): The data format of the input and output data. An optional string
  1447. from: "NCDHW", "NDHWC". The default is "NCDHW". When it is "NCDHW", the data is stored in
  1448. the order of: [batch_size, input_channels, input_depth, input_height, input_width].
  1449. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
  1450. Usually name is no need to set and None by default.
  1451. Returns:
  1452. Tensor, The output tensor of avg adaptive pool3d result. The data type is same as input tensor.
  1453. Examples:
  1454. .. code-block:: python
  1455. >>> # adaptive avg pool3d
  1456. >>> # suppose input data in shape of [N, C, D, H, W], `output_size` is [l, m, n],
  1457. >>> # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions
  1458. >>> # of input data into l * m * n grids averagely and performs poolings in each
  1459. >>> # grid to get output.
  1460. >>> # adaptive avg pool performs calculations as follow:
  1461. >>> #
  1462. >>> # for i in range(l):
  1463. >>> # for j in range(m):
  1464. >>> # for k in range(n):
  1465. >>> # dstart = floor(i * D / l)
  1466. >>> # dend = ceil((i + 1) * D / l)
  1467. >>> # hstart = floor(j * H / m)
  1468. >>> # hend = ceil((j + 1) * H / m)
  1469. >>> # wstart = floor(k * W / n)
  1470. >>> # wend = ceil((k + 1) * W / n)
  1471. >>> # output[:, :, i, j, k] =
  1472. >>> # avg(input[:, :, dstart:dend, hstart: hend, wstart: wend])
  1473. >>> import paddle
  1474. >>> input_data = paddle.randn(shape=(2, 3, 8, 32, 32))
  1475. >>> out = paddle.nn.functional.adaptive_avg_pool3d(x = input_data,
  1476. ... output_size=[3, 3, 3])
  1477. >>> print(out.shape)
  1478. [2, 3, 3, 3, 3]
  1479. """
  1480. if data_format not in ["NCDHW", "NDHWC"]:
  1481. raise ValueError(
  1482. "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received "
  1483. "Attr(data_format): %s." % str(data_format)
  1484. )
  1485. if data_format == "NCDHW":
  1486. in_l, in_h, in_w = x.shape[2:5]
  1487. else:
  1488. in_l, in_h, in_w = x.shape[1:4]
  1489. if isinstance(output_size, int):
  1490. output_size = convert_to_list(output_size, 3, 'output_size')
  1491. else:
  1492. output_size = list(output_size)
  1493. if output_size[0] is None:
  1494. output_size[0] = in_l
  1495. if output_size[1] is None:
  1496. output_size[1] = in_h
  1497. if output_size[2] is None:
  1498. output_size[2] = in_w
  1499. if in_dynamic_or_pir_mode():
  1500. if in_dynamic_mode():
  1501. x = x._use_gpudnn(False)
  1502. return _C_ops.pool3d(
  1503. x,
  1504. output_size,
  1505. [1, 1, 1],
  1506. [0, 0, 0],
  1507. False,
  1508. True,
  1509. data_format,
  1510. 'avg',
  1511. False,
  1512. True,
  1513. "EXPLICIT",
  1514. )
  1515. else:
  1516. l_type = 'pool3d'
  1517. check_variable_and_dtype(
  1518. x, 'x', ['float16', 'float32', 'float64'], 'adaptive_avg_pool2d'
  1519. )
  1520. check_type(data_format, 'data_format', str, 'adaptive_avg_pool2d')
  1521. helper = LayerHelper(l_type, **locals())
  1522. dtype = helper.input_dtype(input_param_name='x')
  1523. pool_out = helper.create_variable_for_type_inference(dtype)
  1524. outputs = {"Out": pool_out}
  1525. helper.append_op(
  1526. type=l_type,
  1527. inputs={"X": x},
  1528. outputs=outputs,
  1529. attrs={
  1530. "pooling_type": "avg",
  1531. "ksize": output_size,
  1532. "adaptive": True,
  1533. "data_format": data_format,
  1534. },
  1535. )
  1536. return pool_out
  1537. def adaptive_max_pool1d(x, output_size, return_mask=False, name=None):
  1538. """
  1539. This API implements adaptive max pooling 1d operation.
  1540. See more details in :ref:`api_paddle_nn_AdaptiveMaxPool1d` .
  1541. Args:
  1542. x (Tensor): The input tensor of pooling operator, which is a 3-D tensor
  1543. with shape [N, C, L]. The format of input tensor is NCL,
  1544. where N is batch size, C is the number of channels, L is the
  1545. length of the feature. The data type is float32 or float64.
  1546. output_size (int): The pool kernel size. The value should be an integer.
  1547. return_mask (bool): If true, the index of max pooling point will be returned along
  1548. with outputs. It cannot be set in average pooling type. Default False.
  1549. name(str, optional): For detailed information, please refer
  1550. to :ref:`api_guide_Name`. Usually name is no need to set and
  1551. None by default.
  1552. Returns:
  1553. Tensor: The output tensor of adaptive pooling result. The data type is same
  1554. as input tensor.
  1555. Examples:
  1556. .. code-block:: python
  1557. >>> # max adaptive pool1d
  1558. >>> # suppose input data in shape of [N, C, L], `output_size` is m or [m],
  1559. >>> # output shape is [N, C, m], adaptive pool divide L dimension
  1560. >>> # of input data into m grids averagely and performs poolings in each
  1561. >>> # grid to get output.
  1562. >>> # adaptive max pool performs calculations as follow:
  1563. >>> #
  1564. >>> # for i in range(m):
  1565. >>> # lstart = floor(i * L / m)
  1566. >>> # lend = ceil((i + 1) * L / m)
  1567. >>> # output[:, :, i] = max(input[:, :, lstart: lend])
  1568. >>> #
  1569. >>> import paddle
  1570. >>> import paddle.nn.functional as F
  1571. >>> data = paddle.uniform([1, 3, 32], paddle.float32)
  1572. >>> pool_out = F.adaptive_max_pool1d(data, output_size=16)
  1573. >>> print(pool_out.shape)
  1574. [1, 3, 16]
  1575. >>> pool_out, indices = F.adaptive_max_pool1d(data, output_size=16, return_mask=True)
  1576. >>> print(pool_out.shape)
  1577. [1, 3, 16]
  1578. >>> print(indices.shape)
  1579. [1, 3, 16]
  1580. """
  1581. _check_input(x, 3)
  1582. pool_size = [1] + convert_to_list(output_size, 1, 'pool_size')
  1583. x = unsqueeze(x, [2])
  1584. if in_dygraph_mode():
  1585. pool_out = _C_ops.max_pool2d_with_index(
  1586. x, pool_size, [1, 1], [0, 0], False, True
  1587. )
  1588. return (
  1589. (squeeze(pool_out[0], [2]), squeeze(pool_out[1], [2]))
  1590. if return_mask
  1591. else squeeze(pool_out[0], [2])
  1592. )
  1593. else:
  1594. l_type = 'max_pool2d_with_index'
  1595. check_variable_and_dtype(
  1596. x, 'x', ['float32', 'float64'], 'adaptive_max_pool1d'
  1597. )
  1598. check_type(output_size, 'pool_size', int, 'adaptive_max_pool1d')
  1599. check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool1d')
  1600. helper = LayerHelper(l_type, **locals())
  1601. dtype = helper.input_dtype(input_param_name='x')
  1602. pool_out = helper.create_variable_for_type_inference(dtype)
  1603. mask = helper.create_variable_for_type_inference('int32')
  1604. outputs = {"Out": pool_out, "Mask": mask}
  1605. helper.append_op(
  1606. type=l_type,
  1607. inputs={"X": x},
  1608. outputs=outputs,
  1609. attrs={
  1610. "pooling_type": 'max',
  1611. "ksize": pool_size,
  1612. "adaptive": True,
  1613. },
  1614. )
  1615. return (
  1616. (squeeze(pool_out, [2]), squeeze(mask, [2]))
  1617. if return_mask
  1618. else squeeze(pool_out, [2])
  1619. )
  1620. def adaptive_max_pool2d(x, output_size, return_mask=False, name=None):
  1621. """
  1622. This operation applies a 2D adaptive max pooling on input tensor.
  1623. See more details in :ref:`api_paddle_nn_AdaptiveMaxPool2d` .
  1624. Args:
  1625. x (Tensor): The input tensor of adaptive max pool2d operator, which is a 4-D tensor. The data type can be float16, float32, float64, int32 or int64.
  1626. output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain two elements, (H, W). H and W can be either a int, or None which means the size will be the same as that of the input.
  1627. return_mask (bool): If true, the index of max pooling point will be returned along with outputs. Default False.
  1628. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default.
  1629. Returns:
  1630. Tensor: The output tensor of adaptive max pool2d result. The data type is same as input tensor.
  1631. Examples:
  1632. .. code-block:: python
  1633. >>> # max adaptive pool2d
  1634. >>> # suppose input data in the shape of [N, C, H, W], `output_size` is [m, n]
  1635. >>> # output shape is [N, C, m, n], adaptive pool divide H and W dimensions
  1636. >>> # of input data into m*n grids averagely and performs poolings in each
  1637. >>> # grid to get output.
  1638. >>> # adaptive max pool performs calculations as follow:
  1639. >>> #
  1640. >>> # for i in range(m):
  1641. >>> # for j in range(n):
  1642. >>> # hstart = floor(i * H / m)
  1643. >>> # hend = ceil((i + 1) * H / m)
  1644. >>> # wstart = floor(i * W / n)
  1645. >>> # wend = ceil((i + 1) * W / n)
  1646. >>> # output[:, :, i, j] = max(input[:, :, hstart: hend, wstart: wend])
  1647. >>> #
  1648. >>> import paddle
  1649. >>> input_data = paddle.randn(shape=(2, 3, 32, 32))
  1650. >>> out = paddle.nn.functional.adaptive_max_pool2d(x = input_data,
  1651. ... output_size=[3, 3])
  1652. >>> print(out.shape)
  1653. [2, 3, 3, 3]
  1654. """
  1655. _check_input(x, 4)
  1656. in_h, in_w = x.shape[2:4]
  1657. if isinstance(output_size, int):
  1658. output_size = convert_to_list(output_size, 2, 'output_size')
  1659. else:
  1660. output_size = list(output_size)
  1661. if output_size[0] is None:
  1662. output_size[0] = in_h
  1663. if output_size[1] is None:
  1664. output_size[1] = in_w
  1665. if in_dygraph_mode():
  1666. pool_out = _C_ops.max_pool2d_with_index(
  1667. x, output_size, [1, 1], [0, 0], False, True
  1668. )
  1669. return pool_out if return_mask else pool_out[0]
  1670. else:
  1671. l_type = 'max_pool2d_with_index'
  1672. check_variable_and_dtype(
  1673. x, 'x', ['float32', 'float64'], 'adaptive_max_pool2d'
  1674. )
  1675. check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool2d')
  1676. # check_type(output_size, 'pool_size', (int), 'adaptive_max_pool2d')
  1677. helper = LayerHelper(l_type, **locals())
  1678. dtype = helper.input_dtype(input_param_name='x')
  1679. pool_out = helper.create_variable_for_type_inference(dtype)
  1680. mask = helper.create_variable_for_type_inference('int32')
  1681. outputs = {"Out": pool_out, "Mask": mask}
  1682. helper.append_op(
  1683. type=l_type,
  1684. inputs={"X": x},
  1685. outputs=outputs,
  1686. attrs={
  1687. "pooling_type": 'max',
  1688. "ksize": output_size,
  1689. "adaptive": True,
  1690. },
  1691. )
  1692. return (pool_out, mask) if return_mask else pool_out
  1693. def adaptive_max_pool3d(x, output_size, return_mask=False, name=None):
  1694. """
  1695. This operation applies a 3D adaptive max pooling on input tensor.
  1696. See more details in :ref:`api_paddle_nn_AdaptiveMaxPool3d` .
  1697. Args:
  1698. x (Tensor): The input tensor of adaptive max pool3d operator, which is a 5-D tensor. The data type can be float32, float64.
  1699. output_size (int|list|tuple): The pool kernel size. If pool kernel size is a tuple or list, it must contain three elements, (D, H, W). D, H and W can be either a int, or None which means the size will be the same as that of the input.
  1700. return_mask (bool): If true, the index of max pooling point will be returned along with outputs. Default False.
  1701. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`. Usually name is no need to set and None by default.
  1702. Returns:
  1703. Tensor: The output tensor of adaptive max pool3d result. The data type is same as input tensor.
  1704. Examples:
  1705. .. code-block:: python
  1706. >>> # adaptive max pool3d
  1707. >>> # suppose input data in the shape of [N, C, D, H, W], `output_size` is [l, m, n]
  1708. >>> # output shape is [N, C, l, m, n], adaptive pool divide D, H and W dimensions
  1709. >>> # of input data into m*n grids averagely and performs poolings in each
  1710. >>> # grid to get output.
  1711. >>> # adaptive max pool performs calculations as follow:
  1712. >>> #
  1713. >>> # for i in range(l):
  1714. >>> # for j in range(m):
  1715. >>> # for k in range(n):
  1716. >>> # dstart = floor(i * D / l)
  1717. >>> # dend = ceil((i + 1) * D / l)
  1718. >>> # hstart = floor(i * H / m)
  1719. >>> # hend = ceil((i + 1) * H / m)
  1720. >>> # wstart = floor(i * W / n)
  1721. >>> # wend = ceil((i + 1) * W / n)
  1722. >>> # output[:, :, i, j, k] = max(input[:, :, dstart: dend, hstart: hend, wstart: wend])
  1723. >>> #
  1724. >>> import paddle
  1725. >>> input_data = paddle.randn(shape=(2, 3, 8, 32, 32))
  1726. >>> out = paddle.nn.functional.adaptive_max_pool3d(x = input_data,
  1727. ... output_size=[3, 3, 3])
  1728. >>> print(out.shape)
  1729. [2, 3, 3, 3, 3]
  1730. """
  1731. _check_input(x, 5)
  1732. in_l, in_h, in_w = x.shape[2:5]
  1733. if isinstance(output_size, int):
  1734. output_size = convert_to_list(output_size, 3, 'output_size')
  1735. else:
  1736. output_size = list(output_size)
  1737. if output_size[0] is None:
  1738. output_size[0] = in_l
  1739. if output_size[1] is None:
  1740. output_size[1] = in_h
  1741. if output_size[2] is None:
  1742. output_size[2] = in_w
  1743. if in_dygraph_mode():
  1744. # By default, strides is [1,1,1] and paddings is [0, 0, 0]
  1745. pool_out = _C_ops.max_pool3d_with_index(
  1746. x, output_size, [1, 1, 1], [0, 0, 0], False, True
  1747. )
  1748. return pool_out if return_mask else pool_out[0]
  1749. else:
  1750. l_type = 'max_pool3d_with_index'
  1751. check_variable_and_dtype(
  1752. x, 'x', ['float32', 'float64'], 'adaptive_max_pool3d'
  1753. )
  1754. check_type(return_mask, 'return_mask', bool, 'adaptive_max_pool3d')
  1755. # check_type(output_size, 'pool_size', (int), 'adaptive_max_pool3d')
  1756. helper = LayerHelper(l_type, **locals())
  1757. dtype = helper.input_dtype(input_param_name='x')
  1758. pool_out = helper.create_variable_for_type_inference(dtype)
  1759. mask = helper.create_variable_for_type_inference('int32')
  1760. outputs = {"Out": pool_out, "Mask": mask}
  1761. helper.append_op(
  1762. type=l_type,
  1763. inputs={"X": x},
  1764. outputs=outputs,
  1765. attrs={
  1766. "pooling_type": 'max',
  1767. "ksize": output_size,
  1768. "adaptive": True,
  1769. },
  1770. )
  1771. return (pool_out, mask) if return_mask else pool_out
  1772. def fractional_max_pool2d(
  1773. x,
  1774. output_size,
  1775. kernel_size=None,
  1776. random_u=None,
  1777. return_mask=False,
  1778. name=None,
  1779. ):
  1780. r"""
  1781. This operation applies 2D fractional max pooling on input tensor, which is described in the paper:
  1782. [1] Ben Graham, Fractional Max-Pooling. 2015. http://arxiv.org/abs/1412.6071
  1783. The h and w dimensions of the output tensor are determined by the parameter output_size.
  1784. For each dimension, the fractional max pooling:
  1785. .. math::
  1786. \alpha &= size_{input} / size_{output}
  1787. index_{start} &= ceil( \alpha * (i + u) - 1)
  1788. index_{end} &= ceil( \alpha * (i + 1 + u) - 1)
  1789. Output &= max(Input[index_{start}:index_{end}])
  1790. where, u \in (0, 1), i = 0,1,2...size_{output}
  1791. The ``u`` from the formula is the parameter ``random_u``, and subtract ``1`` for the index starts from ``0``
  1792. instead of ``1`` where ``ceil`` works.
  1793. For instance, giving a sequence of length ``7`` is ``[2, 4, 3, 1, 5, 2, 3]``, ``output_size`` is ``5`` and ``random_u`` is ``0.3``.
  1794. The ``alpha = 7/5 = 1.4``, the starts of index is ``[0, 1, 3, 4, 6]``, the ends of index is ``[1, 3, 4, 6, 7]`` and makes the
  1795. random sequence in the paper is ``index_end - index_start = [1, 2, 1, 2, 1]``. The strides and kernel_sizes are both equal to
  1796. the random sequence, giving the final pooling output is ``[2, 4, 1, 5, 3]``.
  1797. Parameters:
  1798. x (Tensor): The input tensor of fractional max pool2d operator, which is a 4-D tensor. The data type can be float16, bfloat16, float32, float64.
  1799. output_size(int|list|tuple): The output size. If output size is a tuple or list, it must contain
  1800. two element, (H, W). H and W can be either a int, or None which means the size will be the same as that of
  1801. the input.
  1802. kernel_size (int|list|tuple, optional): The pool kernel size. If the kernel size
  1803. is a tuple or list, it must contain two integers, (kernel_size_Height, kernel_size_Width).
  1804. Otherwise, the pool kernel size will be the square of an int. Default is None, means using the non-overlapping mode.
  1805. random_u(float): A random float number in range (0, 1) for the fractional pooling.
  1806. Default None, means randomly generated by framework which can be fixed by ``paddle.seed``.
  1807. return_mask(bool, optional): If true, the index of max pooling point will be returned along with outputs. Default False.
  1808. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
  1809. Usually name is no need to set and None by default.
  1810. Returns:
  1811. Tensor: The output tensor of fractional max pool2d result which is a 4-D tensor.. The data type is same as input tensor.
  1812. Examples:
  1813. .. code-block:: python
  1814. >>> # fractional max pool2d
  1815. >>> # suppose input data in shape of [N, C, H, W], `output_size` is [m, n],
  1816. >>> # output shape is [N, C, m, n], fractional pool divide H and W dimensions
  1817. >>> # of input data into m * n grids and performs poolings in each
  1818. >>> # grid to get output.
  1819. >>> import paddle
  1820. >>> x = paddle.rand([2, 3, 32, 32])
  1821. >>> # disjont: without `kernel_size`
  1822. >>> pool_out = paddle.nn.functional.fractional_max_pool2d(x, output_size=3)
  1823. >>> print(pool_out.shape)
  1824. [2, 3, 3, 3]
  1825. >>> # overlapping: with `kernel_size`
  1826. >>> pool_out = paddle.nn.functional.fractional_max_pool2d(x, kernel_size=2, output_size=3)
  1827. >>> print(pool_out.shape)
  1828. [2, 3, 3, 3]
  1829. >>> pool_out, indices = paddle.nn.functional.fractional_max_pool2d(x, output_size=[2, 3], return_mask=True)
  1830. >>> print(pool_out.shape)
  1831. [2, 3, 2, 3]
  1832. >>> print(indices.shape)
  1833. [2, 3, 2, 3]
  1834. """
  1835. _check_input(x, 4)
  1836. if random_u is None:
  1837. random_u = 0.0
  1838. else:
  1839. if random_u <= 0 or random_u >= 1:
  1840. raise ValueError(
  1841. "The param `random_u` should be a `float` in (0, 1)."
  1842. )
  1843. kernel_size = (
  1844. convert_to_list(kernel_size, 2, 'kernel_size')
  1845. if kernel_size is not None
  1846. else [0, 0]
  1847. )
  1848. in_h, in_w = x.shape[2:4]
  1849. if isinstance(output_size, int):
  1850. output_size = convert_to_list(output_size, 2, 'output_size')
  1851. else:
  1852. output_size = list(output_size)
  1853. if output_size[0] is None:
  1854. output_size[0] = in_h
  1855. if output_size[1] is None:
  1856. output_size[1] = in_w
  1857. if in_dygraph_mode():
  1858. pool_out = _C_ops.fractional_max_pool2d(
  1859. x, output_size, kernel_size, float(random_u), return_mask
  1860. )
  1861. return pool_out if return_mask else pool_out[0]
  1862. else:
  1863. l_type = 'fractional_max_pool2d'
  1864. check_variable_and_dtype(
  1865. x,
  1866. 'x',
  1867. ['uint16', 'float16', 'float32', 'float64'],
  1868. 'fractional_max_pool2d',
  1869. )
  1870. check_type(return_mask, 'return_mask', bool, 'fractional_max_pool2d')
  1871. check_type(
  1872. random_u,
  1873. 'random_u',
  1874. float,
  1875. 'fractional_max_pool2d',
  1876. )
  1877. helper = LayerHelper(l_type, **locals())
  1878. dtype = helper.input_dtype(input_param_name='x')
  1879. pool_out = helper.create_variable_for_type_inference(dtype)
  1880. mask = helper.create_variable_for_type_inference('int32')
  1881. outputs = {"out": pool_out, "mask": mask}
  1882. helper.append_op(
  1883. type=l_type,
  1884. inputs={"x": x},
  1885. outputs=outputs,
  1886. attrs={
  1887. "output_size": output_size,
  1888. "kernel_size": kernel_size,
  1889. "random_u": random_u,
  1890. "return_mask": return_mask,
  1891. },
  1892. )
  1893. return (pool_out, mask) if return_mask else pool_out
  1894. def fractional_max_pool3d(
  1895. x,
  1896. output_size,
  1897. kernel_size=None,
  1898. random_u=None,
  1899. return_mask=False,
  1900. name=None,
  1901. ):
  1902. r"""
  1903. This operation applies 3D fractional max pooling on input tensor, which is described in the paper:
  1904. [1] Ben Graham, Fractional Max-Pooling. 2015. http://arxiv.org/abs/1412.6071
  1905. The d, h and w dimensions of the output tensor are determined by the parameter output_size.
  1906. For each dimension, the fractional max pooling:
  1907. .. math::
  1908. \alpha &= size_{input} / size_{output}
  1909. index_{start} &= ceil( \alpha * (i + u) - 1)
  1910. index_{end} &= ceil( \alpha * (i + 1 + u) - 1)
  1911. Output &= max(Input[index_{start}:index_{end}])
  1912. where, u \in (0, 1), i = 0,1,2...size_{output}
  1913. The ``u`` from the formula is the parameter ``random_u``, and subtract ``1`` for the index starts from ``0``
  1914. instead of ``1`` where ``ceil`` works.
  1915. For instance, giving a sequence of length ``7`` is ``[2, 4, 3, 1, 5, 2, 3]``, ``output_size`` is ``5`` and ``random_u`` is ``0.3``.
  1916. The ``alpha = 7/5 = 1.4``, the starts of index is ``[0, 1, 3, 4, 6]``, the ends of index is ``[1, 3, 4, 6, 7]`` and makes the
  1917. random sequence in the paper is ``index_end - index_start = [1, 2, 1, 2, 1]``. The strides and kernel_sizes are both equal to
  1918. the random sequence, giving the final pooling output is ``[2, 4, 1, 5, 3]``.
  1919. Parameters:
  1920. x (Tensor): The input tensor of fractional max pool3d operator, which is a 5-D tensor. The data type can be float16, bfloat16, float32, float64.
  1921. output_size(int|list|tuple): The output size. If output size is a tuple or list, it must contain
  1922. three element, (D, H, W). D, H and W can be either a int, or None which means the size will be the same as that of
  1923. the input.
  1924. kernel_size (int|list|tuple): The pool kernel size. If the kernel size
  1925. is a tuple or list, it must contain three integers, (kernel_size_Depth, kernel_size_Height, kernel_size_Width).
  1926. Otherwise, the pool kernel size will be the cube of an int. Default is None, means using the non-overlapping mode.
  1927. random_u(float): A random float number in range (0, 1) for the fractional pooling.
  1928. Default None, means randomly generated by framework which can be fixed by ``paddle.seed``.
  1929. return_mask(bool, optional): If true, the index of max pooling point will be returned along with outputs. Default False.
  1930. name(str, optional): For detailed information, please refer to :ref:`api_guide_Name`.
  1931. Usually name is no need to set and None by default.
  1932. Returns:
  1933. Tensor: The output tensor of fractional max pool3d result which is a 5-D tensor.. The data type is same as input tensor.
  1934. Examples:
  1935. .. code-block:: python
  1936. >>> # fractional max pool3d
  1937. >>> # suppose input data in shape of [N, C, D, H, W], `output_size` is [l, m, n],
  1938. >>> # output shape is [N, C, l, m, n], fractional pool divide D, H and W dimensions
  1939. >>> # of input data into l * m * n grids and performs poolings in each
  1940. >>> # grid to get output.
  1941. >>> import paddle
  1942. >>> x = paddle.rand([2, 3, 8, 32, 32])
  1943. >>> # disjont: without `kernel_size`
  1944. >>> pool_out = paddle.nn.functional.fractional_max_pool3d(x, output_size=3)
  1945. >>> print(pool_out.shape)
  1946. [2, 3, 3, 3, 3]
  1947. >>> # overlapping: with `kernel_size`
  1948. >>> pool_out = paddle.nn.functional.fractional_max_pool3d(x, kernel_size=2, output_size=3)
  1949. >>> print(pool_out.shape)
  1950. [2, 3, 3, 3, 3]
  1951. >>> pool_out, indices = paddle.nn.functional.fractional_max_pool3d(x, output_size=[2, 3, 3], return_mask=True)
  1952. >>> print(pool_out.shape)
  1953. [2, 3, 2, 3, 3]
  1954. >>> print(indices.shape)
  1955. [2, 3, 2, 3, 3]
  1956. """
  1957. _check_input(x, 5)
  1958. if random_u is None:
  1959. random_u = 0.0
  1960. else:
  1961. if random_u <= 0 or random_u >= 1:
  1962. raise ValueError(
  1963. "The param `random_u` should be a `float` in (0, 1)."
  1964. )
  1965. kernel_size = (
  1966. convert_to_list(kernel_size, 3, 'kernel_size')
  1967. if kernel_size is not None
  1968. else [0, 0, 0]
  1969. )
  1970. in_l, in_h, in_w = x.shape[2:5]
  1971. if isinstance(output_size, int):
  1972. output_size = convert_to_list(output_size, 3, 'output_size')
  1973. else:
  1974. output_size = list(output_size)
  1975. if output_size[0] is None:
  1976. output_size[0] = in_l
  1977. if output_size[1] is None:
  1978. output_size[1] = in_h
  1979. if output_size[2] is None:
  1980. output_size[2] = in_w
  1981. if in_dygraph_mode():
  1982. pool_out = _C_ops.fractional_max_pool3d(
  1983. x,
  1984. output_size,
  1985. kernel_size,
  1986. float(random_u),
  1987. return_mask,
  1988. )
  1989. return pool_out if return_mask else pool_out[0]
  1990. else:
  1991. l_type = 'fractional_max_pool3d'
  1992. check_variable_and_dtype(
  1993. x,
  1994. 'x',
  1995. ['uint16', 'float16', 'float32', 'float64'],
  1996. 'fractional_max_pool3d',
  1997. )
  1998. check_type(return_mask, 'return_mask', bool, 'fractional_max_pool3d')
  1999. check_type(
  2000. random_u,
  2001. 'random_u',
  2002. float,
  2003. 'fractional_max_pool3d',
  2004. )
  2005. helper = LayerHelper(l_type, **locals())
  2006. dtype = helper.input_dtype(input_param_name='x')
  2007. pool_out = helper.create_variable_for_type_inference(dtype)
  2008. mask = helper.create_variable_for_type_inference('int32')
  2009. outputs = {"out": pool_out, "mask": mask}
  2010. helper.append_op(
  2011. type=l_type,
  2012. inputs={"x": x},
  2013. outputs=outputs,
  2014. attrs={
  2015. "output_size": output_size,
  2016. "kernel_size": kernel_size,
  2017. "random_u": random_u,
  2018. "return_mask": return_mask,
  2019. },
  2020. )
  2021. return (pool_out, mask) if return_mask else pool_out