activation.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846
  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 paddle
  15. from paddle import _C_ops, _legacy_C_ops, in_dynamic_mode
  16. from paddle.framework import core, in_dynamic_or_pir_mode
  17. from paddle.utils.inplace_utils import inplace_apis_in_dygraph_only
  18. from ...base.data_feeder import check_dtype, check_variable_and_dtype
  19. from ...base.framework import convert_np_dtype_to_dtype_
  20. from ...base.layer_helper import LayerHelper
  21. from ...tensor.manipulation import chunk
  22. from ...tensor.math import tanh, tanh_ # noqa: F401
  23. from ...tensor.ops import sigmoid
  24. __all__ = []
  25. def celu(x, alpha=1.0, name=None):
  26. r"""
  27. celu activation.
  28. Apply the following operation to each element of the input Tensor according to the `Continuously Differentiable Exponential Linear Units <https://arxiv.org/abs/1704.07483>`_.
  29. .. math::
  30. \operatorname{celu}(x) = \max(0, x) + \min(0, \alpha * (\mathrm{e}^{x/\alpha}-1))
  31. Parameters:
  32. x (Tensor): The input Tensor with data type float16, float32, or float64.
  33. alpha (float, optional): The 'alpha' value of the CELU formula. Default is 1.0.
  34. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  35. Returns:
  36. A ``Tensor`` with the same data type and shape as ``x`` .
  37. Examples:
  38. .. code-block:: python
  39. >>> import paddle
  40. >>> import paddle.nn.functional as F
  41. >>> x = paddle.to_tensor([[-1., 6.], [1., 15.6]])
  42. >>> out = F.celu(x, alpha=0.2)
  43. >>> print(out)
  44. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  45. [[-0.19865242, 6. ],
  46. [ 1. , 15.60000038]])
  47. """
  48. if alpha == 0:
  49. raise ZeroDivisionError("alpha cannot be 0 for celu")
  50. if in_dynamic_or_pir_mode():
  51. return _C_ops.celu(x, alpha)
  52. else:
  53. check_variable_and_dtype(
  54. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'celu'
  55. )
  56. helper = LayerHelper("celu", **locals())
  57. out = helper.create_variable_for_type_inference(x.dtype)
  58. helper.append_op(
  59. type='celu',
  60. inputs={'X': x},
  61. outputs={'Out': out},
  62. attrs={'alpha': alpha},
  63. )
  64. return out
  65. def elu(x, alpha=1.0, name=None):
  66. r"""
  67. elu activation.
  68. .. math::
  69. elu(x)=
  70. \left\{
  71. \begin{array}{lcl}
  72. x,& &\text{if } \ x > 0 \\
  73. alpha * (e^{x} - 1),& &\text{if } \ x <= 0
  74. \end{array}
  75. \right.
  76. Parameters:
  77. x (Tensor): The input Tensor with data type float32, float64.
  78. alpha (float, optional): The 'alpha' value of the ELU formulation. Default is 1.0.
  79. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  80. Returns:
  81. A Tensor with the same data type and shape as ``x`` .
  82. Examples:
  83. .. code-block:: python
  84. >>> import paddle
  85. >>> import paddle.nn.functional as F
  86. >>> x = paddle.to_tensor([[-1., 6.], [1., 15.6]])
  87. >>> out = F.elu(x, alpha=0.2)
  88. >>> print(out)
  89. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  90. [[-0.12642412, 6. ],
  91. [ 1. , 15.60000038]])
  92. """
  93. if in_dynamic_or_pir_mode():
  94. return _C_ops.elu(x, alpha)
  95. else:
  96. check_variable_and_dtype(
  97. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'elu'
  98. )
  99. helper = LayerHelper("elu", **locals())
  100. out = helper.create_variable_for_type_inference(x.dtype)
  101. helper.append_op(
  102. type='elu',
  103. inputs={'X': x},
  104. outputs={'Out': out},
  105. attrs={'alpha': alpha},
  106. )
  107. return out
  108. @inplace_apis_in_dygraph_only
  109. def elu_(x, alpha=1.0, name=None):
  110. r"""
  111. Inplace version of ``elu`` API, the output Tensor will be inplaced with input ``x``.
  112. Please refer to :ref:`api_paddle_nn_functional_elu`.
  113. """
  114. assert alpha >= 0.0, "elu_ only support alpha >= 0, please use elu instead."
  115. if in_dynamic_mode():
  116. return _C_ops.elu_(x, alpha)
  117. return _legacy_C_ops.elu_(x, 'alpha', alpha)
  118. def gelu(x, approximate=False, name=None):
  119. r"""
  120. gelu activation.
  121. The activation function of Gelu is calculated element by element. More information refers to :ref: `Gaussian Error Linear Units`.
  122. if approximate is True
  123. .. math::
  124. gelu(x) = 0.5 * x * (1 + tanh(\sqrt{\frac{2}{\pi}} * (x + 0.044715x^{3})))
  125. else
  126. .. math::
  127. gelu(x) = 0.5 * x * (1 + erf(\frac{x}{\sqrt{2}}))
  128. Parameters:
  129. x (Tensor): The input Tensor with data type float32, float64.
  130. approximate (bool, optional): Whether to enable approximation. Default is False.
  131. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  132. Returns:
  133. A Tensor with the same data type and shape as ``x`` .
  134. Examples:
  135. .. code-block:: python
  136. >>> import paddle
  137. >>> import paddle.nn.functional as F
  138. >>> x = paddle.to_tensor([[-1, 0.5], [1, 1.5]])
  139. >>> out1 = F.gelu(x)
  140. >>> print(out1)
  141. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  142. [[-0.15865529, 0.34573123],
  143. [ 0.84134471, 1.39978933]])
  144. >>> out2 = F.gelu(x, True)
  145. >>> print(out2)
  146. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  147. [[-0.15880796, 0.34571400],
  148. [ 0.84119201, 1.39957154]])
  149. """
  150. if in_dynamic_or_pir_mode():
  151. return _C_ops.gelu(x, approximate)
  152. else:
  153. check_variable_and_dtype(
  154. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'gelu'
  155. )
  156. helper = LayerHelper("gelu", **locals())
  157. out = helper.create_variable_for_type_inference(x.dtype)
  158. helper.append_op(
  159. type='gelu',
  160. inputs={'X': x},
  161. outputs={'Out': out},
  162. attrs={'approximate': approximate},
  163. )
  164. return out
  165. def hardshrink(x, threshold=0.5, name=None):
  166. r"""
  167. hard shrinkage activation
  168. .. math::
  169. hardshrink(x)=
  170. \left\{
  171. \begin{array}{rcl}
  172. x,& &if \ {x > threshold} \\
  173. x,& &if \ {x < -threshold} \\
  174. 0,& &if \ {others} &
  175. \end{array}
  176. \right.
  177. Args:
  178. x (Tensor): The input Tensor with data type float32, float64.
  179. threshold (float, optional): The value of threshold for hardthrink. Default is 0.5.
  180. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  181. Returns:
  182. A Tensor with the same data type and shape as ``x`` .
  183. Examples:
  184. .. code-block:: python
  185. >>> import paddle
  186. >>> import paddle.nn.functional as F
  187. >>> x = paddle.to_tensor([-1, 0.3, 2.5])
  188. >>> out = F.hardshrink(x)
  189. >>> print(out)
  190. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  191. [-1. , 0. , 2.50000000])
  192. """
  193. if in_dynamic_or_pir_mode():
  194. return _C_ops.hardshrink(x, threshold)
  195. else:
  196. check_variable_and_dtype(
  197. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'hardshrink'
  198. )
  199. helper = LayerHelper('hardshrink', **locals())
  200. out = helper.create_variable_for_type_inference(x.dtype)
  201. helper.append_op(
  202. type='hard_shrink',
  203. inputs={'X': x},
  204. outputs={'Out': out},
  205. attrs={'threshold': threshold},
  206. )
  207. return out
  208. def hardtanh(x, min=-1.0, max=1.0, name=None):
  209. r"""
  210. hardtanh activation. Calculate the `hardtanh` of input `x`.
  211. .. math::
  212. hardtanh(x)=
  213. \left\{
  214. \begin{array}{cll}
  215. max,& & \text{if } x > max \\
  216. min,& & \text{if } x < min \\
  217. x,& & \text{otherwise}
  218. \end{array}
  219. \right.
  220. Parameters:
  221. x (Tensor): The input Tensor with data type float32, float64.
  222. min (float, optional): The minimum value of the linear region range. Default is -1.
  223. max (float, optional): The maximum value of the linear region range. Default is 1.
  224. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  225. Returns:
  226. A Tensor with the same data type and shape as ``x`` .
  227. Examples:
  228. .. code-block:: python
  229. >>> import paddle
  230. >>> import paddle.nn.functional as F
  231. >>> x = paddle.to_tensor([-1.5, 0.3, 2.5])
  232. >>> out = F.hardtanh(x)
  233. >>> print(out)
  234. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  235. [-1. , 0.30000001, 1. ])
  236. """
  237. if in_dynamic_or_pir_mode():
  238. return _C_ops.hardtanh(x, min, max)
  239. else:
  240. check_variable_and_dtype(
  241. x, 'x', ['float16', 'float32', 'float64'], 'hardtanh'
  242. )
  243. helper = LayerHelper('hardtanh', **locals())
  244. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  245. helper.append_op(
  246. type='brelu',
  247. inputs={'X': x},
  248. outputs={'Out': out},
  249. attrs={'t_min': min, 't_max': max},
  250. )
  251. return out
  252. @inplace_apis_in_dygraph_only
  253. def hardtanh_(x, min=-1.0, max=1.0, name=None):
  254. r"""
  255. Inplace version of ``hardtanh`` API, the output Tensor will be inplaced with input ``x``.
  256. Please refer to :ref:`api_paddle_nn_functional_hardtanh`.
  257. """
  258. if in_dynamic_mode():
  259. return _C_ops.hardtanh_(x, min, max)
  260. def hardsigmoid(x, slope=0.1666667, offset=0.5, name=None):
  261. r"""
  262. hardsigmoid activation. Calculate the `hardsigmoid` of input `x`.
  263. A 3-part piecewise linear approximation of sigmoid(https://arxiv.org/abs/1603.00391),
  264. which is much faster than sigmoid.
  265. .. math::
  266. hardsigmoid(x)=
  267. \left\{
  268. \begin{array}{lcl}
  269. 0, & &\text{if } \ x \leq -3 \\
  270. 1, & &\text{if } \ x \geq 3 \\
  271. slope * x + offset, & &\text{otherwise}
  272. \end{array}
  273. \right.
  274. Parameters:
  275. x (Tensor): The input Tensor with data type float32, float64.
  276. slope (float, optional): The slope of hardsigmoid function. Default is 0.1666667.
  277. offset (float, optional): The offset of hardsigmoid function. Default is 0.5.
  278. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  279. Returns:
  280. A Tensor with the same data type and shape as ``x`` .
  281. Examples:
  282. .. code-block:: python
  283. >>> import paddle
  284. >>> import paddle.nn.functional as F
  285. >>> x = paddle.to_tensor([-4., 5., 1.])
  286. >>> out = F.hardsigmoid(x)
  287. >>> print(out)
  288. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  289. [0. , 1. , 0.66666669])
  290. """
  291. if in_dynamic_or_pir_mode():
  292. return _C_ops.hardsigmoid(x, slope, offset)
  293. else:
  294. check_variable_and_dtype(
  295. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'hardsigmoid'
  296. )
  297. helper = LayerHelper('hardsigmoid', **locals())
  298. out = helper.create_variable_for_type_inference(x.dtype)
  299. helper.append_op(
  300. type='hard_sigmoid',
  301. inputs={'X': x},
  302. outputs={'Out': out},
  303. attrs={'slope': slope, 'offset': offset},
  304. )
  305. return out
  306. def hardswish(x, name=None):
  307. r"""
  308. hardswish activation. hardswish is proposed in MobileNetV3, and performs
  309. better in computational stability and efficiency compared to swish function.
  310. For more details please refer to: https://arxiv.org/pdf/1905.02244.pdf
  311. .. math::
  312. hardswish(x)=
  313. \left\{
  314. \begin{array}{cll}
  315. 0 &, & \text{if } x \leq -3 \\
  316. x &, & \text{if } x \geq 3 \\
  317. \frac{x(x+3)}{6} &, & \text{otherwise}
  318. \end{array}
  319. \right.
  320. Parameters:
  321. x (Tensor): The input Tensor with data type float32, float64.
  322. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  323. Returns:
  324. A Tensor with the same data type and shape as ``x`` .
  325. Examples:
  326. .. code-block:: python
  327. >>> import paddle
  328. >>> import paddle.nn.functional as F
  329. >>> x = paddle.to_tensor([-4., 5., 1.])
  330. >>> out = F.hardswish(x)
  331. >>> print(out)
  332. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  333. [-0. , 5. , 0.66666669])
  334. """
  335. if in_dynamic_or_pir_mode():
  336. return _C_ops.hardswish(x)
  337. else:
  338. check_variable_and_dtype(
  339. x,
  340. 'x',
  341. [
  342. 'float16',
  343. 'uint16',
  344. 'float32',
  345. 'float64',
  346. 'complex64',
  347. 'complex128',
  348. ],
  349. 'hardswish',
  350. )
  351. threshold = 6.0
  352. scale = 6.0
  353. offset = 3.0
  354. helper = LayerHelper('hardswish', **locals())
  355. out = helper.create_variable_for_type_inference(x.dtype)
  356. helper.append_op(
  357. type='hard_swish',
  358. inputs={'X': x},
  359. outputs={'Out': out},
  360. attrs={'threshold': threshold, 'scale': scale, 'offset': offset},
  361. )
  362. return out
  363. def leaky_relu(x, negative_slope=0.01, name=None):
  364. r"""
  365. leaky_relu activation. The calculation formula is:
  366. .. math::
  367. leaky\_relu(x)=
  368. \left\{
  369. \begin{array}{rcl}
  370. x, & & if \ x >= 0 \\
  371. negative\_slope * x, & & otherwise \\
  372. \end{array}
  373. \right.
  374. Args:
  375. x (Tensor): The input Tensor with data type float32, float64.
  376. negative_slope (float, optional): Slope of the activation function at
  377. :math:`x < 0` . Default is 0.01.
  378. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  379. Returns:
  380. A Tensor with the same data type and shape as ``x`` .
  381. Examples:
  382. .. code-block:: python
  383. >>> import paddle
  384. >>> import paddle.nn.functional as F
  385. >>> x = paddle.to_tensor([-2., 0., 1.])
  386. >>> out = F.leaky_relu(x)
  387. >>> print(out)
  388. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  389. [-0.02000000, 0. , 1. ])
  390. """
  391. if in_dynamic_or_pir_mode():
  392. return _C_ops.leaky_relu(x, negative_slope)
  393. else:
  394. check_variable_and_dtype(
  395. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'leaky_relu'
  396. )
  397. helper = LayerHelper('leaky_relu', **locals())
  398. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  399. helper.append_op(
  400. type='leaky_relu',
  401. inputs={'X': x},
  402. outputs={'Out': out},
  403. attrs={'alpha': negative_slope},
  404. )
  405. return out
  406. @inplace_apis_in_dygraph_only
  407. def leaky_relu_(x, negative_slope=0.01, name=None):
  408. r"""
  409. Inplace version of ``leaky_relu`` API, the output Tensor will be inplaced with input ``x``.
  410. Please refer to :ref:`api_paddle_nn_functional_leaky_relu`.
  411. """
  412. if in_dynamic_mode():
  413. return _C_ops.leaky_relu_(x, negative_slope)
  414. def prelu(x, weight, data_format="NCHW", name=None):
  415. """
  416. prelu activation. The calculation formula is follows:
  417. .. math::
  418. prelu(x) = max(0, x) + weight * min(0, x)
  419. x and weight is input Tensor.
  420. Parameters:
  421. x (Tensor): The input Tensor with data type float32, float64.
  422. weight (Tensor): The learnable parameter with data type same as ``x``.
  423. The weight shape is [], [1] or [in], where `in` is the input channel of ``x``.
  424. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  425. data_format(str, optional): Data format that specifies the layout of input.
  426. It may be "NC", "NCL", "NCHW", "NCDHW", "NLC", "NHWC" or "NDHWC". Default: "NCHW".
  427. Returns:
  428. A Tensor with the same data type and shape as ``x`` .
  429. Examples:
  430. .. code-block:: python
  431. >>> import paddle
  432. >>> import paddle.nn.functional as F
  433. >>> data = paddle.to_tensor([[[[-2.0, 3.0, -4.0, 5.0],
  434. ... [ 3.0, -4.0, 5.0, -6.0],
  435. ... [-7.0, -8.0, 8.0, 9.0]],
  436. ... [[ 1.0, -2.0, -3.0, 4.0],
  437. ... [-5.0, 6.0, 7.0, -8.0],
  438. ... [ 6.0, 7.0, 8.0, 9.0]]]], dtype='float32')
  439. >>> w = paddle.to_tensor([0.25], dtype='float32')
  440. >>> out = F.prelu(data, w)
  441. >>> print(out)
  442. Tensor(shape=[1, 2, 3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  443. [[[[-0.50000000, 3. , -1. , 5. ],
  444. [ 3. , -1. , 5. , -1.50000000],
  445. [-1.75000000, -2. , 8. , 9. ]],
  446. [[ 1. , -0.50000000, -0.75000000, 4. ],
  447. [-1.25000000, 6. , 7. , -2. ],
  448. [ 6. , 7. , 8. , 9. ]]]])
  449. """
  450. assert (
  451. len(weight.shape) == 0 or len(weight.shape) == 1
  452. ), "The dim count of weight shape should be 0 or 1 in prelu()."
  453. mode = 'all'
  454. if len(weight.shape) == 1 and weight.shape[0] > 1:
  455. true_data_format = [
  456. 'NC',
  457. 'NCL',
  458. 'NCHW',
  459. 'NCDHW',
  460. 'NLC',
  461. 'NHWC',
  462. 'NDHWC',
  463. ]
  464. if data_format not in true_data_format:
  465. raise ValueError(
  466. "data_format must be one of 'NC', 'NCL', 'NCHW', 'NCDHW', "
  467. f"'NLC', 'NHWC', 'NDHWC' but receive {data_format}"
  468. )
  469. data_format = 'NCHW' if data_format[1] == 'C' else 'NHWC'
  470. assert (
  471. len(x.shape) > 1
  472. ), "The dim count of x should be equal or larger than 2 in prelu() when weight shape is not [1]."
  473. # NOTE(GuoxiaWang): support NHWC data format
  474. if data_format == 'NHWC':
  475. assert (
  476. weight.shape[0] == x.shape[-1]
  477. ), "The weight size should be equal to x input channel in prelu() when weight shape is not [1]."
  478. else:
  479. assert (
  480. weight.shape[0] == x.shape[1]
  481. ), "The weight size should be equal to x input channel in prelu() when weight shape is not [1]."
  482. mode = 'channel'
  483. if in_dynamic_or_pir_mode():
  484. return _C_ops.prelu(x, weight, data_format, mode)
  485. else:
  486. check_variable_and_dtype(
  487. x, 'x', ['float16', 'float32', 'float64', 'uint16'], 'prelu'
  488. )
  489. check_variable_and_dtype(
  490. weight,
  491. 'weight',
  492. ['float16', 'float32', 'float64', 'uint16'],
  493. 'prelu',
  494. )
  495. helper = LayerHelper('prelu', **locals())
  496. out = helper.create_variable_for_type_inference(x.dtype)
  497. helper.append_op(
  498. type="prelu",
  499. inputs={"X": x, "Alpha": weight},
  500. outputs={"Out": out},
  501. attrs={"mode": mode, "data_format": data_format},
  502. )
  503. return out
  504. def rrelu(x, lower=1.0 / 8.0, upper=1.0 / 3.0, training=True, name=None):
  505. r"""
  506. rrelu activation.
  507. Applies the randomized leaky rectified liner unit function to improve generalization performance,
  508. as described in the paper:
  509. `Empirical Evaluation of Rectified Activations in Convolutional Network <https://arxiv.org/abs/1505.00853>`_
  510. During training, randomly samples the negative slope for activation values as described below:
  511. .. math::
  512. rrelu(x)=
  513. \left\{
  514. \begin{array}{rcl}
  515. x, & & if \ x >= 0 \\
  516. a * x, & & otherwise \\
  517. \end{array}
  518. \right.
  519. where :math:`x` is the input tensor,
  520. :math:`a` is randomly sampled from uniform distribution in range (:math:`lower`, :math:`upper`),
  521. In the test phase, the negative slope will take the average value of :math:`lower` and :math:`upper`:
  522. .. math::
  523. rrelu(x)=
  524. \left\{
  525. \begin{array}{rcl}
  526. x, & & if \ x >= 0 \\
  527. (lower + upper) * 0.5 * x, & & otherwise \\
  528. \end{array}
  529. \right.
  530. where :math:`x` is the input tensor,
  531. :math:`lower` and :math:`upper` are the bounds of uniform distribution.
  532. Parameters:
  533. x (Tensor): The input Tensor with data type float16, float32, float64.
  534. lower (float, optional): The lower bound of uniform distribution. Default: 0.125.
  535. upper (float, optional): The upper bound of uniform distribution. Default: 0.3333333333333333.
  536. training (bool, optional): Current mode is in training or others. Default is True.
  537. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  538. Returns:
  539. A Tensor with the same data type and shape as ``x`` .
  540. Examples:
  541. .. code-block:: python
  542. >>> import paddle
  543. >>> import paddle.nn.functional as F
  544. >>> paddle.seed(1)
  545. >>> input_tensor = paddle.to_tensor([[[[-2.0, 3.0, -4.0, 5.0],
  546. ... [ 3.0, -4.0, 5.0, -6.0],
  547. ... [-7.0, -8.0, 8.0, 9.0]],
  548. ... [[ 1.0, -2.0, -3.0, 4.0],
  549. ... [-5.0, 6.0, 7.0, -8.0],
  550. ... [ 6.0, 7.0, 8.0, 9.0]]]], dtype='float32')
  551. >>> out = F.rrelu(input_tensor, 0.1, 0.3)
  552. >>> print(out)
  553. Tensor(shape=[1, 2, 3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  554. [[[[-0.20715050, 3. , -1.01193857, 5. ],
  555. [ 3. , -0.94084597, 5. , -0.65544695],
  556. [-1.24268556, -2.34339547, 8. , 9. ]],
  557. [[ 1. , -0.44942653, -0.68969047, 4. ],
  558. [-1.03736508, 6. , 7. , -0.95799232],
  559. [ 6. , 7. , 8. , 9. ]]]])
  560. """
  561. if not isinstance(lower, float) or not isinstance(upper, float):
  562. raise TypeError(
  563. f"The lower and upper values must be float type. Received: lower {lower}, upper {upper}."
  564. )
  565. if lower < 0 or lower > 1:
  566. raise ValueError(
  567. f"The lower value must be no less than zero or greater than one. Received: {lower}."
  568. )
  569. if upper < lower:
  570. raise ValueError(
  571. f"The upper value must be greater than lower value. Received: lower {lower}, upper {upper}."
  572. )
  573. if upper > 1:
  574. raise ValueError(
  575. f"The upper value must be no greater than one. Received: {upper}."
  576. )
  577. is_test = not training
  578. if in_dynamic_or_pir_mode():
  579. return _C_ops.rrelu(x, lower, upper, is_test)
  580. else:
  581. check_variable_and_dtype(
  582. x, 'X', ['float16', 'uint16', 'float32', 'float64'], 'rrelu'
  583. )
  584. helper = LayerHelper('rrelu', **locals())
  585. out = helper.create_variable_for_type_inference(x.dtype)
  586. noise = helper.create_variable_for_type_inference(dtype=x.dtype)
  587. attrs = {'lower': lower, 'upper': upper, 'is_test': is_test}
  588. helper.append_op(
  589. type='rrelu',
  590. inputs={"X": x},
  591. outputs={"Out": out, "Noise": noise},
  592. attrs=attrs,
  593. )
  594. return out
  595. def relu(x, name=None):
  596. """
  597. relu activation. The calculation formula is follows:
  598. .. math::
  599. out = max(x, 0)
  600. x is input Tensor.
  601. Parameters:
  602. x (Tensor): The input Tensor with data type float32, float64.
  603. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  604. Returns:
  605. A Tensor with the same data type and shape as ``x`` .
  606. Examples:
  607. .. code-block:: python
  608. >>> import paddle
  609. >>> import paddle.nn.functional as F
  610. >>> x = paddle.to_tensor([-2, 0, 1], dtype='float32')
  611. >>> out = F.relu(x)
  612. >>> print(out)
  613. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  614. [0., 0., 1.])
  615. """
  616. if in_dynamic_or_pir_mode():
  617. return _C_ops.relu(x)
  618. else:
  619. check_variable_and_dtype(
  620. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'relu'
  621. )
  622. helper = LayerHelper('relu', **locals())
  623. out = helper.create_variable_for_type_inference(x.dtype)
  624. helper.append_op(type='relu', inputs={'X': x}, outputs={'Out': out})
  625. return out
  626. @inplace_apis_in_dygraph_only
  627. def relu_(x, name=None):
  628. """
  629. Inplace version of ``relu`` API, the output Tensor will be inplaced with input ``x``.
  630. Please refer to :ref:`api_paddle_nn_functional_relu`.
  631. """
  632. return _C_ops.relu_(x)
  633. def log_sigmoid(x, name=None):
  634. r"""
  635. log_sigmoid activation.
  636. .. math::
  637. log\_sigmoid(x) = log \frac{1}{1 + e^{-x}}
  638. Parameters:
  639. x (Tensor): The input Tensor with data type float32, float64, complex64, complex128.
  640. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  641. Returns:
  642. A Tensor with the same data type and shape as ``x`` .
  643. Examples:
  644. .. code-block:: python
  645. >>> import paddle
  646. >>> import paddle.nn.functional as F
  647. >>> x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
  648. >>> out = F.log_sigmoid(x)
  649. >>> print(out)
  650. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  651. [-0.31326166, -0.12692805, -0.04858733, -0.01814996])
  652. """
  653. if in_dynamic_or_pir_mode():
  654. return _C_ops.logsigmoid(x)
  655. else:
  656. check_variable_and_dtype(
  657. x,
  658. 'x',
  659. ['float16', 'float32', 'float64', 'complex64', 'complex128'],
  660. 'log_sigmoid',
  661. )
  662. helper = LayerHelper("log_sigmoid", **locals())
  663. out = helper.create_variable_for_type_inference(x.dtype)
  664. helper.append_op(
  665. type='logsigmoid', inputs={'X': x}, outputs={'Out': out}
  666. )
  667. return out
  668. def maxout(x, groups, axis=1, name=None):
  669. r"""
  670. maxout activation.
  671. Assumed the input shape is (N, Ci, H, W).
  672. The output shape is (N, Co, H, W).
  673. Then Co = Ci/groups and the operator formula is as follows:
  674. .. math::
  675. \begin{array}{l}
  676. &out_{si+j} = \max_{k} x_{gsi + sk + j} \\
  677. &g = groups \\
  678. &s = \frac{input.size}{num\_channels} \\
  679. &0 \le i < \frac{num\_channels}{groups} \\
  680. &0 \le j < s \\
  681. &0 \le k < groups
  682. \end{array}
  683. Parameters:
  684. x (Tensor): The input is 4-D Tensor with shape [N, C, H, W] or [N, H, W, C], the data type
  685. of input is float16, float32 or float64.
  686. groups (int): The groups number of maxout. `groups` specifies the
  687. index of channel dimension where maxout will be performed. This must be
  688. a factor of number of features.
  689. axis (int, optional): The axis along which to perform maxout calculations.
  690. It should be 1 when data format is NCHW, be -1 or 3 when data format
  691. is NHWC. If ``axis`` < 0, it works the same way as :math:`axis + D` ,
  692. where D is the dimensions of ``x`` . ``axis`` only supports 1, 3 or -1.
  693. Default is 1.
  694. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  695. Returns:
  696. A Tensor with the same data type as ``x`` .
  697. Examples:
  698. .. code-block:: python
  699. >>> import paddle
  700. >>> import paddle.nn.functional as F
  701. >>> paddle.seed(2023)
  702. >>> x = paddle.rand([1, 2, 3, 4])
  703. >>> print(x)
  704. Tensor(shape=[1, 2, 3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  705. [[[[0.86583614, 0.52014720, 0.25960937, 0.90525323],
  706. [0.42400089, 0.40641287, 0.97020894, 0.74437362],
  707. [0.51785129, 0.73292869, 0.97786582, 0.04315904]],
  708. [[0.42639419, 0.71958369, 0.20811461, 0.19731510],
  709. [0.38424349, 0.14603184, 0.22713774, 0.44607511],
  710. [0.21657862, 0.67685395, 0.46460176, 0.92382854]]]])
  711. >>> out = F.maxout(x, groups=2)
  712. >>> print(out)
  713. Tensor(shape=[1, 1, 3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  714. [[[[0.86583614, 0.71958369, 0.25960937, 0.90525323],
  715. [0.42400089, 0.40641287, 0.97020894, 0.74437362],
  716. [0.51785129, 0.73292869, 0.97786582, 0.92382854]]]])
  717. """
  718. if in_dynamic_or_pir_mode():
  719. return _C_ops.maxout(x, groups, axis)
  720. else:
  721. check_variable_and_dtype(
  722. x, 'x', ['float16', 'float32', 'float64'], 'maxout'
  723. )
  724. if axis not in [1, -1, 3]:
  725. raise ValueError(
  726. "Attr(axis) should be 1 when data format is NCHW, -1 or 3 when data format is NHWC. Received "
  727. "Attr(axis): %s." % str(axis)
  728. )
  729. if axis == -1:
  730. axis = 3
  731. helper = LayerHelper('maxout', **locals())
  732. out = helper.create_variable_for_type_inference(x.dtype)
  733. helper.append_op(
  734. type='maxout',
  735. inputs={'X': x},
  736. outputs={'Out': out},
  737. attrs={'groups': groups, 'axis': axis},
  738. )
  739. return out
  740. def relu6(x, name=None):
  741. """
  742. relu6 activation
  743. .. math::
  744. relu6(x) = min(max(0,x), 6)
  745. Parameters:
  746. x (Tensor): The input Tensor with data type float32, float64.
  747. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  748. Returns:
  749. A Tensor with the same data type and shape as ``x`` .
  750. Examples:
  751. .. code-block:: python
  752. >>> import paddle
  753. >>> import paddle.nn.functional as F
  754. >>> x = paddle.to_tensor([-1, 0.3, 6.5])
  755. >>> out = F.relu6(x)
  756. >>> print(out)
  757. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  758. [0. , 0.30000001, 6. ])
  759. """
  760. threshold = 6.0
  761. if in_dynamic_or_pir_mode():
  762. return _C_ops.relu6(x)
  763. check_variable_and_dtype(
  764. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'relu6'
  765. )
  766. helper = LayerHelper('relu6', **locals())
  767. out = helper.create_variable_for_type_inference(x.dtype)
  768. helper.append_op(
  769. type='relu6',
  770. inputs={'X': x},
  771. outputs={'Out': out},
  772. attrs={'threshold': threshold},
  773. )
  774. return out
  775. def selu(
  776. x,
  777. scale=1.0507009873554804934193349852946,
  778. alpha=1.6732632423543772848170429916717,
  779. name=None,
  780. ):
  781. r"""
  782. selu activation
  783. .. math::
  784. selu(x)= scale *
  785. \left\{
  786. \begin{array}{lcl}
  787. x,& &\text{if } \ x > 0 \\
  788. alpha * e^{x} - alpha,& &\text{if } \ x <= 0
  789. \end{array}
  790. \right.
  791. Parameters:
  792. x (Tensor): The input Tensor with data type float32, float64.
  793. scale (float, optional): The value of scale(must be greater than 1.0) for selu. Default is 1.0507009873554804934193349852946.
  794. alpha (float, optional): The value of alpha(must be no less than zero) for selu. Default is 1.6732632423543772848170429916717.
  795. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  796. Returns:
  797. A Tensor with the same data type and shape as ``x`` .
  798. Examples:
  799. .. code-block:: python
  800. >>> import paddle
  801. >>> import paddle.nn.functional as F
  802. >>> x = paddle.to_tensor([[0.0, 1.0],[2.0, 3.0]])
  803. >>> out = F.selu(x)
  804. >>> print(out)
  805. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  806. [[0. , 1.05070102],
  807. [2.10140204, 3.15210295]])
  808. """
  809. if scale <= 1.0:
  810. raise ValueError(
  811. f"The scale must be greater than 1.0. Received: {scale}."
  812. )
  813. if alpha < 0:
  814. raise ValueError(
  815. f"The alpha must be no less than zero. Received: {alpha}."
  816. )
  817. if in_dynamic_or_pir_mode():
  818. return _C_ops.selu(x, scale, alpha)
  819. else:
  820. check_variable_and_dtype(
  821. x, 'x', ['float16', 'float32', 'float64'], 'selu'
  822. )
  823. helper = LayerHelper('selu', **locals())
  824. out = helper.create_variable_for_type_inference(x.dtype)
  825. helper.append_op(
  826. type='selu',
  827. inputs={'X': x},
  828. outputs={'Out': out},
  829. attrs={'scale': scale, 'alpha': alpha},
  830. )
  831. return out
  832. def silu(x, name=None):
  833. r"""
  834. silu activation
  835. .. math::
  836. silu(x) = \frac{x}{1 + e^{-x}}
  837. Where :math:`x` is the input Tensor.
  838. Parameters:
  839. x (Tensor): The input Tensor with data type bfloat16, float16, float32, float64, complex64, complex128.
  840. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  841. Returns:
  842. A Tensor with the same data type and shape as :attr:`x`.
  843. Examples:
  844. .. code-block:: python
  845. >>> import paddle
  846. >>> import paddle.nn.functional as F
  847. >>> x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
  848. >>> out = F.silu(x)
  849. >>> print(out)
  850. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  851. [0.73105860, 1.76159406, 2.85772228, 3.92805505])
  852. """
  853. if in_dynamic_or_pir_mode():
  854. return _C_ops.silu(x)
  855. else:
  856. check_variable_and_dtype(
  857. x,
  858. 'x',
  859. [
  860. 'float16',
  861. 'uint16',
  862. 'float32',
  863. 'float64',
  864. 'complex64',
  865. 'complex128',
  866. ],
  867. 'silu',
  868. )
  869. helper = LayerHelper("silu", **locals())
  870. out = helper.create_variable_for_type_inference(x.dtype)
  871. helper.append_op(type='silu', inputs={'X': x}, outputs={'Out': out})
  872. return out
  873. def softmax(x, axis=-1, dtype=None, name=None):
  874. r"""
  875. This operator implements the softmax layer. The calculation process is as follows:
  876. 1. The dimension :attr:`axis` of ``x`` will be permuted to the last.
  877. 2. Then ``x`` will be logically flattened to a 2-D matrix. The matrix's second
  878. dimension(row length) is the same as the dimension :attr:`axis` of ``x``,
  879. and the first dimension(column length) is the product of all other dimensions
  880. of ``x``. For each row of the matrix, the softmax operator squashes the
  881. K-dimensional(K is the width of the matrix, which is also the size of ``x``'s
  882. dimension :attr:`axis`) vector of arbitrary real values to a K-dimensional
  883. vector of real values in the range [0, 1] that add up to 1.
  884. 3. After the softmax operation is completed, the inverse operations of steps 1 and 2
  885. are performed to restore the two-dimensional matrix to the same dimension as the ``x`` .
  886. It computes the exponential of the given dimension and the sum of exponential
  887. values of all the other dimensions in the K-dimensional vector input.
  888. Then the ratio of the exponential of the given dimension and the sum of
  889. exponential values of all the other dimensions is the output of the softmax
  890. operator.
  891. For each row :math:`i` and each column :math:`j` in the matrix, we have:
  892. .. math::
  893. softmax[i, j] = \frac{\exp(x[i, j])}{\sum_j(exp(x[i, j])}
  894. Example:
  895. .. code-block:: text
  896. Case 1:
  897. Input:
  898. x.shape = [2, 3, 4]
  899. x.data = [[[2.0, 3.0, 4.0, 5.0],
  900. [3.0, 4.0, 5.0, 6.0],
  901. [7.0, 8.0, 8.0, 9.0]],
  902. [[1.0, 2.0, 3.0, 4.0],
  903. [5.0, 6.0, 7.0, 8.0],
  904. [6.0, 7.0, 8.0, 9.0]]]
  905. Attrs:
  906. axis = -1
  907. Output:
  908. out.shape = [2, 3, 4]
  909. out.data = [[[0.0320586 , 0.08714432, 0.23688282, 0.64391426],
  910. [0.0320586 , 0.08714432, 0.23688282, 0.64391426],
  911. [0.07232949, 0.19661193, 0.19661193, 0.53444665]],
  912. [[0.0320586 , 0.08714432, 0.23688282, 0.64391426],
  913. [0.0320586 , 0.08714432, 0.23688282, 0.64391426],
  914. [0.0320586 , 0.08714432, 0.23688282, 0.64391426]]]
  915. Case 2:
  916. Input:
  917. x.shape = [2, 3, 4]
  918. x.data = [[[2.0, 3.0, 4.0, 5.0],
  919. [3.0, 4.0, 5.0, 6.0],
  920. [7.0, 8.0, 8.0, 9.0]],
  921. [[1.0, 2.0, 3.0, 4.0],
  922. [5.0, 6.0, 7.0, 8.0],
  923. [6.0, 7.0, 8.0, 9.0]]]
  924. Attrs:
  925. axis = 1
  926. Output:
  927. out.shape = [2, 3, 4]
  928. out.data = [[[0.00657326, 0.00657326, 0.01714783, 0.01714783],
  929. [0.01786798, 0.01786798, 0.04661262, 0.04661262],
  930. [0.97555875, 0.97555875, 0.93623955, 0.93623955]],
  931. [[0.00490169, 0.00490169, 0.00490169, 0.00490169],
  932. [0.26762315, 0.26762315, 0.26762315, 0.26762315],
  933. [0.72747516, 0.72747516, 0.72747516, 0.72747516]]]
  934. Parameters:
  935. x (Tensor): The input Tensor with data type bfloat16, float16, float32, float64.
  936. axis (int, optional): The axis along which to perform softmax
  937. calculations. It should be in range [-D, D), where D is the
  938. rank of ``x`` . If ``axis`` < 0, it works the same way as
  939. :math:`axis + D` . Default is -1.
  940. dtype (str, optional): The data type of the output tensor, can be bfloat16, float16, float32, float64.
  941. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  942. Returns:
  943. A Tensor with the same shape and data type (use ``dtype`` if it is
  944. specified) as x.
  945. Examples:
  946. .. code-block:: python
  947. >>> import paddle
  948. >>> import paddle.nn.functional as F
  949. >>> x = paddle.to_tensor([[[2.0, 3.0, 4.0, 5.0],
  950. ... [3.0, 4.0, 5.0, 6.0],
  951. ... [7.0, 8.0, 8.0, 9.0]],
  952. ... [[1.0, 2.0, 3.0, 4.0],
  953. ... [5.0, 6.0, 7.0, 8.0],
  954. ... [6.0, 7.0, 8.0, 9.0]]],dtype='float32')
  955. >>> out1 = F.softmax(x)
  956. >>> out2 = F.softmax(x, dtype='float64')
  957. >>> #out1's data type is float32; out2's data type is float64
  958. >>> #out1 and out2's value is as follows:
  959. >>> print(out1)
  960. >>> print(out2)
  961. Tensor(shape=[2, 3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  962. [[[0.03205860, 0.08714432, 0.23688284, 0.64391428],
  963. [0.03205860, 0.08714432, 0.23688284, 0.64391428],
  964. [0.07232949, 0.19661194, 0.19661194, 0.53444666]],
  965. [[0.03205860, 0.08714432, 0.23688284, 0.64391428],
  966. [0.03205860, 0.08714432, 0.23688284, 0.64391428],
  967. [0.03205860, 0.08714432, 0.23688284, 0.64391428]]])
  968. Tensor(shape=[2, 3, 4], dtype=float64, place=Place(cpu), stop_gradient=True,
  969. [[[0.03205860, 0.08714432, 0.23688282, 0.64391426],
  970. [0.03205860, 0.08714432, 0.23688282, 0.64391426],
  971. [0.07232949, 0.19661193, 0.19661193, 0.53444665]],
  972. [[0.03205860, 0.08714432, 0.23688282, 0.64391426],
  973. [0.03205860, 0.08714432, 0.23688282, 0.64391426],
  974. [0.03205860, 0.08714432, 0.23688282, 0.64391426]]])
  975. """
  976. if (
  977. (dtype is not None)
  978. and (not isinstance(dtype, core.VarDesc.VarType))
  979. and (not isinstance(dtype, core.DataType))
  980. ):
  981. dtype = convert_np_dtype_to_dtype_(dtype)
  982. if in_dynamic_or_pir_mode():
  983. outs_cast = x if dtype is None else _C_ops.cast(x, dtype)
  984. return _C_ops.softmax(outs_cast, axis)
  985. else:
  986. use_cudnn = True
  987. if dtype is None:
  988. check_variable_and_dtype(
  989. x, 'x', ['uint16', 'float16', 'float32', 'float64'], 'softmax'
  990. )
  991. else:
  992. check_dtype(
  993. dtype,
  994. 'dtype',
  995. ['uint16', 'float16', 'float32', 'float64'],
  996. 'softmax',
  997. 'If dtype is not None, it only support uint16, float16, float32 or float64.',
  998. )
  999. helper = LayerHelper("softmax", **locals())
  1000. outs_cast = x
  1001. if dtype is not None:
  1002. outs_cast = helper.create_variable_for_type_inference(dtype)
  1003. helper.append_op(
  1004. type='cast',
  1005. inputs={'X': x},
  1006. outputs={'Out': outs_cast},
  1007. attrs={'in_dtype': x.dtype, 'out_dtype': dtype},
  1008. )
  1009. outs_softmax = helper.create_variable_for_type_inference(
  1010. outs_cast.dtype
  1011. )
  1012. helper.append_op(
  1013. type='softmax',
  1014. inputs={'X': outs_cast},
  1015. outputs={'Out': outs_softmax},
  1016. attrs={'axis': axis, 'use_cudnn': use_cudnn},
  1017. )
  1018. return outs_softmax
  1019. @inplace_apis_in_dygraph_only
  1020. def softmax_(x, axis=-1, dtype=None, name=None):
  1021. r"""
  1022. Inplace version of ``softmax`` API, the output Tensor will be inplaced with input ``x``.
  1023. Please refer to :ref:`api_paddle_nn_functional_softmax`.
  1024. """
  1025. if (dtype is not None) and (not isinstance(dtype, core.VarDesc.VarType)):
  1026. dtype = convert_np_dtype_to_dtype_(dtype)
  1027. outs_cast = (
  1028. x
  1029. if dtype is None
  1030. else _legacy_C_ops.cast(x, 'in_dtype', x.dtype, 'out_dtype', dtype)
  1031. )
  1032. return _C_ops.softmax_(outs_cast, axis)
  1033. def softplus(x, beta=1, threshold=20, name=None):
  1034. r"""
  1035. softplus activation
  1036. .. math::
  1037. softplus(x)=\begin{cases}
  1038. \frac{1}{\beta} * \log(1 + e^{\beta * x}),&x\leqslant\frac{\varepsilon}{\beta};\\
  1039. x,&x>\frac{\varepsilon}{\beta}.
  1040. \end{cases}
  1041. Parameters:
  1042. x (Tensor): The input Tensor with data type float32, float64, complex64, complex128.
  1043. beta (float, optional): The value of :math:`\beta` for softplus. Default is 1
  1044. threshold (float, optional): The value of :math:`\varepsilon` for softplus. Default is 20
  1045. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1046. Returns:
  1047. A Tensor with the same data type and shape as ``x`` .
  1048. Examples:
  1049. .. code-block:: python
  1050. >>> import paddle
  1051. >>> import paddle.nn.functional as F
  1052. >>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3], dtype='float32')
  1053. >>> out = F.softplus(x)
  1054. >>> print(out)
  1055. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1056. [0.51301527, 0.59813893, 0.74439669, 0.85435522])
  1057. """
  1058. if in_dynamic_or_pir_mode():
  1059. return _C_ops.softplus(x, beta, threshold)
  1060. else:
  1061. check_variable_and_dtype(
  1062. x,
  1063. 'x',
  1064. [
  1065. 'float16',
  1066. 'uint16',
  1067. 'float32',
  1068. 'float64',
  1069. 'complex64',
  1070. 'complex128',
  1071. ],
  1072. 'softplus',
  1073. )
  1074. helper = LayerHelper('softplus', **locals())
  1075. out = helper.create_variable_for_type_inference(x.dtype)
  1076. helper.append_op(
  1077. type='softplus',
  1078. inputs={'X': x},
  1079. outputs={'Out': out},
  1080. attrs={'beta': beta, 'threshold': threshold},
  1081. )
  1082. return out
  1083. def softshrink(x, threshold=0.5, name=None):
  1084. r"""
  1085. softshrink activation
  1086. .. math::
  1087. softshrink(x)=
  1088. \left\{
  1089. \begin{array}{rcl}
  1090. x - threshold,& & \text{if } x > threshold \\
  1091. x + threshold,& & \text{if } x < -threshold \\
  1092. 0,& & \text{otherwise}
  1093. \end{array}
  1094. \right.
  1095. Parameters:
  1096. x (Tensor): The input Tensor with data type float32, float64.
  1097. threshold (float, optional): The value of threshold(must be no less than zero) for softplus. Default is 0.5
  1098. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1099. Returns:
  1100. A Tensor with the same data type and shape as ``x`` .
  1101. Examples:
  1102. .. code-block:: python
  1103. >>> import paddle
  1104. >>> import paddle.nn.functional as F
  1105. >>> x = paddle.to_tensor([-0.9, -0.2, 0.1, 0.8])
  1106. >>> out = F.softshrink(x)
  1107. >>> print(out)
  1108. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1109. [-0.39999998, 0. , 0. , 0.30000001])
  1110. """
  1111. if threshold < 0:
  1112. raise ValueError(
  1113. f"The threshold must be no less than zero. Received: {threshold}."
  1114. )
  1115. if in_dynamic_or_pir_mode():
  1116. return _C_ops.softshrink(x, threshold)
  1117. else:
  1118. check_variable_and_dtype(
  1119. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'softshrink'
  1120. )
  1121. helper = LayerHelper('softshrink', **locals())
  1122. out = helper.create_variable_for_type_inference(x.dtype)
  1123. helper.append_op(
  1124. type='softshrink',
  1125. inputs={'X': x},
  1126. outputs={'Out': out},
  1127. attrs={'lambda': threshold},
  1128. )
  1129. return out
  1130. def softsign(x, name=None):
  1131. r"""
  1132. softsign activation
  1133. .. math::
  1134. softsign(x) = \frac{x}{1 + |x|}
  1135. Parameters:
  1136. x (Tensor): The input Tensor with data type float32, float64, complex64 or complex128.
  1137. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1138. Returns:
  1139. A Tensor with the same data type and shape as ``x`` .
  1140. Examples:
  1141. .. code-block:: python
  1142. >>> import paddle
  1143. >>> import paddle.nn.functional as F
  1144. >>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
  1145. >>> out = F.softsign(x)
  1146. >>> print(out)
  1147. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1148. [-0.28571430, -0.16666666, 0.09090909, 0.23076925])
  1149. """
  1150. if in_dynamic_or_pir_mode():
  1151. return _C_ops.softsign(x)
  1152. check_variable_and_dtype(
  1153. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'softsign'
  1154. )
  1155. helper = LayerHelper('softsign', **locals())
  1156. out = helper.create_variable_for_type_inference(x.dtype)
  1157. helper.append_op(type='softsign', inputs={'X': x}, outputs={'Out': out})
  1158. return out
  1159. def swish(x, name=None):
  1160. r"""
  1161. swish activation.
  1162. .. math::
  1163. swish(x) = \frac{x}{1 + e^{-x}}
  1164. Parameters:
  1165. x (Tensor): The input Tensor with data type float32, float64.
  1166. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1167. Returns:
  1168. A Tensor with the same data type and shape as ``x`` .
  1169. Examples:
  1170. .. code-block:: python
  1171. >>> import paddle
  1172. >>> import paddle.nn.functional as F
  1173. >>> x = paddle.to_tensor([-2., 0., 1.])
  1174. >>> out = F.swish(x)
  1175. >>> print(out)
  1176. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1177. [-0.23840584, 0. , 0.73105860])
  1178. """
  1179. if in_dynamic_or_pir_mode():
  1180. return _C_ops.swish(x)
  1181. else:
  1182. check_variable_and_dtype(
  1183. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'swish'
  1184. )
  1185. helper = LayerHelper('swish', **locals())
  1186. out = helper.create_variable_for_type_inference(x.dtype)
  1187. helper.append_op(
  1188. type='swish',
  1189. inputs={'X': x},
  1190. outputs={'Out': out},
  1191. attrs={'beta': 1.0},
  1192. )
  1193. return out
  1194. def mish(x, name=None):
  1195. r"""
  1196. mish activation.
  1197. .. math::
  1198. softplus(x) = \begin{cases}
  1199. x, \text{if } x > \text{threshold} \\
  1200. \ln(1 + e^{x}), \text{otherwise}
  1201. \end{cases}
  1202. mish(x) = x * \tanh(softplus(x))
  1203. Parameters:
  1204. x (Tensor): The input Tensor with data type float32, float64.
  1205. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1206. Returns:
  1207. A Tensor with the same data type and shape as ``x`` .
  1208. Examples:
  1209. .. code-block:: python
  1210. >>> import paddle
  1211. >>> import paddle.nn.functional as F
  1212. >>> x = paddle.to_tensor([-5., 0., 5.])
  1213. >>> out = F.mish(x)
  1214. >>> print(out)
  1215. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1216. [-0.03357624, 0. , 4.99955177])
  1217. """
  1218. if in_dynamic_or_pir_mode():
  1219. return _C_ops.mish(x, 20)
  1220. else:
  1221. check_variable_and_dtype(
  1222. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'mish'
  1223. )
  1224. helper = LayerHelper('mish', **locals())
  1225. out = helper.create_variable_for_type_inference(x.dtype)
  1226. helper.append_op(type='mish', inputs={'X': x}, outputs={'Out': out})
  1227. return out
  1228. def tanhshrink(x, name=None):
  1229. """
  1230. tanhshrink activation
  1231. .. math::
  1232. tanhshrink(x) = x - tanh(x)
  1233. Args:
  1234. x (Tensor): The input Tensor with data type float32, float64.
  1235. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1236. Returns:
  1237. A Tensor with the same data type and shape as ``x`` .
  1238. Examples:
  1239. .. code-block:: python
  1240. >>> import paddle
  1241. >>> import paddle.nn.functional as F
  1242. >>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
  1243. >>> out = F.tanhshrink(x)
  1244. >>> print(out)
  1245. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1246. [-0.02005100, -0.00262472, 0.00033201, 0.00868741])
  1247. """
  1248. if in_dynamic_or_pir_mode():
  1249. return _C_ops.tanh_shrink(x)
  1250. else:
  1251. check_variable_and_dtype(
  1252. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'tanhshrink'
  1253. )
  1254. helper = LayerHelper('tanh_shrink', **locals())
  1255. out = helper.create_variable_for_type_inference(x.dtype)
  1256. helper.append_op(
  1257. type='tanh_shrink', inputs={'X': x}, outputs={'Out': out}
  1258. )
  1259. return out
  1260. def thresholded_relu(x, threshold=1.0, name=None):
  1261. r"""
  1262. thresholded relu activation.
  1263. .. math::
  1264. thresholded\_relu(x) =
  1265. \left\{
  1266. \begin{array}{rl}
  1267. x,& \text{if } \ x > threshold \\
  1268. 0,& \text{otherwise}
  1269. \end{array}
  1270. \right.
  1271. Parameters:
  1272. x (Tensor): The input Tensor with data type float32, float64.
  1273. threshold (float, optional): The value of threshold for thresholded_relu. Default is 1.0
  1274. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1275. Returns:
  1276. A Tensor with the same data type and shape as ``x`` .
  1277. Examples:
  1278. .. code-block:: python
  1279. >>> import paddle
  1280. >>> import paddle.nn.functional as F
  1281. >>> x = paddle.to_tensor([2., 0., 1.])
  1282. >>> out = F.thresholded_relu(x)
  1283. >>> print(out)
  1284. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1285. [2., 0., 0.])
  1286. """
  1287. if in_dynamic_or_pir_mode():
  1288. return _C_ops.thresholded_relu(x, threshold)
  1289. else:
  1290. check_variable_and_dtype(
  1291. x,
  1292. 'x',
  1293. ['float16', 'uint16', 'float32', 'float64'],
  1294. 'thresholded_relu',
  1295. )
  1296. helper = LayerHelper('thresholded_relu', **locals())
  1297. out = helper.create_variable_for_type_inference(x.dtype)
  1298. helper.append_op(
  1299. type='thresholded_relu',
  1300. inputs={'X': x},
  1301. outputs={'Out': out},
  1302. attrs={'threshold': threshold},
  1303. )
  1304. return out
  1305. @inplace_apis_in_dygraph_only
  1306. def thresholded_relu_(x, threshold=1.0, name=None):
  1307. r"""
  1308. Inplace version of ``thresholded_relu`` API, the output Tensor will be inplaced with input ``x``.
  1309. Please refer to :ref:`api_paddle_nn_functional_thresholded_relu`.
  1310. """
  1311. if in_dynamic_mode():
  1312. return _C_ops.thresholded_relu_(x, threshold)
  1313. def log_softmax(x, axis=-1, dtype=None, name=None):
  1314. r"""
  1315. This operator implements the log_softmax layer. The calculation process is
  1316. as follows:
  1317. .. math::
  1318. \begin{aligned}
  1319. log\_softmax[i, j] &= log(softmax(x)) \\
  1320. &= log(\frac{\exp(X[i, j])}{\sum_j(\exp(X[i, j])})
  1321. \end{aligned}
  1322. Parameters:
  1323. x (Tensor): The input Tensor with data type float32, float64.
  1324. axis (int, optional): The axis along which to perform log_softmax
  1325. calculations. It should be in range [-D, D), where D is the
  1326. dimensions of ``x`` . If ``axis`` < 0, it works the same way as
  1327. :math:`axis + D` . Default is -1.
  1328. dtype (str|np.dtype|core.VarDesc.VarType, optional): The desired data
  1329. type of the output tensor. If dtype is specified, ``x`` is casted
  1330. to ``dtype`` before the operation is performed. This is useful for
  1331. preventing data type overflows. Supported dtype: float32, float64.
  1332. If ``dtype`` is None, the output Tensor has the same dtype as x.
  1333. Default is None.
  1334. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1335. Returns:
  1336. A Tensor with the same shape and data type (use ``dtype`` if it is
  1337. specified) as x.
  1338. Examples:
  1339. .. code-block:: python
  1340. >>> import paddle
  1341. >>> import paddle.nn.functional as F
  1342. >>> x = [[[-2.0, 3.0, -4.0, 5.0],
  1343. ... [3.0, -4.0, 5.0, -6.0],
  1344. ... [-7.0, -8.0, 8.0, 9.0]],
  1345. ... [[1.0, -2.0, -3.0, 4.0],
  1346. ... [-5.0, 6.0, 7.0, -8.0],
  1347. ... [6.0, 7.0, 8.0, 9.0]]]
  1348. >>> x = paddle.to_tensor(x)
  1349. >>> out1 = F.log_softmax(x)
  1350. >>> out2 = F.log_softmax(x, dtype='float64')
  1351. >>> #out1's data type is float32; out2's data type is float64
  1352. >>> #out1 and out2's value is as follows:
  1353. >>> print(out1)
  1354. Tensor(shape=[2, 3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1355. [[[-7.12783957 , -2.12783957 , -9.12783909 , -0.12783945 ],
  1356. [-2.12705135 , -9.12705135 , -0.12705141 , -11.12705135],
  1357. [-16.31326103, -17.31326103, -1.31326187 , -0.31326184 ]],
  1358. [[-3.05181193 , -6.05181217 , -7.05181217 , -0.05181199 ],
  1359. [-12.31326675, -1.31326652 , -0.31326646 , -15.31326675],
  1360. [-3.44018984 , -2.44018984 , -1.44018972 , -0.44018975 ]]])
  1361. >>> print(out2)
  1362. Tensor(shape=[2, 3, 4], dtype=float64, place=Place(cpu), stop_gradient=True,
  1363. [[[-7.12783948 , -2.12783948 , -9.12783948 , -0.12783948 ],
  1364. [-2.12705141 , -9.12705141 , -0.12705141 , -11.12705141],
  1365. [-16.31326180, -17.31326180, -1.31326180 , -0.31326180 ]],
  1366. [[-3.05181198 , -6.05181198 , -7.05181198 , -0.05181198 ],
  1367. [-12.31326640, -1.31326640 , -0.31326640 , -15.31326640],
  1368. [-3.44018970 , -2.44018970 , -1.44018970 , -0.44018970 ]]])
  1369. """
  1370. if (dtype is not None) and (not isinstance(dtype, core.VarDesc.VarType)):
  1371. dtype = convert_np_dtype_to_dtype_(dtype)
  1372. if in_dynamic_or_pir_mode():
  1373. if dtype is not None:
  1374. x = _C_ops.cast(x, dtype)
  1375. return _C_ops.log_softmax(x, axis)
  1376. else:
  1377. if dtype is None:
  1378. check_variable_and_dtype(
  1379. x,
  1380. 'x',
  1381. ['float16', 'uint16', 'float32', 'float64'],
  1382. 'log_softmax',
  1383. )
  1384. else:
  1385. check_dtype(
  1386. dtype,
  1387. 'dtype',
  1388. ['float32', 'float64'],
  1389. 'log_softmax',
  1390. 'If dtype is not None, it only support float32 or float64.',
  1391. )
  1392. helper = LayerHelper("log_softmax", **locals())
  1393. out_cast = x
  1394. if dtype is not None:
  1395. out_cast = helper.create_variable_for_type_inference(dtype)
  1396. helper.append_op(
  1397. type='cast',
  1398. inputs={'X': x},
  1399. outputs={'Out': out_cast},
  1400. attrs={'in_dtype': x.dtype, 'out_dtype': dtype},
  1401. )
  1402. out = helper.create_variable_for_type_inference(out_cast.dtype)
  1403. helper.append_op(
  1404. type='log_softmax',
  1405. inputs={'X': out_cast},
  1406. outputs={'Out': out},
  1407. attrs={'axis': axis},
  1408. )
  1409. return out
  1410. def glu(x, axis=-1, name=None):
  1411. r"""
  1412. The gated linear unit. The input is evenly splited into 2 parts along a
  1413. given axis. The first part is used as the content, and the second part is
  1414. passed through a sigmoid function then used as the gate. The output is a
  1415. elementwise multiplication of the content and the gate.
  1416. .. math::
  1417. \mathrm{GLU}(a, b) = a \otimes \sigma(b)
  1418. Parameters:
  1419. x (Tensor): The input Tensor with data type float32, float64.
  1420. axis (int, optional): The axis along which split the input tensor. It
  1421. should be in range [-D, D), where D is the dimensions of ``x`` .
  1422. If ``axis`` < 0, it works the same way as :math:`axis + D` .
  1423. Default is -1.
  1424. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1425. Returns:
  1426. A Tensor with the same data type as x. The size of the given axis is
  1427. halved.
  1428. Examples:
  1429. .. code-block:: python
  1430. >>> import paddle
  1431. >>> from paddle.nn import functional as F
  1432. >>> x = paddle.to_tensor(
  1433. ... [[-0.22014759, -1.76358426, 0.80566144, 0.04241343],
  1434. ... [-1.94900405, -1.89956081, 0.17134808, -1.11280477]]
  1435. ... )
  1436. >>> print(F.glu(x))
  1437. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1438. [[-0.15216254, -0.90048921],
  1439. [-1.05778778, -0.46985325]])
  1440. """
  1441. check_variable_and_dtype(
  1442. x, 'input', ['float16', 'float32', 'float64'], "glu"
  1443. )
  1444. rank = len(x.shape)
  1445. if not (-rank <= axis < rank):
  1446. raise ValueError(
  1447. f"Expected value range of `axis` is [{-rank}, {rank}), but received axis: {axis}"
  1448. )
  1449. a, b = chunk(x, 2, axis=axis, name=name)
  1450. gate = sigmoid(b, name=name)
  1451. out = paddle.multiply(a, gate, name=name)
  1452. return out
  1453. def gumbel_softmax(x, temperature=1.0, hard=False, axis=-1, name=None):
  1454. r"""
  1455. Samples from the Gumbel-Softmax distribution and optionally discretizes.
  1456. temperature is denoted by t. The calculation process is as follows:
  1457. First, generate gumbel noise:
  1458. .. math::
  1459. G_i = -log(-log(U_i)), U_i \sim U(0,1)
  1460. Second, add noise to ``x``:
  1461. .. math::
  1462. v = [x_1 + G_1,...,x_n + G_n]
  1463. Finally, calculate gumbel_softmax and generate samples:
  1464. .. math::
  1465. gumbel\_softmax(v_i)=\frac{e^{v_i/t}}{\sum_{j=1}^n{e^{v_j/t}}},i=1,2,3...n
  1466. Parameters:
  1467. x (Tensor): An N-D Tensor, the first N - 1 dimensions index into a batch
  1468. of independent distributions and the last dimension represents
  1469. a vector of probabilities with datatype float16, float32, float64.
  1470. temperature (float, optional): non-negative scalar temperature.
  1471. Default is 1.0.
  1472. hard (bool, optional): if True, the returned samples will be discretized as
  1473. one-hot vectors, but will be differentiated as if it is the soft sample
  1474. in autograd. Default is False.
  1475. axis (int, optional): The axis along will be calculated softmax value.
  1476. Default is -1.
  1477. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1478. Returns:
  1479. Sampled tensor of same shape as ``x`` from the Gumbel-Softmax distribution.
  1480. If ``hard = True``, the returned samples will be one-hot, otherwise they will be
  1481. probability distributions that sum to 1 across ``axis``.
  1482. Examples:
  1483. .. code-block:: python
  1484. >>> import paddle
  1485. >>> import paddle.nn.functional as F
  1486. >>> paddle.seed(2023)
  1487. >>> logits = paddle.randn([4, 6])
  1488. >>> temperature = 0.01
  1489. >>> gumbel_softmax = F.gumbel_softmax(logits, temperature)
  1490. >>> print(gumbel_softmax)
  1491. Tensor(shape=[4, 6], dtype=float32, place=Place(cpu), stop_gradient=True,
  1492. [[0.00000000, 1. , 0.00000000, 0.00000000, 0.00000000, 0.00000000],
  1493. [0.00000000, 0.00000000, 1. , 0.00000000, 0.00000000, 0.00000000],
  1494. [0.00000000, 0.00000004, 0.00000000, 0.00000000, 1. , 0.00000000],
  1495. [0.00000000, 1. , 0.00000000, 0.00000000, 0.00000000, 0.00000000]])
  1496. """
  1497. if in_dynamic_or_pir_mode():
  1498. return _C_ops.gumbel_softmax(x, temperature, hard, axis)
  1499. helper = LayerHelper("gumbel_softmax", **locals())
  1500. check_variable_and_dtype(
  1501. x, 'x', ['float16', 'float32', 'float64'], 'gumbel_softmax'
  1502. )
  1503. out = helper.create_variable_for_type_inference(x.dtype)
  1504. helper.append_op(
  1505. type='gumbel_softmax',
  1506. inputs={'X': x},
  1507. outputs={'Out': out},
  1508. attrs={'temperature': temperature, 'hard': hard, 'axis': axis},
  1509. )
  1510. return out