common.py 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434
  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
  15. import paddle
  16. from paddle import _C_ops, pir
  17. from paddle.base.layer_helper import LayerHelper
  18. from paddle.common_ops_import import Variable, default_main_program
  19. from paddle.framework import (
  20. core,
  21. in_dynamic_mode,
  22. in_dynamic_or_pir_mode,
  23. in_pir_mode,
  24. )
  25. from paddle.tensor.creation import full
  26. from ...base.data_feeder import (
  27. check_dtype,
  28. check_type,
  29. check_variable_and_dtype,
  30. )
  31. from ...tensor import clip, concat, sqrt, sum
  32. from ...tensor.creation import zeros
  33. # TODO: define the common functions to build a neural network
  34. from ...tensor.manipulation import squeeze, unsqueeze
  35. __all__ = []
  36. def unfold(x, kernel_sizes, strides=1, paddings=0, dilations=1, name=None):
  37. r"""
  38. Return a col buffer of sliding local blocks of input x, also known
  39. as im2col for batched 2D image tensors. For each block under the convolution filter,
  40. all element will be rearranged as a column. While the convolution filter sliding over
  41. the input feature map, a series of such columns will be formed.
  42. For each input :math:`x` with shape [N, C, H, W], the output shape [N, Cout, Lout]
  43. can be calculated as following.
  44. .. math::
  45. dkernel[0] &= dilations[0] \times (kernel\_sizes[0] - 1) + 1
  46. dkernel[1] &= dilations[1] \times (kernel\_sizes[1] - 1) + 1
  47. hout &= \frac{H + paddings[0] + paddings[2] - dkernel[0]}{strides[0]} + 1
  48. wout &= \frac{W + paddings[1] + paddings[3] - dkernel[1]}{strides[1]} + 1
  49. Cout &= C \times kernel\_sizes[0] \times kernel\_sizes[1]
  50. Lout &= hout \times wout
  51. Parameters:
  52. x(Tensor): 4-D Tensor, input tensor of format [N, C, H, W],
  53. data type can be float32 or float64
  54. kernel_sizes(int|list|tuple): The size of convolution kernel, should be [k_h, k_w]
  55. or an integer k treated as [k, k].
  56. strides(int|list|tuple, optional): The strides, should be [stride_h, stride_w]
  57. or an integer stride treated as [stride, stride].
  58. For default, strides will be [1, 1].
  59. paddings(int|list|tuple, optional): The paddings of each dimension, should be
  60. [padding_top, padding_left, padding_bottom, padding_right]
  61. or [padding_h, padding_w] or an integer padding.
  62. If [padding_h, padding_w] was given, it will expanded to
  63. [padding_h, padding_w, padding_h, padding_w]. If an integer
  64. padding was given, [padding, padding, padding, padding] will
  65. be used. For default, paddings will be [0, 0, 0, 0]
  66. dilations(int|list|tuple, optional): the dilations of convolution kernel, should be
  67. [dilation_h, dilation_w], or an integer dilation treated as
  68. [dilation, dilation]. For default, it will be [1, 1].
  69. name(str, optional): The default value is None.
  70. Normally there is no need for user to set this property.
  71. For more information, please refer to :ref:`api_guide_Name`
  72. Returns:
  73. Tensor, The tensor corresponding to the sliding local blocks.
  74. The output shape is [N, Cout, Lout] as described above.
  75. Cout is the total number of values within each block,
  76. and Lout is the total number of such blocks.
  77. The data type of output is the same as the input :math:`x`
  78. Examples:
  79. .. code-block:: python
  80. >>> import paddle
  81. >>> import paddle.nn.functional as F
  82. >>> x = paddle.randn((100,3,224,224))
  83. >>> y = F.unfold(x, [3, 3], 1, 1, 1)
  84. """
  85. helper = LayerHelper("unfold", **locals())
  86. check_variable_and_dtype(
  87. x, 'x', ['uint16', 'float16', 'float32', 'float64'], 'unfold'
  88. )
  89. assert len(x.shape) == 4, "input should be the format of [N, C, H, W]"
  90. if isinstance(kernel_sizes, int):
  91. kernel_sizes = [kernel_sizes, kernel_sizes]
  92. else:
  93. assert isinstance(kernel_sizes, (list, tuple)) and (
  94. len(kernel_sizes) == 2
  95. ), "kernel_sizes should either be an integer or a list/tuple of two integers"
  96. kernel_sizes = list(kernel_sizes)
  97. if isinstance(strides, int):
  98. strides = [strides, strides]
  99. else:
  100. assert isinstance(strides, (list, tuple)) and (
  101. len(strides) == 2
  102. ), "strides should either be an integer or a list/tuple of two integers"
  103. strides = list(strides)
  104. if isinstance(dilations, int):
  105. dilations = [dilations, dilations]
  106. else:
  107. assert isinstance(dilations, (list, tuple)) and (
  108. len(dilations) == 2
  109. ), "dilations should either be an integer or a list/tuple of two integers"
  110. dilations = list(dilations)
  111. if isinstance(paddings, int):
  112. paddings = [paddings] * 4
  113. elif isinstance(paddings, (list, tuple)):
  114. paddings = list(paddings)
  115. if len(paddings) == 2:
  116. paddings = paddings * 2
  117. elif len(paddings) == 4:
  118. pass
  119. else:
  120. raise ValueError(
  121. "paddings should either be an integer or a list/tuple of 2 or 4 integers"
  122. )
  123. else:
  124. raise ValueError(
  125. "Unexpected type of paddings, it should be either an integer or a list/tuple"
  126. "of 2 or 4 integers"
  127. )
  128. if in_dynamic_or_pir_mode():
  129. return _C_ops.unfold(x, kernel_sizes, strides, paddings, dilations)
  130. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  131. helper.append_op(
  132. type="unfold",
  133. inputs={"X": x},
  134. outputs={"Y": out},
  135. attrs={
  136. "kernel_sizes": kernel_sizes,
  137. "strides": strides,
  138. "paddings": paddings,
  139. "dilations": dilations,
  140. },
  141. )
  142. return out
  143. def interpolate(
  144. x,
  145. size=None,
  146. scale_factor=None,
  147. mode='nearest',
  148. align_corners=False,
  149. align_mode=0,
  150. data_format=None,
  151. name=None,
  152. ):
  153. """
  154. This API resizes a batch of images.
  155. The input must be be a 3-D Tensor of the shape (num_batches, channels, in_w)
  156. or (num_batches, in_w, channels), or 4-D (num_batches, channels, in_h, in_w) or
  157. (num_batches, in_h, in_w, channels), or a 5-D Tensor of the shape
  158. (num_batches, channels, in_d, in_h, in_w) or (num_batches, in_d, in_h, in_w, channels),
  159. Where in_w is width of the input tensor, in_h is the height of the input tensor,
  160. in_d is the depth of the input tensor.
  161. and the resizing only applies on the three dimensions(depth, height and width).
  162. Supporting resample methods:
  163. - 'linear' : Linear interpolation
  164. - 'bilinear' : Bilinear interpolation
  165. - 'trilinear' : Trilinear interpolation
  166. - 'nearest' : Nearest neighbor interpolation
  167. - 'bicubic' : Bicubic interpolation
  168. - 'area': Area interpolation
  169. Linear interpolation is the method of using a line connecting two known quantities
  170. to determine the value of an unknown quantity between the two known quantities.
  171. Nearest neighbor interpolation is to perform nearest neighbor interpolation
  172. in both the 3rd dimension(in height direction) and the 4th dimension(in width
  173. direction) on input tensor.
  174. Bilinear interpolation is an extension of linear interpolation for
  175. interpolating functions of two variables (e.g. H-direction and
  176. W-direction in this op) on a rectilinear 2D grid. The key idea is
  177. to perform linear interpolation first in one direction, and then
  178. again in the other direction.
  179. Trilinear interpolation is an extension of linear interpolation for
  180. interpolating functions of three variables (e.g. D-direction,
  181. H-direction and W-direction in this op) on a rectilinear 3D grid.
  182. The linear interpolation is performed on three directions.
  183. align_corners and align_mode are optional parameters,the calculation method
  184. of interpolation can be selected by them.
  185. Bicubic interpolation is an extension of cubic interpolation for interpolating
  186. data points on a two-dimensional regular grid. The interpolated surface is
  187. smoother than corresponding surfaces obtained by bilinear interpolation or
  188. nearest-neighbor interpolation.
  189. Area interpolation is to perform area interpolation
  190. in both the 3rd dimension(in height direction) , the 4th dimension(in width
  191. direction) and the 5th dimension(in depth direction) on input tensor. Set to
  192. area will directly call `paddle.nn.functional.adaptive_avg_pool1d` or
  193. `paddle.nn.functional.adaptive_avg_pool2d` or `paddle.nn.functional.adaptive_avg_pool3d`.
  194. Example:
  195. .. code-block:: text
  196. # For scale_factor:
  197. if align_corners = True && out_size > 1 :
  198. scale_factor = (in_size-1.0)/(out_size-1.0)
  199. else:
  200. scale_factor = float(in_size/out_size)
  201. # Linear interpolation:
  202. if:
  203. align_corners = False , align_mode = 0
  204. input : (N,C,W_in)
  205. output: (N,C,W_out) where:
  206. W_out = (W_{in}+0.5) * scale_{factor} - 0.5
  207. else:
  208. input : (N,C,W_in)
  209. output: (N,C,W_out) where:
  210. W_out = W_{in} * scale_{factor}
  211. # Nearest neighbor interpolation:
  212. align_corners = False
  213. input : (N,C,H_in,W_in)
  214. output: (N,C,H_out,W_out) where:
  215. H_out = floor (H_{in} * scale_{factor})
  216. W_out = floor (W_{in} * scale_{factor})
  217. # Bilinear interpolation:
  218. if:
  219. align_corners = False , align_mode = 0
  220. input : (N,C,H_in,W_in)
  221. output: (N,C,H_out,W_out) where:
  222. H_out = (H_{in}+0.5) * scale_{factor} - 0.5
  223. W_out = (W_{in}+0.5) * scale_{factor} - 0.5
  224. else:
  225. input : (N,C,H_in,W_in)
  226. output: (N,C,H_out,W_out) where:
  227. H_out = H_{in} * scale_{factor}
  228. W_out = W_{in} * scale_{factor}
  229. # Bicubic interpolation:
  230. if:
  231. align_corners = False
  232. input : (N,C,H_in,W_in)
  233. output: (N,C,H_out,W_out) where:
  234. H_out = (H_{in}+0.5) * scale_{factor} - 0.5
  235. W_out = (W_{in}+0.5) * scale_{factor} - 0.5
  236. else:
  237. input : (N,C,H_in,W_in)
  238. output: (N,C,H_out,W_out) where:
  239. H_out = H_{in} * scale_{factor}
  240. W_out = W_{in} * scale_{factor}
  241. # Trilinear interpolation:
  242. if:
  243. align_corners = False , align_mode = 0
  244. input : (N,C,D_in,H_in,W_in)
  245. output: (N,C,D_out,H_out,W_out) where:
  246. D_out = (D_{in}+0.5) * scale_{factor} - 0.5
  247. H_out = (H_{in}+0.5) * scale_{factor} - 0.5
  248. W_out = (W_{in}+0.5) * scale_{factor} - 0.5
  249. else:
  250. input : (N,C,D_in,H_in,W_in)
  251. output: (N,C,D_out,H_out,W_out) where:
  252. D_out = D_{in} * scale_{factor}
  253. H_out = H_{in} * scale_{factor}
  254. W_out = W_{in} * scale_{factor}
  255. For details of linear interpolation, please refer to Wikipedia:
  256. https://en.wikipedia.org/wiki/Linear_interpolation.
  257. For details of nearest neighbor interpolation, please refer to Wikipedia:
  258. https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation.
  259. For details of bilinear interpolation, please refer to Wikipedia:
  260. https://en.wikipedia.org/wiki/Bilinear_interpolation.
  261. For details of trilinear interpolation, please refer to Wikipedia:
  262. https://en.wikipedia.org/wiki/Trilinear_interpolation.
  263. For details of bicubic interpolation, please refer to Wikipedia:
  264. https://en.wikipedia.org/wiki/Bicubic_interpolation
  265. Parameters:
  266. x (Tensor): 3-D, 4-D or 5-D Tensor, its data type is float32, float64, or uint8, its data format is
  267. specified by :attr:`data_format`. If :attr:`data_format` is not provided, the data format will
  268. be presumed according to its dimension. See details in :attr:`data_format`.
  269. size (list|tuple|Tensor|None): Output shape of image resize
  270. layer, the shape is (out_w, ) when input is a 3-D Tensor, the shape is (out_h, out_w)
  271. when input is a 4-D Tensor and is (out_d, out_h, out_w) when input is a 5-D Tensor.
  272. Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1] or [].
  273. If a Tensor, its dimensions size should be a 1.
  274. scale_factor (float|Tensor|list|tuple|None): The multiplier for the input height or width. At
  275. least one of :attr:`size` or :attr:`scale_factor` must be set.
  276. And :attr:`size` has a higher priority than :attr:`scale_factor`.Has to match input size if it is either a list or a tuple or a Tensor.If a list/tuple, each element can be an integer or a Tensor of shape: [1] or [].
  277. Default: None.
  278. mode (str): The resample method. It supports 'linear', 'area', 'nearest', 'bilinear',
  279. 'bicubic' and 'trilinear' currently. Default: 'nearest'
  280. align_corners(bool) : An optional bool, If True, the centers of the 4 corner pixels of the
  281. input and output tensors are aligned, preserving the values at the
  282. corner pixels.This only has an effect when 'linear', 'bilinear', 'bicubic' or 'trilinear'.
  283. Default: False
  284. align_mode(int) : An optional for linear/bilinear/trilinear interpolation. Refer to the formula in the example above,
  285. it can be \'0\' for src_idx = scale_factor*(dst_index+0.5)-0.5 , can be \'1\' for
  286. src_idx = scale_factor*dst_index.
  287. data_format (str, optional): Specify the data format of the input, and the data format of
  288. the output will be consistent with that of the input. An optional string from:`"NCW"`,
  289. `"NWC"`, `"NCHW"`, `"NHWC"`, `"NCDHW"`, `"NDHWC"`. The default value is None.
  290. When :attr:`data_format` is not specified, it will be automatically inferred from the
  291. input dimension of :attr:`x`. When :attr:`x` is a 3-D Tensor, :attr:`data_format` will be
  292. set to `"NCW"`; When :attr:`x` is a 4-D Tensor, :attr:`data_format` will be set to
  293. `"NCHW"`; When :attr:`x` is a 5-D Tensor, :attr:`data_format` will be set to `"NCDHW"`.
  294. When it is `"NCHW"`, the data should be stored in the order of:
  295. `[batch_size, input_channels, input_height, input_width]`. When it is `"NCDHW"`, the
  296. data should be stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`.
  297. name(str, optional): The default value is None.
  298. Normally there is no need for user to set this property.
  299. For more information, please refer to :ref:`api_guide_Name`
  300. Returns:
  301. A 3-D, 4-D or 5-D Tensor, with the same data format of the input :attr:`x`.
  302. Examples:
  303. .. code-block:: python
  304. >>> import paddle
  305. >>> import paddle.nn.functional as F
  306. >>> input_data = paddle.randn(shape=(2,3,6,10)).astype(paddle.float32)
  307. >>> output_1 = F.interpolate(x=input_data, size=[12,12])
  308. >>> print(output_1.shape)
  309. [2, 3, 12, 12]
  310. >>> # given scale
  311. >>> output_2 = F.interpolate(x=input_data, scale_factor=[2,1])
  312. >>> print(output_2.shape)
  313. [2, 3, 12, 10]
  314. >>> # bilinear interp
  315. >>> output_3 = F.interpolate(x=input_data, scale_factor=[2,1], mode="bilinear")
  316. >>> print(output_2.shape)
  317. [2, 3, 12, 10]
  318. """
  319. if data_format is None:
  320. dim_size = len(x.shape)
  321. if dim_size == 3:
  322. data_format = 'NCW'
  323. elif dim_size == 4:
  324. data_format = 'NCHW'
  325. elif dim_size == 5:
  326. data_format = 'NCDHW'
  327. else:
  328. raise ValueError(
  329. f"The dimension of the input tensor should only be 3-D, 4-D or 5-D, but the received dimension is {dim_size}."
  330. )
  331. data_format = data_format.upper()
  332. resample = mode.upper()
  333. resample_type = mode.lower()
  334. resample_methods = [
  335. 'LINEAR',
  336. 'BILINEAR',
  337. 'TRILINEAR',
  338. 'NEAREST',
  339. 'BICUBIC',
  340. 'AREA',
  341. ]
  342. if resample not in resample_methods:
  343. raise ValueError(
  344. "The 'resample' of image_resize can only be 'area', 'linear', 'bilinear', 'trilinear', "
  345. " 'bicubic' or 'nearest' currently."
  346. )
  347. if resample in ['LINEAR'] and len(x.shape) != 3:
  348. raise ValueError("'linear' only support 3-D tensor.")
  349. if resample in ['NEAREST'] and len(x.shape) != 4 and len(x.shape) != 5:
  350. raise ValueError("'NEAREST' only support 4-D or 5-D tensor.")
  351. if resample in ['BILINEAR', 'BICUBIC'] and len(x.shape) != 4:
  352. raise ValueError("'bilinear' and 'bicubic' only support 4-D tensor.")
  353. if resample == 'TRILINEAR' and len(x.shape) != 5:
  354. raise ValueError("'trilinear'only support 5-D tensor.")
  355. if size is None and scale_factor is None:
  356. raise ValueError("One of size and scale_factor must not be None.")
  357. if isinstance(size, (tuple, list)) and (len(size) != x.ndim - 2):
  358. raise ValueError(
  359. 'The x and size should satisfy rank(x) - 2 == len(size).'
  360. )
  361. if isinstance(size, (Variable, paddle.pir.Value)):
  362. size = size.cast("int32") # static mode only support int32
  363. if size.ndim != 1:
  364. raise ValueError(
  365. f"If size is a tensor, it's rank must be 1, but received {size.ndim}."
  366. )
  367. if size.shape[0] != x.ndim - 2:
  368. raise ValueError(
  369. 'The x and size should satisfy rank(x) - 2 == size.shape[0].'
  370. )
  371. if not isinstance(align_corners, bool):
  372. raise TypeError("Attr align_corners should be a bool value")
  373. if align_mode != 0 and align_mode != 1:
  374. raise ValueError("align_mode can only be 0 or 1")
  375. if align_corners != 0 and resample == 'NEAREST':
  376. raise ValueError(
  377. "align_corners option can only be set with the interpolating modes: linear | bilinear | bicubic | trilinear"
  378. )
  379. if resample == 'AREA':
  380. if isinstance(size, (list, tuple, Variable, paddle.pir.Value)):
  381. if len(size) == 0:
  382. raise ValueError("output size can not be empty")
  383. if size is None:
  384. raise ValueError("output size can not be None in AREA mode")
  385. if len(x.shape) == 3:
  386. return paddle.nn.functional.adaptive_avg_pool1d(x, size)
  387. elif len(x.shape) == 4:
  388. print("size :", size)
  389. return paddle.nn.functional.adaptive_avg_pool2d(x, size)
  390. elif len(x.shape) == 5:
  391. return paddle.nn.functional.adaptive_avg_pool3d(x, size)
  392. helper = LayerHelper(f'{resample_type}_interp_v2', **locals())
  393. if len(x.shape) == 3 and data_format not in ['NCW', 'NWC']:
  394. raise ValueError(
  395. "Got wrong value for param `data_format`: "
  396. + data_format
  397. + " received but only `NCW` or `NWC` supported for 3-D input."
  398. )
  399. elif len(x.shape) == 4 and data_format not in ['NCHW', 'NHWC']:
  400. raise ValueError(
  401. "Got wrong value for param `data_format`: "
  402. + data_format
  403. + " received but only `NCHW` or `NHWC` supported for 4-D input."
  404. )
  405. elif len(x.shape) == 5 and data_format not in ['NCDHW', 'NDHWC']:
  406. raise ValueError(
  407. "Got wrong value for param `data_format`: "
  408. + data_format
  409. + " received but only `NCDHW` or `NDHWC` supported for 5-D input."
  410. )
  411. def _is_list_or_tuple_(data):
  412. return isinstance(data, (list, tuple))
  413. if data_format == 'NCHW' or data_format == 'NCDHW' or data_format == 'NCW':
  414. data_layout = 'NCHW'
  415. if data_format == 'NHWC' or data_format == 'NDHWC' or data_format == 'NWC':
  416. data_layout = 'NHWC'
  417. if resample == 'NEAREST':
  418. align_corners = False
  419. inputs = {"X": x}
  420. attrs = {
  421. "out_d": -1,
  422. "out_h": -1,
  423. "out_w": -1,
  424. "interp_method": resample_type,
  425. "align_corners": align_corners,
  426. "align_mode": align_mode,
  427. "data_layout": data_layout,
  428. }
  429. out_shape = size
  430. scale = scale_factor
  431. if out_shape is not None and scale is not None:
  432. raise ValueError("Only one of size or scale_factor should be defined.")
  433. if out_shape is not None:
  434. if (
  435. isinstance(out_shape, (Variable, paddle.pir.Value))
  436. and not in_dynamic_mode()
  437. ):
  438. out_shape.stop_gradient = True
  439. inputs['OutSize'] = out_shape
  440. else:
  441. if in_dynamic_mode():
  442. if isinstance(out_shape, Variable):
  443. out_shape = list(out_shape.numpy(False))
  444. else:
  445. out_shape = list(out_shape)
  446. for i, dim in enumerate(out_shape):
  447. if isinstance(dim, Variable):
  448. out_shape[i] = dim.item()
  449. if not (_is_list_or_tuple_(out_shape)):
  450. raise TypeError("size should be a list or tuple or Variable.")
  451. # Validate the shape
  452. contain_var = False
  453. for dim_idx, dim_size in enumerate(out_shape):
  454. if isinstance(dim_size, (Variable, paddle.pir.Value)):
  455. contain_var = True
  456. continue
  457. assert (
  458. dim_size > 0
  459. ), "Each dimension size given in out_shape must be greater than 0."
  460. if contain_var:
  461. new_size_tensor = []
  462. size_list = []
  463. for dim in out_shape:
  464. if isinstance(dim, (Variable, paddle.pir.Value)):
  465. dim.stop_gradient = True
  466. new_size_tensor.append(dim)
  467. size_list.append(-1)
  468. else:
  469. assert isinstance(dim, int)
  470. if in_pir_mode():
  471. temp_out = paddle.tensor.fill_constant(
  472. [1], 'int32', dim, force_cpu=True
  473. )
  474. else:
  475. temp_out = (
  476. helper.create_variable_for_type_inference(
  477. 'int32'
  478. )
  479. )
  480. paddle.tensor.fill_constant(
  481. [1], 'int32', dim, force_cpu=True, out=temp_out
  482. )
  483. new_size_tensor.append(temp_out)
  484. size_list.append(dim)
  485. inputs['SizeTensor'] = new_size_tensor
  486. if len(x.shape) == 3:
  487. if len(out_shape) != 1:
  488. raise ValueError(
  489. "size length should be 2 for input 3-D tensor"
  490. )
  491. if contain_var:
  492. attrs['out_w'] = size_list[0]
  493. else:
  494. out_shape = list(map(int, out_shape))
  495. attrs['out_w'] = out_shape[0]
  496. if len(x.shape) == 4:
  497. if len(out_shape) != 2:
  498. raise ValueError(
  499. "size length should be 2 for " "input 4-D tensor."
  500. )
  501. if contain_var:
  502. attrs['out_h'] = size_list[0]
  503. attrs['out_w'] = size_list[1]
  504. else:
  505. out_shape = list(map(int, out_shape))
  506. attrs['out_h'] = out_shape[0]
  507. attrs['out_w'] = out_shape[1]
  508. if len(x.shape) == 5:
  509. if len(out_shape) != 3:
  510. raise ValueError(
  511. "size length should be 3 for " "input 5-D tensor."
  512. )
  513. if contain_var:
  514. attrs['out_d'] = size_list[0]
  515. attrs['out_h'] = size_list[1]
  516. attrs['out_w'] = size_list[2]
  517. else:
  518. out_shape = list(map(int, out_shape))
  519. attrs['out_d'] = out_shape[0]
  520. attrs['out_h'] = out_shape[1]
  521. attrs['out_w'] = out_shape[2]
  522. else:
  523. if in_dynamic_mode() and isinstance(scale, Variable):
  524. if scale.shape == []:
  525. scale = float(scale)
  526. else:
  527. scale = list(scale.numpy())
  528. if isinstance(scale, (Variable, paddle.pir.Value)):
  529. scale.stop_gradient = True
  530. inputs["Scale"] = scale
  531. elif isinstance(scale, (float, int, numpy.ndarray)):
  532. if scale <= 0:
  533. raise ValueError("Attr(scale) should be greater than zero.")
  534. scale_list = []
  535. for i in range(len(x.shape) - 2):
  536. scale_list.append(scale)
  537. attrs['scale'] = list(map(float, scale_list))
  538. elif isinstance(scale, (list, tuple)):
  539. if len(scale) != len(x.shape) - 2:
  540. raise ValueError(
  541. f"scale_shape length should be {len(x.shape) - 2} for "
  542. f"input {len(x.shape)}-D tensor."
  543. )
  544. for value in scale:
  545. if value <= 0:
  546. raise ValueError("Attr(scale) should be greater than zero.")
  547. attrs['scale'] = list(map(float, scale))
  548. else:
  549. raise TypeError(
  550. "Attr(scale)'s type should be float, int, list, tuple, or Tensor."
  551. )
  552. if in_dynamic_or_pir_mode():
  553. attr_list = []
  554. for k, v in attrs.items():
  555. attr_list.append(k)
  556. attr_list.append(v)
  557. dy_attr = tuple(attr_list)
  558. if resample_type == "linear":
  559. out = _C_ops.linear_interp(
  560. x,
  561. inputs['OutSize'] if 'OutSize' in inputs else None,
  562. inputs['SizeTensor'] if 'SizeTensor' in inputs else None,
  563. inputs['Scale'] if 'Scale' in inputs else None,
  564. attrs['data_layout'],
  565. attrs['out_d'],
  566. attrs['out_h'],
  567. attrs['out_w'],
  568. attrs['scale'] if 'scale' in attrs else [],
  569. attrs['interp_method'],
  570. attrs['align_corners'],
  571. attrs['align_mode'],
  572. )
  573. elif resample_type == "bilinear":
  574. out = _C_ops.bilinear_interp(
  575. x,
  576. inputs['OutSize'] if 'OutSize' in inputs else None,
  577. inputs['SizeTensor'] if 'SizeTensor' in inputs else None,
  578. inputs['Scale'] if 'Scale' in inputs else None,
  579. attrs['data_layout'],
  580. attrs['out_d'],
  581. attrs['out_h'],
  582. attrs['out_w'],
  583. attrs['scale'] if 'scale' in attrs else [],
  584. attrs['interp_method'],
  585. attrs['align_corners'],
  586. attrs['align_mode'],
  587. )
  588. elif resample_type == "trilinear":
  589. out = _C_ops.trilinear_interp(
  590. x,
  591. inputs['OutSize'] if 'OutSize' in inputs else None,
  592. inputs['SizeTensor'] if 'SizeTensor' in inputs else None,
  593. inputs['Scale'] if 'Scale' in inputs else None,
  594. attrs['data_layout'],
  595. attrs['out_d'],
  596. attrs['out_h'],
  597. attrs['out_w'],
  598. attrs['scale'] if 'scale' in attrs else [],
  599. attrs['interp_method'],
  600. attrs['align_corners'],
  601. attrs['align_mode'],
  602. )
  603. elif resample_type == "nearest":
  604. out = _C_ops.nearest_interp(
  605. x,
  606. inputs['OutSize'] if 'OutSize' in inputs else None,
  607. inputs['SizeTensor'] if 'SizeTensor' in inputs else None,
  608. inputs['Scale'] if 'Scale' in inputs else None,
  609. attrs['data_layout'],
  610. attrs['out_d'],
  611. attrs['out_h'],
  612. attrs['out_w'],
  613. attrs['scale'] if 'scale' in attrs else [],
  614. attrs['interp_method'],
  615. attrs['align_corners'],
  616. attrs['align_mode'],
  617. )
  618. elif resample_type == "bicubic":
  619. out = _C_ops.bicubic_interp(
  620. x,
  621. inputs['OutSize'] if 'OutSize' in inputs else None,
  622. inputs['SizeTensor'] if 'SizeTensor' in inputs else None,
  623. inputs['Scale'] if 'Scale' in inputs else None,
  624. attrs['data_layout'],
  625. attrs['out_d'],
  626. attrs['out_h'],
  627. attrs['out_w'],
  628. attrs['scale'] if 'scale' in attrs else [],
  629. attrs['interp_method'],
  630. attrs['align_corners'],
  631. attrs['align_mode'],
  632. )
  633. return out
  634. dtype = helper.input_dtype(input_param_name='x')
  635. out = helper.create_variable_for_type_inference(dtype)
  636. helper.append_op(
  637. type=f'{resample_type}_interp_v2',
  638. inputs=inputs,
  639. outputs={"Out": out},
  640. attrs=attrs,
  641. )
  642. return out
  643. def upsample(
  644. x,
  645. size=None,
  646. scale_factor=None,
  647. mode='nearest',
  648. align_corners=False,
  649. align_mode=0,
  650. data_format=None,
  651. name=None,
  652. ):
  653. """
  654. This API resizes a batch of images.
  655. The input must be a 3-D Tensor of the shape (num_batches, channels, in_w)
  656. or (num_batches, in_w, channels), or 4-D (num_batches, channels, in_h, in_w) or
  657. (num_batches, in_h, in_w, channels), or a 5-D Tensor of the shape
  658. (num_batches, channels, in_d, in_h, in_w) or (num_batches, in_d, in_h, in_w, channels),
  659. Where in_w is width of the input tensor, in_h is the height of the input tensor,
  660. in_d is the depth of the input tensor.
  661. and the resizing only applies on the three dimensions(depth, height and width).
  662. Supporting resample methods:
  663. - 'linear' : Linear interpolation
  664. - 'bilinear' : Bilinear interpolation
  665. - 'trilinear' : Trilinear interpolation
  666. - 'nearest' : Nearest neighbor interpolation
  667. - 'bicubic' : Bicubic interpolation
  668. Linear interpolation is the method of using a line connecting two known quantities
  669. to determine the value of an unknown quantity between the two known quantities.
  670. Nearest neighbor interpolation is to perform nearest neighbor interpolation
  671. in both the 3rd dimension(in height direction) and the 4th dimension(in width
  672. direction) on input tensor.
  673. Bilinear interpolation is an extension of linear interpolation for
  674. interpolating functions of two variables (e.g. H-direction and
  675. W-direction in this op) on a rectilinear 2D grid. The key idea is
  676. to perform linear interpolation first in one direction, and then
  677. again in the other direction.
  678. Bicubic interpolation is an extension of cubic interpolation for interpolating
  679. data points on a two-dimensional regular grid. The interpolated surface is
  680. smoother than corresponding surfaces obtained by bilinear interpolation or
  681. nearest-neighbor interpolation.
  682. Trilinear interpolation is an extension of linear interpolation for
  683. interpolating functions of three variables (e.g. D-direction,
  684. H-direction and W-direction in this op) on a rectilinear 3D grid.
  685. The linear interpolation is performed on three directions.
  686. align_corners and align_mode are optional parameters,the calculation method
  687. of interpolation can be selected by them.
  688. Area interpolation is to perform area interpolation
  689. in both the 3rd dimension(in height direction) , the 4th dimension(in width
  690. direction) and the 5th dimension(in depth direction) on input tensor. Set to
  691. area will directly call `paddle.nn.functional.adaptive_avg_pool1d` or
  692. `paddle.nn.functional.adaptive_avg_pool2d` or `paddle.nn.functional.adaptive_avg_pool3d`.
  693. Example:
  694. .. code-block:: text
  695. For scale_factor:
  696. if align_corners = True && out_size > 1 :
  697. scale_factor = (in_size-1.0)/(out_size-1.0)
  698. else:
  699. scale_factor = float(in_size/out_size)
  700. Linear interpolation:
  701. if:
  702. align_corners = False , align_mode = 0
  703. input : (N,C,W_in)
  704. output: (N,C,W_out) where:
  705. W_out = (W_{in}+0.5) * scale_{factor} - 0.5
  706. else:
  707. input : (N,C,W_in)
  708. output: (N,C,W_out) where:
  709. W_out = W_{in} * scale_{factor}
  710. Nearest neighbor interpolation:
  711. if:
  712. align_corners = False
  713. input : (N,C,H_in,W_in)
  714. output: (N,C,H_out,W_out) where:
  715. H_out = floor (H_{in} * scale_{factor})
  716. W_out = floor (W_{in} * scale_{factor})
  717. else:
  718. align_corners = True
  719. input : (N,C,H_in,W_in)
  720. output: (N,C,H_out,W_out) where:
  721. H_out = round(H_{in} * scale_{factor})
  722. W_out = round(W_{in} * scale_{factor})
  723. Bilinear interpolation:
  724. if:
  725. align_corners = False , align_mode = 0
  726. input : (N,C,H_in,W_in)
  727. output: (N,C,H_out,W_out) where:
  728. H_out = (H_{in}+0.5) * scale_{factor} - 0.5
  729. W_out = (W_{in}+0.5) * scale_{factor} - 0.5
  730. else:
  731. input : (N,C,H_in,W_in)
  732. output: (N,C,H_out,W_out) where:
  733. H_out = H_{in} * scale_{factor}
  734. W_out = W_{in} * scale_{factor}
  735. Bicubic interpolation:
  736. if:
  737. align_corners = False
  738. input : (N,C,H_in,W_in)
  739. output: (N,C,H_out,W_out) where:
  740. H_out = (H_{in}+0.5) * scale_{factor} - 0.5
  741. W_out = (W_{in}+0.5) * scale_{factor} - 0.5
  742. else:
  743. input : (N,C,H_in,W_in)
  744. output: (N,C,H_out,W_out) where:
  745. H_out = H_{in} * scale_{factor}
  746. W_out = W_{in} * scale_{factor}
  747. Trilinear interpolation:
  748. if:
  749. align_corners = False , align_mode = 0
  750. input : (N,C,D_in,H_in,W_in)
  751. output: (N,C,D_out,H_out,W_out) where:
  752. D_out = (D_{in}+0.5) * scale_{factor} - 0.5
  753. H_out = (H_{in}+0.5) * scale_{factor} - 0.5
  754. W_out = (W_{in}+0.5) * scale_{factor} - 0.5
  755. else:
  756. input : (N,C,D_in,H_in,W_in)
  757. output: (N,C,D_out,H_out,W_out) where:
  758. D_out = D_{in} * scale_{factor}
  759. H_out = H_{in} * scale_{factor}
  760. W_out = W_{in} * scale_{factor}
  761. For details of linear interpolation, please refer to Wikipedia:
  762. https://en.wikipedia.org/wiki/Linear_interpolation.
  763. For details of nearest neighbor interpolation, please refer to Wikipedia:
  764. https://en.wikipedia.org/wiki/Nearest-neighbor_interpolation.
  765. For details of bilinear interpolation, please refer to Wikipedia:
  766. https://en.wikipedia.org/wiki/Bilinear_interpolation.
  767. For details of bicubic interpolation, please refer to Wikipedia:
  768. https://en.wikipedia.org/wiki/Bicubic_interpolation
  769. For details of trilinear interpolation, please refer to Wikipedia:
  770. https://en.wikipedia.org/wiki/Trilinear_interpolation.
  771. Parameters:
  772. x (Tensor): 3-D, 4-D or 5-D Tensor, its data type is float32, float64, or uint8, its data format is
  773. specified by :attr:`data_format`. If :attr:`data_format` is not provided, the data format will
  774. be presumed according to its dimension. See details in :attr:`data_format`.
  775. size (list|tuple|Tensor|None, optional): Output shape of image resize
  776. layer, the shape is (out_w, ) when input is a 3-D Tensor, the shape is (out_h, out_w)
  777. when input is a 4-D Tensor and is (out_d, out_h, out_w) when input is a 5-D Tensor.
  778. Default: None. If a list/tuple, each element can be an integer or a Tensor of shape: [1] or [].
  779. If a Tensor , its dimensions size should be a 1.
  780. scale_factor (float|Tensor|list|tuple|None, optional): The multiplier for the input height or width. At
  781. least one of :attr:`size` or :attr:`scale_factor` must be set.
  782. And :attr:`size` has a higher priority than :attr:`scale_factor`.Has to match input size if
  783. it is either a list or a tuple or a Tensor. If a list/tuple, each element can be an integer or a Tensor of shape: [1] or [].
  784. Default: None.
  785. mode (str, optional): The resample method. It supports 'linear', 'nearest', 'bilinear',
  786. 'bicubic' and 'trilinear' currently. Default: 'nearest'
  787. align_corners(bool, optional) : An optional bool, If True, the centers of the 4 corner pixels of the
  788. input and output tensors are aligned, preserving the values at the
  789. corner pixels.
  790. Default: False
  791. align_mode(int, optional) : An optional for linear/bilinear/trilinear interpolation. Refer to the formula in the example above,
  792. it can be \'0\' for src_idx = scale_factor*(dst_index+0.5)-0.5 , can be \'1\' for
  793. src_idx = scale_factor*dst_index.
  794. data_format (str, optional): Specify the data format of the input, and the data format of
  795. the output will be consistent with that of the input. An optional string from:`"NCW"`,
  796. `"NWC"`, `"NCHW"`, `"NHWC"`, `"NCDHW"`, `"NDHWC"`. The default value is None.
  797. When :attr:`data_format` is not specified, it will be automatically inferred from the
  798. input dimension of :attr:`x`. When :attr:`x` is a 3-D Tensor, :attr:`data_format` will be
  799. set to `"NCW"`; When :attr:`x` is a 4-D Tensor, :attr:`data_format` will be set to
  800. `"NCHW"`; When :attr:`x` is a 5-D Tensor, :attr:`data_format` will be set to `"NCDHW"`.
  801. When it is `"NCHW"`, the data should be stored in the order of:
  802. `[batch_size, input_channels, input_height, input_width]`. When it is `"NCDHW"`, the
  803. data should be stored in the order of: `[batch_size, input_channels, input_depth, input_height, input_width]`.
  804. name(str, optional): The default value is None.
  805. Normally there is no need for user to set this property.
  806. For more information, please refer to :ref:`api_guide_Name`
  807. Returns:
  808. A 3-D, 4-D or 5-D Tensor, with the same data format of the input :attr:`x`.
  809. Examples:
  810. .. code-block:: python
  811. >>> import paddle
  812. >>> import paddle.nn as nn
  813. >>> input_data = paddle.randn(shape=(2,3,6,10)).astype(paddle.float32)
  814. >>> upsample_out = paddle.nn.Upsample(size=[12,12])
  815. >>> output = upsample_out(x=input_data)
  816. >>> print(output.shape)
  817. [2, 3, 12, 12]
  818. """
  819. return interpolate(
  820. x, size, scale_factor, mode, align_corners, align_mode, data_format
  821. )
  822. def bilinear(x1, x2, weight, bias=None, name=None):
  823. """
  824. This layer performs bilinear on two inputs.
  825. See :ref:`api_paddle_nn_Bilinear` for details and output shape.
  826. Parameters:
  827. x1 (Tensor): the first input tensor, it's data type should be float32, float64.
  828. x2 (Tensor): the second input tensor, it's data type should be float32, float64.
  829. weight (Parameter): The learnable weights of this layer, shape is [out_features, in1_features, in2_features].
  830. bias (Parameter, optional): The learnable bias(Bias) of this layer, shape is [1, out_features]. If it is set to None, no bias will be added to the output units. The default value is None.
  831. name (str, optional): The default value is None. Normally there is no need for user
  832. to set this property. For more information, please refer to :ref:`api_guide_Name`. Default: None.
  833. Returns:
  834. Tensor: A 2-D Tensor of shape [batch_size, out_features].
  835. Examples:
  836. .. code-block:: python
  837. >>> import paddle
  838. >>> import paddle.nn.functional as F
  839. >>> x1 = paddle.randn((5, 5)).astype(paddle.float32)
  840. >>> x2 = paddle.randn((5, 4)).astype(paddle.float32)
  841. >>> w = paddle.randn((1000, 5, 4)).astype(paddle.float32)
  842. >>> b = paddle.randn((1, 1000)).astype(paddle.float32)
  843. >>> result = F.bilinear(x1, x2, w, b)
  844. >>> print(result.shape)
  845. [5, 1000]
  846. """
  847. if in_dynamic_or_pir_mode():
  848. return _C_ops.bilinear(x1, x2, weight, bias)
  849. else:
  850. check_variable_and_dtype(x1, 'x1', ['float32', 'float64'], 'bilinear')
  851. check_variable_and_dtype(x2, 'x2', ['float32', 'float64'], 'bilinear')
  852. inputs = {"X": x1, "Y": x2, "Weight": weight}
  853. if bias is not None:
  854. inputs["Bias"] = bias
  855. helper = LayerHelper("bilinear", **locals())
  856. out = helper.create_variable_for_type_inference(dtype=x1.dtype)
  857. helper.append_op(
  858. type="bilinear_tensor_product", inputs=inputs, outputs={"Out": out}
  859. )
  860. return out
  861. def dropout(
  862. x, p=0.5, axis=None, training=True, mode="upscale_in_train", name=None
  863. ):
  864. r"""
  865. Dropout is a regularization technique for reducing overfitting by preventing
  866. neuron co-adaption during training. The dropout operator randomly sets the
  867. outputs of some units to zero, while upscale others according to the given
  868. dropout probability.
  869. Args:
  870. x (Tensor): The input tensor. The data type is float16, float32 or float64.
  871. p (float|int, optional): Probability of setting units to zero. Default: 0.5.
  872. axis (int|list|tuple, optional): The axis along which the dropout is performed. Default: None.
  873. training (bool, optional): A flag indicating whether it is in train phrase or not. Default: True.
  874. mode(str, optional): ['upscale_in_train'(default) | 'downscale_in_infer'].
  875. 1. upscale_in_train (default), upscale the output at training time
  876. - train: :math:`out = input \times \frac{mask}{(1.0 - dropout\_prob)}`
  877. - inference: :math:`out = input`
  878. 2. downscale_in_infer, downscale the output at inference
  879. - train: :math:`out = input \times mask`
  880. - inference: :math:`out = input \times (1.0 - dropout\_prob)`
  881. name (str, optional): Name for the operation, Default: None. For more information, please refer to :ref:`api_guide_Name`.
  882. Returns:
  883. A Tensor representing the dropout, has same shape and data type as `x` .
  884. Examples:
  885. We use ``p=0.5`` in the following description for simplicity.
  886. 1. When ``axis=None`` , this is commonly used dropout, which dropout each element of x randomly.
  887. .. code-block:: text
  888. Let's see a simple case when x is a 2d tensor with shape 2*3:
  889. [[1 2 3]
  890. [4 5 6]]
  891. we generate mask with the same shape as x, which is 2*3. The value of mask is
  892. sampled from a Bernoulli distribution randomly. For example, we may get such mask:
  893. [[0 1 0]
  894. [1 0 1]]
  895. So the output is obtained from elementwise multiply of x and mask:
  896. [[0 2 0]
  897. [4 0 6]]
  898. Using default setting, i.e. ``mode='upscale_in_train'`` ,
  899. if in training phase, the final upscale output is:
  900. [[0 4 0 ]
  901. [8 0 12]]
  902. if in test phase, the output is the same as input:
  903. [[1 2 3]
  904. [4 5 6]]
  905. we can also set ``mode='downscale_in_infer'`` , then
  906. if in training phase, the final output is:
  907. [[0 2 0]
  908. [4 0 6]]
  909. if in test phase, the scale output is:
  910. [[0.5 1. 1.5]
  911. [2. 2.5 3. ]]
  912. 2. When ``axis!=None`` , this is useful for dropping whole channels from an image or sequence.
  913. .. code-block:: text
  914. Let's see the simple case when x is a 2d tensor with shape 2*3 again:
  915. [[1 2 3]
  916. [4 5 6]]
  917. (1) If ``axis=0`` , this means the dropout is only performed in axis `0` .
  918. we generate mask with the shape 2*1. Only in axis `0` the value is randomly selected.
  919. For example, we may get such mask:
  920. [[1]
  921. [0]]
  922. The output is obtained from elementwise multiply of x and mask. Doing that the mask will be
  923. broadcast from 2*1 to 2*3:
  924. [[1 1 1]
  925. [0 0 0]]
  926. and the result after elementwise multiply is:
  927. [[1 2 3]
  928. [0 0 0]]
  929. then we can do upscale or downscale according to the setting of other arguments.
  930. (2) If ``axis=1`` , this means the dropout is only performed in axis `1` .
  931. we generate mask with the shape 1*3. Only in axis `1` the value is randomly selected.
  932. For example, we may get such mask:
  933. [[1 0 1]]
  934. Doing elementwise multiply the mask will be broadcast from 1*3 to 2*3:
  935. [[1 0 1]
  936. [1 0 1]]
  937. and the result after elementwise multiply is:
  938. [[1 0 3]
  939. [4 0 6]]
  940. (3) What about ``axis=[0, 1]`` ? This means the dropout is performed in all axes of x,
  941. which is the same case as default setting ``axis=None`` .
  942. (4) You may note that logically `axis=None` means the dropout is performed in none axis of x,
  943. We generate mask with the shape 1*1. Whole input is randomly selected or dropped.
  944. For example, we may get such mask:
  945. [[0]]
  946. Doing elementwise multiply the mask will be broadcast from 1*1 to 2*3:
  947. [[0 0 0]
  948. [0 0 0]]
  949. and the result after elementwise multiply is:
  950. [[0 0 0]
  951. [0 0 0]]
  952. Actually this is not what we want because all elements may set to zero~
  953. When x is a 4d tensor with shape `NCHW`, where `N` is batch size, `C` is the number of channels, H and W are the height and width of the feature, we can set ``axis=[0,1]`` and the dropout will be performed in channel `N` and `C`, `H` and `W` is tied, i.e. paddle.nn.dropout(x, p, axis=[0,1]) . Please refer to ``paddle.nn.functional.dropout2d`` for more details.
  954. Similarly, when x is a 5d tensor with shape `NCDHW`, where `D` is the depth of the feature, we can set ``axis=[0,1]`` to perform dropout3d. Please refer to ``paddle.nn.functional.dropout3d`` for more details.
  955. .. code-block:: python
  956. >>> import paddle
  957. >>> paddle.seed(2023)
  958. >>> x = paddle.to_tensor([[1,2,3], [4,5,6]]).astype(paddle.float32)
  959. >>> y_train = paddle.nn.functional.dropout(x, 0.5)
  960. >>> y_test = paddle.nn.functional.dropout(x, 0.5, training=False)
  961. >>> y_0 = paddle.nn.functional.dropout(x, axis=0)
  962. >>> y_1 = paddle.nn.functional.dropout(x, axis=1)
  963. >>> y_01 = paddle.nn.functional.dropout(x, axis=[0,1])
  964. >>> print(x)
  965. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  966. [[1., 2., 3.],
  967. [4., 5., 6.]])
  968. >>> print(y_train)
  969. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  970. [[2., 4., 0.],
  971. [8., 0., 0.]])
  972. >>> print(y_test)
  973. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  974. [[1., 2., 3.],
  975. [4., 5., 6.]])
  976. >>> print(y_0)
  977. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  978. [[2., 4., 6.],
  979. [8. , 10., 12.]])
  980. >>> print(y_1)
  981. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  982. [[2. , 4. , 6. ],
  983. [8. , 10., 12.]])
  984. >>> print(y_01)
  985. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  986. [[0., 0., 6.],
  987. [0., 0., 0.]])
  988. """
  989. if not isinstance(p, (float, int, Variable, pir.Value)):
  990. raise TypeError("p argument should be a number or Variable")
  991. if isinstance(p, (int, float)):
  992. # fast return for p == 0
  993. if p == 0:
  994. return x
  995. elif p < 0 or p > 1:
  996. raise ValueError("p argument should between 0 and 1")
  997. if mode not in ('downscale_in_infer', 'upscale_in_train'):
  998. raise ValueError(
  999. "mode argument should be 'downscale_in_infer' or 'upscale_in_train'"
  1000. )
  1001. if axis and not isinstance(axis, (int, list, tuple)):
  1002. raise TypeError("datatype of axis argument should be int or list")
  1003. if axis is None: # commonly used dropout
  1004. seed = None
  1005. mode = (
  1006. 'downgrade_in_infer' if mode == 'downscale_in_infer' else mode
  1007. ) # semantic transfer
  1008. if in_dynamic_or_pir_mode():
  1009. if paddle.static.default_main_program().random_seed != 0:
  1010. seed = paddle.static.default_main_program().random_seed
  1011. out = _C_ops.dropout(
  1012. x,
  1013. None,
  1014. p,
  1015. not training,
  1016. mode,
  1017. seed if seed is not None else 0,
  1018. seed is not None,
  1019. )
  1020. return out
  1021. else:
  1022. helper = LayerHelper('dropout', **locals())
  1023. check_variable_and_dtype(
  1024. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'dropout'
  1025. )
  1026. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  1027. mask = helper.create_variable_for_type_inference(
  1028. dtype=core.VarDesc.VarType.UINT8, stop_gradient=True
  1029. )
  1030. def get_attrs(prog, dropout_prob, is_test, seed):
  1031. if (seed is None or seed == 0) and prog.random_seed != 0:
  1032. seed = prog.random_seed
  1033. if isinstance(
  1034. dropout_prob, Variable
  1035. ) and not dropout_prob.shape != [1]:
  1036. raise TypeError(
  1037. f"Required p.shape == [1] if type(p) is Variable, but received p.shape = {p.shape}"
  1038. )
  1039. attrs = {
  1040. 'dropout_prob': dropout_prob,
  1041. 'is_test': is_test,
  1042. 'fix_seed': seed is not None,
  1043. 'seed': seed if seed is not None else 0,
  1044. 'dropout_implementation': mode,
  1045. }
  1046. return attrs
  1047. attrs = get_attrs(helper.main_program, p, not training, seed)
  1048. helper.append_op(
  1049. type='dropout',
  1050. inputs={'X': [x]},
  1051. outputs={'Out': [out], 'Mask': [mask]},
  1052. attrs=attrs,
  1053. )
  1054. return out
  1055. else: # sometimes called dropout_nd #TODO: optimize with c++
  1056. if not in_dynamic_mode():
  1057. check_variable_and_dtype(
  1058. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'dropout'
  1059. )
  1060. dtype = x.dtype
  1061. keep_prob = 1 - p
  1062. if training:
  1063. if in_dynamic_or_pir_mode() and p == 1.0:
  1064. return paddle.scale(x, scale=0.0)
  1065. scale_input = (
  1066. paddle.scale(x, scale=1 / keep_prob)
  1067. if mode == 'upscale_in_train'
  1068. else x
  1069. )
  1070. # get mask shape
  1071. input_shape = x.shape
  1072. if not in_dynamic_mode():
  1073. input_shape_tensor = paddle.shape(x)
  1074. drop_axes = [axis] if isinstance(axis, int) else list(axis)
  1075. if min(drop_axes) < 0 or max(drop_axes) > len(input_shape) - 1:
  1076. raise ValueError(
  1077. f"axis value should be greater than or equal to 0 and less than dimensions of x:{len(input_shape)}, but get axis value:{max(drop_axes)} "
  1078. )
  1079. if len(drop_axes) > len(input_shape):
  1080. raise ValueError(
  1081. f"length of axis should not be greater than dimensions of x:{len(input_shape)}, but get length of axis: {len(drop_axes)}"
  1082. )
  1083. mask_shape = [1] * len(input_shape)
  1084. if not in_dynamic_mode():
  1085. for i in drop_axes:
  1086. mask_shape[i] = input_shape_tensor[i]
  1087. else:
  1088. for i in drop_axes:
  1089. mask_shape[i] = input_shape[i]
  1090. # get mask
  1091. random_tensor = paddle.uniform(
  1092. mask_shape, dtype='float32', min=0.0, max=1.0
  1093. )
  1094. p = full(shape=[1], fill_value=p, dtype='float32')
  1095. keep_mask = paddle.greater_equal(random_tensor, p)
  1096. scale_input = paddle.cast(scale_input, dtype)
  1097. keep_mask = paddle.cast(keep_mask, dtype)
  1098. ret = paddle.multiply(scale_input, keep_mask, name=name)
  1099. return ret
  1100. else: # test
  1101. ret = (
  1102. paddle.scale(x, scale=keep_prob)
  1103. if mode == 'downscale_in_infer'
  1104. else x
  1105. )
  1106. return ret
  1107. def dropout2d(x, p=0.5, training=True, data_format='NCHW', name=None):
  1108. """
  1109. Randomly zero out entire channels (in the batched input 4d tensor with the shape `NCHW` ,
  1110. a channel is a 2D feature map with the shape `HW` ). Each channel will be zeroed out independently
  1111. on every forward call with probability `p` using samples from a Bernoulli distribution.
  1112. See :ref:`api_paddle_nn_functional_dropout` for more details.
  1113. Args:
  1114. x (Tensor): The input is 4-D Tensor with shape [N, C, H, W] or [N, H, W, C].
  1115. The data type is float16, float32 or float64.
  1116. p (float, optional): Probability of setting units to zero. Default: 0.5.
  1117. training (bool, optional): A flag indicating whether it is in train phrase or not. Default: True.
  1118. data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from `NCHW` or `NHWC` . When it is `NCHW` , the data is stored in the order of: [batch_size, input_channels, input_height, input_width]. Default: `NCHW` .
  1119. name (str, optional): Name for the operation, Default: None. For more information, please refer to :ref:`api_guide_Name`.
  1120. Returns:
  1121. A Tensor representing the dropout2d, has same shape and data type as `x` .
  1122. Examples:
  1123. .. code-block:: python
  1124. >>> import paddle
  1125. >>> paddle.seed(1)
  1126. >>> x = paddle.randn(shape=(2, 3, 4, 5)).astype(paddle.float32)
  1127. >>> y_train = paddle.nn.functional.dropout2d(x) #train
  1128. >>> y_test = paddle.nn.functional.dropout2d(x, training=False) #test
  1129. >>> for i in range(2):
  1130. ... for j in range(3):
  1131. ... print(x[i,j,:,:])
  1132. ... print(y_train[i,j,:,:]) # may all 0
  1133. ... print(y_test[i,j,:,:])
  1134. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1135. [[-0.30557564, 0.11855337, 0.41220093, -0.09968963, 1.50014710],
  1136. [ 1.24004936, -0.92485696, 0.08612321, 1.15149164, -0.09276631],
  1137. [ 1.22873247, -1.46587241, -1.30802727, 0.19496460, 1.73776841],
  1138. [ 0.40092674, 0.67630458, 0.72265440, 1.31720388, -1.41899264]])
  1139. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1140. [[-0.61115128, 0.23710674, 0.82440186, -0.19937925, 3.00029421],
  1141. [ 2.48009872, -1.84971392, 0.17224643, 2.30298328, -0.18553263],
  1142. [ 2.45746493, -2.93174481, -2.61605453, 0.38992921, 3.47553682],
  1143. [ 0.80185348, 1.35260916, 1.44530880, 2.63440776, -2.83798528]])
  1144. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1145. [[-0.30557564, 0.11855337, 0.41220093, -0.09968963, 1.50014710],
  1146. [ 1.24004936, -0.92485696, 0.08612321, 1.15149164, -0.09276631],
  1147. [ 1.22873247, -1.46587241, -1.30802727, 0.19496460, 1.73776841],
  1148. [ 0.40092674, 0.67630458, 0.72265440, 1.31720388, -1.41899264]])
  1149. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1150. [[ 0.88350385, -1.14767575, 0.51043051, -0.10051888, -0.61305630],
  1151. [-0.12084112, 0.48506257, -1.13189507, 0.62806708, -0.80003673],
  1152. [ 0.51513153, -0.08890446, 0.22753835, 0.11557858, 0.78117645],
  1153. [ 1.47505593, 0.84618902, -0.38528305, -1.05887091, 0.16592593]])
  1154. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1155. [[ 1.76700771, -2.29535151, 1.02086103, -0.20103776, -1.22611260],
  1156. [-0.24168225, 0.97012514, -2.26379013, 1.25613415, -1.60007346],
  1157. [ 1.03026307, -0.17780893, 0.45507669, 0.23115715, 1.56235290],
  1158. [ 2.95011187, 1.69237804, -0.77056611, -2.11774182, 0.33185187]])
  1159. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1160. [[ 0.88350385, -1.14767575, 0.51043051, -0.10051888, -0.61305630],
  1161. [-0.12084112, 0.48506257, -1.13189507, 0.62806708, -0.80003673],
  1162. [ 0.51513153, -0.08890446, 0.22753835, 0.11557858, 0.78117645],
  1163. [ 1.47505593, 0.84618902, -0.38528305, -1.05887091, 0.16592593]])
  1164. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1165. [[-1.46668839, -0.38117948, 1.18678427, 0.38740095, 0.29117522],
  1166. [-0.13538910, -0.14527084, -0.04912176, -0.26063353, 0.23640174],
  1167. [ 0.45643106, 0.60587281, -1.03242552, -0.45319262, -1.57911122],
  1168. [-0.08732958, -0.75898546, 0.14563090, -1.73751652, -0.89109969]])
  1169. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1170. [[-0., -0., 0. , 0. , 0. ],
  1171. [-0., -0., -0., -0., 0. ],
  1172. [0. , 0. , -0., -0., -0.],
  1173. [-0., -0., 0. , -0., -0.]])
  1174. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1175. [[-1.46668839, -0.38117948, 1.18678427, 0.38740095, 0.29117522],
  1176. [-0.13538910, -0.14527084, -0.04912176, -0.26063353, 0.23640174],
  1177. [ 0.45643106, 0.60587281, -1.03242552, -0.45319262, -1.57911122],
  1178. [-0.08732958, -0.75898546, 0.14563090, -1.73751652, -0.89109969]])
  1179. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1180. [[-0.32110816, -0.76044011, 0.34456784, -0.39410326, 0.37896338],
  1181. [ 0.52747023, 0.72711533, 0.29204839, 0.72493637, 0.31128070],
  1182. [ 0.58046782, -1.78499067, -1.67504823, -0.38590902, -0.26243693],
  1183. [ 0.96669912, 0.43670532, -0.38109761, 0.78405094, -2.17882323]])
  1184. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1185. [[-0., -0., 0. , -0., 0. ],
  1186. [0. , 0. , 0. , 0. , 0. ],
  1187. [0. , -0., -0., -0., -0.],
  1188. [0. , 0. , -0., 0. , -0.]])
  1189. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1190. [[-0.32110816, -0.76044011, 0.34456784, -0.39410326, 0.37896338],
  1191. [ 0.52747023, 0.72711533, 0.29204839, 0.72493637, 0.31128070],
  1192. [ 0.58046782, -1.78499067, -1.67504823, -0.38590902, -0.26243693],
  1193. [ 0.96669912, 0.43670532, -0.38109761, 0.78405094, -2.17882323]])
  1194. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1195. [[ 0.17168395, 0.45112833, 0.63307828, 2.38763475, -1.27247131],
  1196. [ 0.56171960, -1.09584677, 0.38300961, -0.57512099, 0.31011426],
  1197. [-0.95336407, -1.04852903, -0.21312937, -0.53549880, -0.00074209],
  1198. [ 2.22819090, 1.12403083, -0.04198794, -1.51167727, -0.42699185]])
  1199. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1200. [[0. , 0. , 0. , 0. , -0.],
  1201. [0. , -0., 0. , -0., 0. ],
  1202. [-0., -0., -0., -0., -0.],
  1203. [0. , 0. , -0., -0., -0.]])
  1204. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1205. [[ 0.17168395, 0.45112833, 0.63307828, 2.38763475, -1.27247131],
  1206. [ 0.56171960, -1.09584677, 0.38300961, -0.57512099, 0.31011426],
  1207. [-0.95336407, -1.04852903, -0.21312937, -0.53549880, -0.00074209],
  1208. [ 2.22819090, 1.12403083, -0.04198794, -1.51167727, -0.42699185]])
  1209. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1210. [[ 0.62503546, -0.20989063, -0.22046235, -0.38679042, -1.02590704],
  1211. [ 1.04561794, 1.08428383, -0.52219963, -1.56003857, 0.89213932],
  1212. [-0.16578521, 0.14524542, -0.45563069, 0.48180851, 1.35843253],
  1213. [ 1.07669640, -0.84535235, -1.18651557, 0.79144061, -0.45565742]])
  1214. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1215. [[0. , -0., -0., -0., -0.],
  1216. [0. , 0. , -0., -0., 0. ],
  1217. [-0., 0. , -0., 0. , 0. ],
  1218. [0. , -0., -0., 0. , -0.]])
  1219. Tensor(shape=[4, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  1220. [[ 0.62503546, -0.20989063, -0.22046235, -0.38679042, -1.02590704],
  1221. [ 1.04561794, 1.08428383, -0.52219963, -1.56003857, 0.89213932],
  1222. [-0.16578521, 0.14524542, -0.45563069, 0.48180851, 1.35843253],
  1223. [ 1.07669640, -0.84535235, -1.18651557, 0.79144061, -0.45565742]])
  1224. """
  1225. input_shape = x.shape
  1226. if len(input_shape) != 4:
  1227. raise ValueError(
  1228. f"dimensions of x should be 4, but received {len(input_shape)} != 4"
  1229. )
  1230. if data_format not in ["NCHW", "NHWC"]:
  1231. raise ValueError(
  1232. "Attr(data_format) should be 'NCHW' or 'NHWC'. Received "
  1233. "Attr(data_format): %s." % str(data_format)
  1234. )
  1235. return dropout(
  1236. x,
  1237. p=p,
  1238. axis=[0, 1] if data_format == 'NCHW' else [0, 3],
  1239. training=training,
  1240. mode="upscale_in_train",
  1241. name=name,
  1242. )
  1243. def dropout3d(x, p=0.5, training=True, data_format='NCDHW', name=None):
  1244. """
  1245. Randomly zero out entire channels (in the batched input 5d tensor with the shape `NCDHW` ,
  1246. a channel is a 3D feature map with the shape `DHW` ). Each channel will be zeroed out independently
  1247. on every forward call with probability `p` using samples from a Bernoulli distribution.
  1248. See :ref:`api_paddle_nn_functional_dropout` for more details.
  1249. Args:
  1250. x (Tensor): The input is 5-D Tensor with shape [N, C, D, H, W] or [N, D, H, W, C].
  1251. The data type is float32 or float64.
  1252. p (float, optional): Probability of setting units to zero. Default: 0.5.
  1253. training (bool, optional): A flag indicating whether it is in train phrase or not. Default: True.
  1254. data_format (str, optional): Specify the data format of the input, and the data format of the output will be consistent with that of the input. An optional string from ``NCDHW`` or ``NDHWC``. When it is ``NCDHW`` , the data is stored in the order of: [batch_size, input_channels, input_depth, input_height, input_width]. Default: ``NCDHW`` .
  1255. name (str, optional): Name for the operation, Default: None. For more information, please refer to :ref:`api_guide_Name`.
  1256. Returns:
  1257. A Tensor representing the dropout3d, has same shape and data type with `x` .
  1258. Examples:
  1259. .. code-block:: python
  1260. >>> import paddle
  1261. >>> x = paddle.randn(shape=(2, 3, 4, 5, 6)).astype(paddle.float32)
  1262. >>> y_train = paddle.nn.functional.dropout3d(x) #train
  1263. >>> y_test = paddle.nn.functional.dropout3d(x, training=False) #test
  1264. >>> print(x[0,0,:,:,:])
  1265. >>> print(y_train[0,0,:,:,:]) # may all 0
  1266. >>> print(y_test[0,0,:,:,:])
  1267. """
  1268. input_shape = x.shape
  1269. if len(input_shape) != 5:
  1270. raise ValueError(
  1271. f"dimensions of x should be 5, but received {len(input_shape)} != 5"
  1272. )
  1273. if data_format not in ["NCDHW", "NDHWC"]:
  1274. raise ValueError(
  1275. "Attr(data_format) should be 'NCDHW' or 'NDHWC'. Received "
  1276. "Attr(data_format): %s." % str(data_format)
  1277. )
  1278. return dropout(
  1279. x,
  1280. p=p,
  1281. axis=[0, 1] if data_format == 'NCDHW' else [0, 4],
  1282. training=training,
  1283. mode="upscale_in_train",
  1284. name=name,
  1285. )
  1286. def alpha_dropout(x, p=0.5, training=True, name=None):
  1287. """
  1288. Alpha Dropout is a type of Dropout that maintains the self-normalizing property.
  1289. For an input with zero mean and unit standard deviation, the output of Alpha Dropout
  1290. maintains the original mean and standard deviation of the input.
  1291. Alpha Dropout fits well to SELU activate function by randomly setting activations to the negative saturation value.
  1292. Args:
  1293. x (Tensor): The input tensor. The data type is float16, float32 or float64.
  1294. p (float | int): Probability of setting units to zero. Default 0.5.
  1295. training (bool): A flag indicating whether it is in train phrase or not. Default True.
  1296. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1297. Returns:
  1298. A Tensor representing the dropout, has same shape and data type as `x`.
  1299. Examples:
  1300. .. code-block:: python
  1301. >>> import paddle
  1302. >>> paddle.seed(1)
  1303. >>> x = paddle.to_tensor([[-1, 1], [-1, 1]]).astype(paddle.float32)
  1304. >>> y_train = paddle.nn.functional.alpha_dropout(x, 0.5)
  1305. >>> y_test = paddle.nn.functional.alpha_dropout(x, 0.5, training=False)
  1306. >>> print(y_train)
  1307. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1308. [[-0.77919382, 1.66559887],
  1309. [-0.10721093, -0.77919382]])
  1310. >>> print(y_test)
  1311. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1312. [[-1., 1.],
  1313. [-1., 1.]])
  1314. """
  1315. if not isinstance(p, (float, int)):
  1316. raise TypeError("p argument should be a float or int")
  1317. if p < 0 or p > 1:
  1318. raise ValueError("p argument should between 0 and 1")
  1319. if not in_dynamic_mode():
  1320. check_variable_and_dtype(
  1321. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'alpha_dropout'
  1322. )
  1323. if training:
  1324. if p == 1:
  1325. return paddle.scale(x, scale=0.0)
  1326. # get transformation params
  1327. alpha = 1.6732632423543772848170429916717
  1328. scale = 1.0507009873554804934193349852946
  1329. alpha_p = -alpha * scale
  1330. a = ((1 - p) * (1 + p * alpha_p**2)) ** -0.5
  1331. b = -a * alpha_p * p
  1332. dtype = x.dtype
  1333. input_shape = x.shape
  1334. # get mask
  1335. random_tensor = paddle.uniform(
  1336. input_shape, dtype='float32', min=0.0, max=1.0
  1337. )
  1338. p = full(shape=input_shape, fill_value=p, dtype='float32')
  1339. keep_mask = paddle.greater_equal(random_tensor, p)
  1340. keep_mask = paddle.cast(keep_mask, dtype)
  1341. drop_mask = paddle.subtract(
  1342. full(shape=input_shape, fill_value=1.0, dtype=dtype), keep_mask
  1343. )
  1344. # apply mask
  1345. b = full(shape=input_shape, fill_value=b, dtype=dtype)
  1346. y = paddle.add(
  1347. paddle.multiply(x, keep_mask),
  1348. paddle.scale(drop_mask, scale=alpha_p),
  1349. )
  1350. res = paddle.add(paddle.scale(y, scale=a), b, name=name)
  1351. return res
  1352. else: # test
  1353. return x
  1354. def pad(x, pad, mode='constant', value=0.0, data_format="NCHW", name=None):
  1355. """
  1356. Pad tensor according to ``'pad'`` and ``'mode'``.
  1357. If mode is ``'constant'`` and length of pad is twice as length of x dimension,
  1358. then the padding will be started from the first dimension and moved back onto x
  1359. according to ``'pad'`` and ``'value'``.
  1360. If mode is ``'reflect'``, pad[0] and pad[1] must be no greater
  1361. than width-1. The height and depth dimension has the same condition.
  1362. Parameters:
  1363. x (Tensor): The input tensor with data type float32/double/int32/int64_t/complex64/complex128.
  1364. pad (Tensor|list[int]|tuple[int]): The padding size with data type int.
  1365. If mode is ``'constant'`` and length of pad is twice as length of x dimension, then x will
  1366. be padded from the first dimension to the last dimension.
  1367. Else: 1. If input dimension is 3, then the pad has the form (pad_left,
  1368. pad_right). 2. If the input dimension is 4, then the pad has the form (pad_left, pad_right,
  1369. pad_top, pad_bottom). 3. If the input dimension is 5, then the pad has the form
  1370. (pad_left, pad_right, pad_top, pad_bottom, pad_front, pad_back).
  1371. mode (str, optional): Four modes: ``'constant'`` (default), ``'reflect'``, ``'replicate'``, ``'circular'``. Default is ``'constant'``.
  1372. - 'constant' mode, uses a constant value to pad the input tensor.
  1373. - 'reflect' mode, uses reflection of the input boundaries to pad the input tensor.
  1374. - 'replicate' mode, uses input boundaries to pad the input tensor.
  1375. - 'circular' mode, uses circular input to pad the input tensor.
  1376. value (float, optional): The value to fill the padded areas in 'constant' mode . Default is :math:`0.0`.
  1377. data_format (str, optional): An string from: ``'NCL'``, ``'NLC'``, ``'NHWC'``, ``'NCHW'``, ``'NCDHW'``, ``'NDHWC'``. Specify the data format of
  1378. the input data. Default: ``'NCHW'``.
  1379. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: ``'None'``.
  1380. Returns:
  1381. Tensor, a Tensor padded according to pad and mode and data type is same as input.
  1382. Example:
  1383. .. code-block:: text
  1384. x = [[[[[1., 2., 3.],
  1385. [4., 5., 6.]]]]]
  1386. Case 0:
  1387. pad = [0, 0, 0, 0, 0, 0, 1, 1, 0, 0],
  1388. mode = 'constant'
  1389. value = 0
  1390. Out = [[[[[0., 0., 0.],
  1391. [1., 2., 3.],
  1392. [4., 5., 6.],
  1393. [0., 0., 0.]]]]]
  1394. Case 1:
  1395. pad = [2, 2, 1, 1, 0, 0],
  1396. mode = 'constant'
  1397. value = 0
  1398. Out = [[[[[0. 0. 0. 0. 0. 0. 0.]
  1399. [0. 0. 1. 2. 3. 0. 0.]
  1400. [0. 0. 4. 5. 6. 0. 0.]
  1401. [0. 0. 0. 0. 0. 0. 0.]]]]]
  1402. Case 2:
  1403. pad = [2, 2, 1, 1, 0, 0],
  1404. mode = 'reflect'
  1405. Out = [[[[[6. 5. 4. 5. 6. 5. 4.]
  1406. [3. 2. 1. 2. 3. 2. 1.]
  1407. [6. 5. 4. 5. 6. 5. 4.]
  1408. [3. 2. 1. 2. 3. 2. 1.]]]]]
  1409. Case 3:
  1410. pad = [2, 2, 1, 1, 0, 0],
  1411. mode = 'replicate'
  1412. Out = [[[[[1. 1. 1. 2. 3. 3. 3.]
  1413. [1. 1. 1. 2. 3. 3. 3.]
  1414. [4. 4. 4. 5. 6. 6. 6.]
  1415. [4. 4. 4. 5. 6. 6. 6.]]]]]
  1416. Case 4:
  1417. pad = [2, 2, 1, 1, 0, 0],
  1418. mode = 'circular'
  1419. Out = [[[[[5. 6. 4. 5. 6. 4. 5.]
  1420. [2. 3. 1. 2. 3. 1. 2.]
  1421. [5. 6. 4. 5. 6. 4. 5.]
  1422. [2. 3. 1. 2. 3. 1. 2.]]]]]
  1423. Examples:
  1424. .. code-block:: python
  1425. >>> import paddle
  1426. >>> import paddle.nn.functional as F
  1427. >>> # example 1
  1428. >>> x_shape = (1, 1, 3)
  1429. >>> x = paddle.arange(paddle.prod(paddle.to_tensor(x_shape)), dtype="float32").reshape(x_shape) + 1
  1430. >>> y = F.pad(x, [0, 0, 0, 0, 2, 3], value=1, mode='constant', data_format="NCL")
  1431. >>> print(y)
  1432. Tensor(shape=[1, 1, 8], dtype=float32, place=Place(cpu), stop_gradient=True,
  1433. [[[1., 1., 1., 2., 3., 1., 1., 1.]]])
  1434. >>> # example 2
  1435. >>> x_shape = (1, 1, 3)
  1436. >>> x = paddle.arange(paddle.prod(paddle.to_tensor(x_shape)), dtype="float32").reshape(x_shape) + 1
  1437. >>> y = F.pad(x, [2, 3], value=1, mode='constant', data_format="NCL")
  1438. >>> print(y)
  1439. Tensor(shape=[1, 1, 8], dtype=float32, place=Place(cpu), stop_gradient=True,
  1440. [[[1., 1., 1., 2., 3., 1., 1., 1.]]])
  1441. >>> # example 3
  1442. >>> x_shape = (1, 1, 2, 3)
  1443. >>> x = paddle.arange(paddle.prod(paddle.to_tensor(x_shape)), dtype="float32").reshape(x_shape) + 1
  1444. >>> y = F.pad(x, [1, 2, 1, 1], value=1, mode='circular')
  1445. >>> print(y)
  1446. Tensor(shape=[1, 1, 4, 6], dtype=float32, place=Place(cpu), stop_gradient=True,
  1447. [[[[6., 4., 5., 6., 4., 5.],
  1448. [3., 1., 2., 3., 1., 2.],
  1449. [6., 4., 5., 6., 4., 5.],
  1450. [3., 1., 2., 3., 1., 2.]]]])
  1451. """
  1452. assert mode in [
  1453. 'reflect',
  1454. 'replicate',
  1455. 'constant',
  1456. 'circular',
  1457. ], f"mode should be one of constant, reflect, replicate, circular, but got {mode}."
  1458. data_format = data_format.upper()
  1459. assert data_format in ["NCL", "NCHW", "NCDHW", "NLC", "NHWC", "NDHWC"], (
  1460. "data_format should be in one of [NCL, NCHW, NCDHW, NLC, NHWC, NDHWC], "
  1461. f"but got {data_format}"
  1462. )
  1463. x_dim = len(x.shape)
  1464. if (
  1465. mode == "constant"
  1466. and isinstance(pad, (list, tuple))
  1467. and len(pad) == x_dim * 2
  1468. ):
  1469. paddings = pad
  1470. pad_value = value
  1471. if in_dynamic_mode():
  1472. out = _C_ops.pad(x, paddings, float(pad_value))
  1473. return out
  1474. if in_pir_mode():
  1475. if isinstance(pad_value, paddle.pir.Value):
  1476. return _C_ops.pad(x, paddings, pad_value)
  1477. else:
  1478. return _C_ops.pad(x, paddings, float(pad_value))
  1479. check_variable_and_dtype(
  1480. x,
  1481. 'x',
  1482. [
  1483. 'float16',
  1484. 'float32',
  1485. 'float64',
  1486. 'int32',
  1487. 'int64',
  1488. 'complex64',
  1489. 'complex128',
  1490. 'uint16',
  1491. ],
  1492. "pad",
  1493. )
  1494. check_type(pad_value, 'pad_value', (float, int, Variable), 'pad')
  1495. if isinstance(pad_value, int):
  1496. pad_value = float(pad_value)
  1497. helper = LayerHelper('pad', **locals())
  1498. dtype = helper.input_dtype(input_param_name='x')
  1499. out = helper.create_variable_for_type_inference(dtype)
  1500. helper.append_op(
  1501. type='pad',
  1502. inputs={'X': x},
  1503. outputs={'Out': out},
  1504. attrs={'paddings': paddings, 'pad_value': pad_value},
  1505. )
  1506. return out
  1507. assert x_dim in [
  1508. 3,
  1509. 4,
  1510. 5,
  1511. ], f"input tensor dimension must be in [3, 4, 5] but got {x_dim}"
  1512. supported_format_map = {
  1513. 3: ["NCL", "NLC"],
  1514. 4: ["NCHW", "NHWC"],
  1515. 5: ["NCDHW", "NDHWC"],
  1516. }
  1517. assert (
  1518. data_format in supported_format_map[x_dim]
  1519. ), f"input tensor dimension is {x_dim}, it's data format should be in {supported_format_map[x_dim]} but got {data_format}"
  1520. unsqueezed_dim = []
  1521. if isinstance(pad, (Variable, pir.Value)):
  1522. if data_format in ["NCL", "NCHW", "NCDHW"]:
  1523. data_format = "NCDHW"
  1524. if x_dim == 3:
  1525. pad = concat([zeros((4,), dtype="int32"), pad], axis=0)
  1526. unsqueezed_dim = [3, 4]
  1527. x = unsqueeze(x, axis=unsqueezed_dim)
  1528. elif x_dim == 4:
  1529. pad = concat([pad, zeros((2,), dtype="int32")], axis=0)
  1530. unsqueezed_dim = [2]
  1531. x = unsqueeze(x, axis=unsqueezed_dim)
  1532. elif data_format in ["NLC", "NHWC", "NDHWC"]:
  1533. data_format = "NDHWC"
  1534. if x_dim == 3:
  1535. pad = concat([zeros((4,), dtype="int32"), pad], axis=0)
  1536. unsqueezed_dim = [2, 3]
  1537. x = unsqueeze(x, axis=unsqueezed_dim)
  1538. elif x_dim == 4:
  1539. pad = concat([pad, zeros((2,), dtype="int32")], axis=0)
  1540. unsqueezed_dim = [1]
  1541. x = unsqueeze(x, axis=unsqueezed_dim)
  1542. else:
  1543. pad = list(pad)
  1544. if data_format in ["NCL", "NCHW", "NCDHW"]:
  1545. data_format = "NCDHW"
  1546. if x_dim == 3:
  1547. pad = [0, 0, 0, 0] + pad
  1548. unsqueezed_dim = [3, 4]
  1549. x = unsqueeze(x, axis=unsqueezed_dim)
  1550. elif x_dim == 4:
  1551. pad = pad + [0, 0]
  1552. unsqueezed_dim = [2]
  1553. x = unsqueeze(x, axis=unsqueezed_dim)
  1554. elif data_format in ["NLC", "NHWC", "NDHWC"]:
  1555. data_format = "NDHWC"
  1556. if x_dim == 3:
  1557. pad = [0, 0, 0, 0] + pad
  1558. unsqueezed_dim = [2, 3]
  1559. x = unsqueeze(x, axis=unsqueezed_dim)
  1560. elif x_dim == 4:
  1561. pad = pad + [0, 0]
  1562. unsqueezed_dim = [1]
  1563. x = unsqueeze(x, axis=unsqueezed_dim)
  1564. if in_dynamic_or_pir_mode():
  1565. if isinstance(pad, Variable):
  1566. pad = pad.tolist()
  1567. out = _C_ops.pad3d(x, pad, mode, value, data_format)
  1568. else:
  1569. attrs = {'mode': mode, 'value': value, 'data_format': data_format}
  1570. inputs = {'X': [x]}
  1571. if isinstance(pad, Variable):
  1572. inputs['Paddings'] = [pad]
  1573. attrs['paddings'] = []
  1574. else:
  1575. attrs['paddings'] = pad
  1576. helper = LayerHelper('pad3d', **locals())
  1577. dtype = helper.input_dtype(input_param_name='input')
  1578. out = helper.create_variable_for_type_inference(dtype)
  1579. helper.append_op(
  1580. type='pad3d', inputs=inputs, outputs={"Out": out}, attrs=attrs
  1581. )
  1582. if len(unsqueezed_dim) != 0:
  1583. out = squeeze(out, axis=unsqueezed_dim)
  1584. return out
  1585. def zeropad2d(x, padding, data_format="NCHW", name=None):
  1586. """
  1587. Pads the input tensor boundaries with zero according to 'pad'.
  1588. Args:
  1589. x(Tensor): The input tensor with data type float16/float32/float64/int32/int64.
  1590. padding(int | Tensor | List[int] | Tuple[int]): The padding size with data type int.
  1591. The input dimension should be 4 and pad has the form (pad_left, pad_right,
  1592. pad_top, pad_bottom).
  1593. data_format(str, optional): An string from: "NHWC", "NCHW". Specify the data format of
  1594. the input data. Default: "NCHW".
  1595. name(str, optional): The default value is None. Normally there is no need for user
  1596. to set this property. For more information, please refer to :ref:`api_guide_Name`.
  1597. Returns:
  1598. Tensor, padded with 0 according to pad and data type is same as input.
  1599. Examples:
  1600. .. code-block:: python
  1601. >>> import paddle
  1602. >>> import paddle.nn.functional as F
  1603. >>> x_shape = paddle.to_tensor([1, 1, 2, 3])
  1604. >>> x = paddle.arange(paddle.prod(x_shape), dtype="float32").reshape(x_shape) + 1
  1605. >>> y = F.zeropad2d(x, [1, 2, 1, 1])
  1606. >>> print(y)
  1607. Tensor(shape=[1, 1, 4, 6], dtype=float32, place=Place(cpu), stop_gradient=True,
  1608. [[[[0., 0., 0., 0., 0., 0.],
  1609. [0., 1., 2., 3., 0., 0.],
  1610. [0., 4., 5., 6., 0., 0.],
  1611. [0., 0., 0., 0., 0., 0.]]]])
  1612. """
  1613. return pad(
  1614. x,
  1615. pad=padding,
  1616. mode='constant',
  1617. value=0,
  1618. data_format=data_format,
  1619. name=name,
  1620. )
  1621. def cosine_similarity(x1, x2, axis=1, eps=1e-8):
  1622. """
  1623. Compute cosine similarity between x1 and x2 along axis.
  1624. Parameters:
  1625. x1 (Tensor): First input. float32/double.
  1626. x2 (Tensor): Second input. float32/double.
  1627. axis (int, optional): Dimension of vectors to compute cosine similarity. Default is 1.
  1628. eps(float, optional): Small value to avoid division by zero. Default is 1e-8.
  1629. Returns:
  1630. Tensor, a Tensor representing cosine similarity between x1 and x2 along axis.
  1631. Examples:
  1632. .. code-block:: text
  1633. Case 0:
  1634. x1 = [[0.8024077 0.9927354 0.27238318 0.8344984 ]
  1635. [0.48949873 0.5797396 0.65444374 0.66510963]
  1636. [0.1031398 0.9614342 0.08365563 0.6796464 ]
  1637. [0.10760343 0.7461209 0.7726148 0.5801006 ]]
  1638. x2 = [[0.62913156 0.1536727 0.9847992 0.04591406]
  1639. [0.9098952 0.15715368 0.8671125 0.3156102 ]
  1640. [0.4427798 0.54136837 0.5276275 0.32394758]
  1641. [0.3769419 0.8535014 0.48041078 0.9256797 ]]
  1642. axis = 1
  1643. eps = 1e-8
  1644. Out: [0.5275037 0.8368967 0.75037485 0.9245899]
  1645. Code Examples:
  1646. .. code-block:: python
  1647. >>> import paddle
  1648. >>> import paddle.nn as nn
  1649. >>> paddle.seed(1)
  1650. >>> x1 = paddle.randn(shape=[2, 3])
  1651. >>> x2 = paddle.randn(shape=[2, 3])
  1652. >>> result = paddle.nn.functional.cosine_similarity(x1, x2, axis=0)
  1653. >>> print(result)
  1654. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1655. [ 0.97689527, 0.99996042, -0.55138415])
  1656. """
  1657. w12 = sum(paddle.multiply(x1, x2), axis=axis)
  1658. w1 = sum(paddle.multiply(x1, x1), axis=axis)
  1659. w2 = sum(paddle.multiply(x2, x2), axis=axis)
  1660. n12 = sqrt(clip(w1 * w2, min=eps * eps))
  1661. cos_sim = w12 / n12
  1662. return cos_sim
  1663. def linear(x, weight, bias=None, name=None):
  1664. r"""
  1665. Fully-connected linear transformation operator. For each input :math:`X` ,
  1666. the equation is:
  1667. .. math::
  1668. Out = XW + b
  1669. where :math:`W` is the weight and :math:`b` is the bias.
  1670. If the weight is a 2-D tensor of shape :math:`[in\_features, out\_features]` ,
  1671. input should be a multi-dimensional tensor of shape
  1672. :math:`[batch\_size, *, in\_features]` , where :math:`*` means any number of
  1673. additional dimensions. The linear operator multiplies input tensor with
  1674. weight and produces an output tensor of shape :math:`[batch\_size, *, out\_features]` ,
  1675. If :math:`bias` is not None, the bias should be a 1-D tensor of shape
  1676. :math:`[out\_features]` and will be added to the output.
  1677. Parameters:
  1678. x (Tensor): Input tensor. The data type should be bfloat16, float16, float32 or float64.
  1679. weight (Tensor): Weight tensor. The data type should be float16, float32 or float64.
  1680. bias (Tensor, optional): Bias tensor. The data type should be float16, float32 or float64.
  1681. If it is set to None, no bias will be added to the output units.
  1682. name (str, optional): Normally there is no need for user to set this parameter.
  1683. For detailed information, please refer to :ref:`api_guide_Name` .
  1684. Returns:
  1685. Tensor, the shape is :math:`[batch\_size, *, out\_features]` and the
  1686. data type is the same with input :math:`x` .
  1687. Examples:
  1688. .. code-block:: python
  1689. >>> import paddle
  1690. >>> paddle.seed(2023)
  1691. >>> x = paddle.randn((3, 2), dtype="float32")
  1692. >>> print(x)
  1693. Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1694. [[ 0.06132207, 1.11349595],
  1695. [ 0.41906244, -0.24858207],
  1696. [-1.85169315, -1.50370061]])
  1697. >>> weight = paddle.full(shape=[2, 4], fill_value="0.5", dtype="float32", name="weight")
  1698. >>> print(weight)
  1699. Tensor(shape=[2, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1700. [[0.50000000, 0.50000000, 0.50000000, 0.50000000],
  1701. [0.50000000, 0.50000000, 0.50000000, 0.50000000]])
  1702. >>> bias = paddle.ones(shape=[4], dtype="float32", name="bias")
  1703. >>> print(bias)
  1704. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1705. [1., 1., 1., 1.])
  1706. >>> y = paddle.nn.functional.linear(x, weight, bias)
  1707. >>> print(y)
  1708. Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1709. [[ 1.58740902, 1.58740902, 1.58740902, 1.58740902],
  1710. [ 1.08524013, 1.08524013, 1.08524013, 1.08524013],
  1711. [-0.67769694, -0.67769694, -0.67769694, -0.67769694]])
  1712. """
  1713. if in_dynamic_mode():
  1714. # TODO(jiabin): using addmm for fast forward route
  1715. return _C_ops.linear(x, weight, bias)
  1716. elif in_pir_mode():
  1717. out = _C_ops.matmul(x, weight, False, False)
  1718. if bias is not None:
  1719. return _C_ops.add(out, bias)
  1720. else:
  1721. return out
  1722. else:
  1723. helper = LayerHelper('linear', **locals())
  1724. dtype = x.dtype
  1725. check_variable_and_dtype(
  1726. x, 'x', ["uint16", 'float16', 'float32', 'float64'], 'linear'
  1727. )
  1728. check_dtype(
  1729. dtype,
  1730. 'dtype',
  1731. ["uint16", 'float16', 'float32', 'float64'],
  1732. 'linear',
  1733. )
  1734. inputs = {'X': [x], 'Y': [weight]}
  1735. attrs = {'trans_x': False, 'trans_y': False}
  1736. tmp = helper.create_variable_for_type_inference(dtype)
  1737. helper.append_op(
  1738. type='matmul_v2',
  1739. inputs=inputs,
  1740. outputs={'Out': tmp},
  1741. attrs=attrs,
  1742. )
  1743. if bias is not None:
  1744. res = helper.create_variable_for_type_inference(dtype)
  1745. helper.append_op(
  1746. type='elementwise_add',
  1747. inputs={'X': [tmp], 'Y': [bias]},
  1748. outputs={'Out': [res]},
  1749. attrs={'axis': -1},
  1750. )
  1751. else:
  1752. res = tmp
  1753. return res
  1754. def label_smooth(label, prior_dist=None, epsilon=0.1, name=None):
  1755. r"""
  1756. Label smoothing is a mechanism to regularize the classifier layer and is called
  1757. label-smoothing regularization (LSR).Label smoothing is proposed to encourage
  1758. the model to be less confident, since optimizing the log-likelihood of the
  1759. correct label directly may cause overfitting and reduce the ability of the
  1760. model to adapt.
  1761. Label smoothing replaces the ground-truth label :math:`y` with the weighted sum
  1762. of itself and some fixed distribution :math:`\mu`. For class :math:`k`,
  1763. i.e.
  1764. .. math::
  1765. \\tilde{y_k} = (1 - \epsilon) * y_k + \epsilon * \mu_k,
  1766. where :math:`1 - \epsilon` and :math:`\epsilon` are the weights
  1767. respectively, and :math:`\\tilde{y}_k` is the smoothed label. Usually
  1768. uniform distribution is used for :math:`\mu`.
  1769. See more details about label smoothing in https://arxiv.org/abs/1512.00567.
  1770. Parameters:
  1771. label(Tensor): The input variable containing the label data. The
  1772. label data should use one-hot representation. It's
  1773. a multidimensional tensor with a shape of
  1774. :math:`[N_1, ..., Depth]`, where Depth is class number. The dtype can be "float16" "float32" and "float64".
  1775. prior_dist(Tensor, optional): The prior distribution to be used to smooth
  1776. labels. If not provided, an uniform distribution
  1777. is used. It's a multidimensional tensor with a shape of
  1778. :math:`[1, class\_num]` . The default value is None.
  1779. epsilon(float, optional): The weight used to mix up the original ground-truth
  1780. distribution and the fixed distribution. The default value is
  1781. 0.1.
  1782. name(str, optional): The default value is None. Normally there is no need for user
  1783. to set this property. For more information, please refer to
  1784. :ref:`api_guide_Name`.
  1785. Returns:
  1786. Tensor: The tensor containing the smoothed labels.
  1787. Examples:
  1788. .. code-block:: python
  1789. >>> import paddle
  1790. >>> paddle.disable_static()
  1791. >>> x = paddle.to_tensor([[[0, 1, 0],
  1792. >>> [ 1, 0, 1]]], dtype="float32", stop_gradient=False)
  1793. >>> output = paddle.nn.functional.label_smooth(x)
  1794. >>> print(output)
  1795. Tensor(shape=[1, 2, 3], dtype=float32, place=Place(cpu), stop_gradient=False,
  1796. [[[0.03333334, 0.93333334, 0.03333334],
  1797. [0.93333334, 0.03333334, 0.93333334]]])
  1798. """
  1799. if epsilon > 1.0 or epsilon < 0.0:
  1800. raise ValueError("The value of epsilon must be between 0 and 1.")
  1801. if in_dynamic_or_pir_mode():
  1802. return _C_ops.label_smooth(label, prior_dist, float(epsilon))
  1803. check_variable_and_dtype(
  1804. label,
  1805. 'label',
  1806. ['uint16', 'float16', 'float32', 'float64'],
  1807. 'label_smooth',
  1808. )
  1809. helper = LayerHelper("label_smooth", **locals())
  1810. label.stop_gradient = True
  1811. smooth_label = helper.create_variable_for_type_inference(label.dtype)
  1812. helper.append_op(
  1813. type="label_smooth",
  1814. inputs={"X": label, "PriorDist": prior_dist}
  1815. if prior_dist
  1816. else {"X": label},
  1817. outputs={"Out": smooth_label},
  1818. attrs={"epsilon": float(epsilon)},
  1819. )
  1820. return smooth_label
  1821. def class_center_sample(label, num_classes, num_samples, group=None):
  1822. """
  1823. Class center sample method is proposed from the paper PartialFC that only sample a subset of the class centers.
  1824. The process of sampling subset class centers is straightforward:
  1825. 1. First select the positive class centers;
  1826. 2. Then randomly sample negative class centers.
  1827. Specifically, given a label tensor, shape [batch_size], select all the positive class centers and randomly
  1828. sample negative class centers, then remap the input label tensor using the sampled class centers.
  1829. For more information, Partial FC: Training 10 Million Identities on a Single Machine
  1830. arxiv: https://arxiv.org/abs/2010.05222
  1831. Note:
  1832. If the number of the positive class centers is greater than the input num_samples, it keeps all the positive
  1833. class centers and the shape of sampled_class_center will be [num_positive_class_centers].
  1834. The API supports CPU, single GPU and multi GPU.
  1835. For data parallel mode, set ``group=False``.
  1836. For model parallel mode, set ``group=None`` or the group instance return by paddle.distributed.new_group.
  1837. Args:
  1838. label (Tensor): 1-D tensor with shape [N], each label in [0, num_classes)
  1839. num_classes (int): A positive integer to specify the number of classes at local rank.
  1840. Note that num_classes of each GPU can be different.
  1841. num_samples (int): A positive integer to specify the number of class center to sample.
  1842. group (Group, optional): The group instance return by paddle.distributed.new_group
  1843. or ``None`` for global default group or ``False`` for data parallel (do not communication cross ranks).
  1844. Default is ``None``.
  1845. Returns:
  1846. Tuple of two ``Tensor`` : (remapped_label, sampled_class_center), remapped label using sampled class center,
  1847. sampled class center from [0, num_classes).
  1848. Examples:
  1849. .. code-block:: python
  1850. :name: code-example1
  1851. >>> # CPU or single GPU
  1852. >>> import paddle
  1853. >>> num_classes = 20
  1854. >>> batch_size = 10
  1855. >>> num_samples = 6
  1856. >>> paddle.seed(2023)
  1857. >>> label = paddle.randint(low=0, high=num_classes, shape=[batch_size], dtype='int64')
  1858. >>> remapped_label, sampled_class_index = paddle.nn.functional.class_center_sample(label, num_classes, num_samples)
  1859. >>> print(label)
  1860. Tensor(shape=[10], dtype=int64, place=Place(cpu), stop_gradient=True,
  1861. [17, 10, 5 , 18, 8 , 8 , 19, 14, 10, 14])
  1862. >>> print(remapped_label)
  1863. Tensor(shape=[10], dtype=int64, place=Place(cpu), stop_gradient=True,
  1864. [4, 2, 0, 5, 1, 1, 6, 3, 2, 3])
  1865. >>> print(sampled_class_index)
  1866. Tensor(shape=[7], dtype=int64, place=Place(cpu), stop_gradient=True,
  1867. [5 , 8 , 10, 14, 17, 18, 19])
  1868. .. code-block:: python
  1869. :name: code-example2
  1870. >>> # doctest: +REQUIRES(env:DISTRIBUTED)
  1871. >>> # required: distributed
  1872. >>> # Multi GPU, test_class_center_sample.py
  1873. >>> import paddle
  1874. >>> import paddle.distributed as dist
  1875. >>> strategy = dist.fleet.DistributedStrategy()
  1876. >>> dist.fleet.init(is_collective=True, strategy=strategy)
  1877. >>> batch_size = 10
  1878. >>> num_samples = 6
  1879. >>> rank_id = dist.get_rank()
  1880. >>> # num_classes of each GPU can be different, e.g num_classes_list = [10, 8]
  1881. >>> num_classes_list = [10, 10]
  1882. >>> num_classes = paddle.sum(paddle.to_tensor(num_classes_list))
  1883. >>> label = paddle.randint(low=0, high=num_classes.item(), shape=[batch_size], dtype='int64')
  1884. >>> label_list = []
  1885. >>> dist.all_gather(label_list, label)
  1886. >>> label = paddle.concat(label_list, axis=0)
  1887. >>> remapped_label, sampled_class_index = paddle.nn.functional.class_center_sample(label, num_classes_list[rank_id], num_samples)
  1888. >>> print(label)
  1889. >>> print(remapped_label)
  1890. >>> print(sampled_class_index)
  1891. >>> #python -m paddle.distributed.launch --gpus=0,1 test_class_center_sample.py
  1892. >>> # rank 0 output:
  1893. Tensor(shape=[20], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
  1894. [10, 17, 15, 11, 9 , 12, 18, 18, 17, 18, 19, 2 , 8 , 13, 11, 13, 9 , 10, 0 , 4 ])
  1895. Tensor(shape=[20], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
  1896. [6 , 11, 10, 7 , 4 , 8 , 12, 12, 11, 12, 13, 1 , 3 , 9 , 7 , 9 , 4 , 6 , 0 , 2 ])
  1897. Tensor(shape=[6], dtype=int64, place=CUDAPlace(0), stop_gradient=True,
  1898. [0, 2, 4, 8, 9, 3])
  1899. >>> # rank 1 output:
  1900. Tensor(shape=[20], dtype=int64, place=CUDAPlace(1), stop_gradient=True,
  1901. [10, 17, 15, 11, 9 , 12, 18, 18, 17, 18, 19, 2 , 8 , 13, 11, 13, 9 , 10, 0 , 4 ])
  1902. Tensor(shape=[20], dtype=int64, place=CUDAPlace(1), stop_gradient=True,
  1903. [6 , 11, 10, 7 , 4 , 8 , 12, 12, 11, 12, 13, 1 , 3 , 9 , 7 , 9 , 4 , 6 , 0 , 2 ])
  1904. Tensor(shape=[7], dtype=int64, place=CUDAPlace(1), stop_gradient=True,
  1905. [0, 1, 2, 3, 5, 7, 8])
  1906. """
  1907. if not (group is False or group is None or hasattr(group, 'is_member')):
  1908. raise ValueError(
  1909. f'Expected group is False, None or instance of paddle.distributed.collective.Group \
  1910. (got group: {group})'
  1911. )
  1912. return
  1913. if hasattr(group, 'is_member') and not group.is_member():
  1914. return
  1915. ring_id = 0
  1916. rank = 0
  1917. nranks = 1
  1918. if group is not False:
  1919. if core.is_compiled_with_dist():
  1920. parallel_env = paddle.distributed.ParallelEnv()
  1921. global_rank = parallel_env.rank
  1922. rank = (
  1923. global_rank
  1924. if group is None
  1925. else group.get_group_rank(global_rank)
  1926. )
  1927. nranks = parallel_env.world_size if group is None else group.nranks
  1928. if num_samples > num_classes:
  1929. raise ValueError(
  1930. f'Expected num_samples less than or equal to {num_classes}, got num_samples {num_samples}'
  1931. )
  1932. label_size = 1
  1933. for dim in list(label.shape):
  1934. label_size *= dim
  1935. if label_size != -1 and label_size < 1:
  1936. raise ValueError(
  1937. f'Expected label_size > 0 \
  1938. (got label_size: {label_size})'
  1939. )
  1940. label_dims = len(list(label.shape))
  1941. if label_dims != 1:
  1942. raise ValueError(
  1943. f'Expected label_dims == 1 \
  1944. (got label_dims: {label_dims})'
  1945. )
  1946. seed = None
  1947. if (seed is None or seed == 0) and default_main_program().random_seed != 0:
  1948. seed = default_main_program().random_seed
  1949. if in_dynamic_or_pir_mode():
  1950. return _C_ops.class_center_sample(
  1951. label,
  1952. num_classes,
  1953. num_samples,
  1954. ring_id,
  1955. rank,
  1956. nranks,
  1957. seed is not None,
  1958. seed if seed is not None else 0,
  1959. )
  1960. check_variable_and_dtype(
  1961. label, 'label', ['int64', 'int32'], 'class_center_sample'
  1962. )
  1963. op_type = 'class_center_sample'
  1964. helper = LayerHelper(op_type, **locals())
  1965. remapped_label = helper.create_variable_for_type_inference(
  1966. dtype=label.dtype
  1967. )
  1968. sampled_class_center = helper.create_variable_for_type_inference(
  1969. dtype=label.dtype
  1970. )
  1971. helper.append_op(
  1972. type=op_type,
  1973. inputs={'Label': label},
  1974. outputs={
  1975. 'RemappedLabel': remapped_label,
  1976. 'SampledLocalClassCenter': sampled_class_center,
  1977. },
  1978. attrs={
  1979. 'num_classes': num_classes,
  1980. 'num_samples': num_samples,
  1981. 'ring_id': ring_id,
  1982. 'nranks': nranks,
  1983. 'rank': rank,
  1984. 'fix_seed': seed is not None,
  1985. 'seed': seed if seed is not None else 0,
  1986. },
  1987. )
  1988. return remapped_label, sampled_class_center
  1989. def fold(
  1990. x, output_sizes, kernel_sizes, strides=1, paddings=0, dilations=1, name=None
  1991. ):
  1992. r"""
  1993. Combines an array of sliding local blocks into a large containing
  1994. tensor. also known as col2im when operated on batched 2D image tensor. Fold calculates each
  1995. combined value in the resulting large tensor by summing all values from all containing blocks.
  1996. For each input :math:`x` with shape [N, C_in , L], the output shape [N, C_out, H_out, W_out]
  1997. can be calculated as following.
  1998. .. math::
  1999. H_{out} &= output\_size[0] \\
  2000. W_{out} &= output\_size[1] \\
  2001. C_{out} &= \frac{C_{in}}{kernel\_sizes[0]\times kernel\_sizes[1]} \\
  2002. Parameters:
  2003. x(Tensor): 3-D Tensor, input tensor of format [N, C, L],
  2004. data type can be float32, float64, complex64 or complex128
  2005. output_sizes(int|list|tuple): The size of output size, should be [output_size_h, output_size_w]
  2006. or an integer o treated as [o, o].
  2007. kernel_sizes(int|list|tuple): The size of convolution kernel, should be [k_h, k_w]
  2008. or an integer k treated as [k, k].
  2009. strides(int|list|tuple, optional): The strides, should be [stride_h, stride_w]
  2010. or an integer stride treated as [stride, stride].
  2011. For default, strides will be [1, 1].
  2012. paddings(int|list|tuple, optional): The paddings of each dimension, should be
  2013. [padding_top, padding_left, padding_bottom, padding_right]
  2014. or [padding_h, padding_w] or an integer padding.
  2015. If [padding_h, padding_w] was given, it will expanded to
  2016. [padding_h, padding_w, padding_h, padding_w]. If an integer
  2017. padding was given, [padding, padding, padding, padding] will
  2018. be used. For default, paddings will be [0, 0, 0, 0]
  2019. dilations(int|list|tuple, optional): the dilations of convolution kernel, should be
  2020. [dilation_h, dilation_w], or an integer dilation treated as
  2021. [dilation, dilation]. For default, it will be [1, 1].
  2022. name(str, optional): The default value is None.
  2023. Normally there is no need for user to set this property.
  2024. For more information, please refer to :ref:`api_guide_Name`
  2025. Returns:
  2026. The tensor formed by combining a group of sliding local blocks
  2027. The output shape is [N, Cout, H, W] as described above.
  2028. Examples:
  2029. .. code-block:: python
  2030. >>> import paddle
  2031. >>> import paddle.nn.functional as F
  2032. >>> x = paddle.randn([2,3*2*2,12])
  2033. >>> y = F.fold(x, output_sizes=[4, 5], kernel_sizes=2)
  2034. >>> x = paddle.randn([2,3*2*2,12])
  2035. >>> y = F.fold(x, output_sizes=[4, 5], kernel_sizes=2)
  2036. >>> print(y.shape)
  2037. [2, 3, 4, 5]
  2038. """
  2039. helper = LayerHelper("fold", **locals())
  2040. check_variable_and_dtype(
  2041. x, 'x', ['float32', 'float64', 'complex64', 'complex128'], 'fold'
  2042. )
  2043. assert len(x.shape) == 3, "input should be the format of [N, C, L]"
  2044. def _is_list_or_tuple_(data):
  2045. return isinstance(data, (list, tuple))
  2046. if isinstance(output_sizes, int):
  2047. output_sizes = [output_sizes, output_sizes]
  2048. else:
  2049. assert _is_list_or_tuple_(output_sizes) and (
  2050. len(output_sizes) == 2
  2051. ), "output_sizes should either be an integer or a list/tuple of two integers"
  2052. if isinstance(kernel_sizes, int):
  2053. kernel_sizes = [kernel_sizes, kernel_sizes]
  2054. else:
  2055. assert _is_list_or_tuple_(kernel_sizes) and (
  2056. len(kernel_sizes) == 2
  2057. ), "kernel_sizes should either be an integer or a list/tuple of two integers"
  2058. if isinstance(strides, int):
  2059. strides = [strides, strides]
  2060. else:
  2061. assert _is_list_or_tuple_(strides) and (
  2062. len(strides) == 2
  2063. ), "strides should either be an integer or a list/tuple of two integers"
  2064. if isinstance(dilations, int):
  2065. dilations = [dilations, dilations]
  2066. else:
  2067. assert _is_list_or_tuple_(dilations) and (
  2068. len(dilations) == 2
  2069. ), "dilations should either be an integer or a list/tuple of two integers"
  2070. if isinstance(paddings, int):
  2071. paddings = [paddings] * 4
  2072. elif isinstance(paddings, list):
  2073. if len(paddings) == 2:
  2074. paddings = paddings * 2
  2075. elif len(paddings) == 4:
  2076. pass
  2077. else:
  2078. raise ValueError(
  2079. "paddings should either be an integer or a list of 2 or 4 integers"
  2080. )
  2081. else:
  2082. raise ValueError(
  2083. "Unexpected type of paddings, it should be either an integer or a list"
  2084. "of 2 or 4 integers"
  2085. )
  2086. if in_dynamic_or_pir_mode():
  2087. out = _C_ops.fold(
  2088. x, output_sizes, kernel_sizes, strides, paddings, dilations
  2089. )
  2090. else:
  2091. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  2092. helper.append_op(
  2093. type="fold",
  2094. inputs={"X": x},
  2095. outputs={"Y": out},
  2096. attrs={
  2097. "output_sizes": output_sizes,
  2098. "kernel_sizes": kernel_sizes,
  2099. "strides": strides,
  2100. "paddings": paddings,
  2101. "dilations": dilations,
  2102. },
  2103. )
  2104. return out