creation.py 104 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977
  1. # Copyright (c) 2022 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. # TODO: define functions to get create a tensor
  15. import math
  16. import re
  17. import numpy as np
  18. import paddle
  19. from paddle import _C_ops
  20. from paddle.utils.inplace_utils import inplace_apis_in_dygraph_only
  21. from ..base.data_feeder import (
  22. check_dtype,
  23. check_type,
  24. check_variable_and_dtype,
  25. convert_dtype,
  26. convert_float_to_uint16,
  27. )
  28. from ..base.framework import Variable, device_guard
  29. from ..base.param_attr import ParamAttr
  30. from ..framework import (
  31. LayerHelper,
  32. _current_expected_place,
  33. _current_expected_place_,
  34. _get_paddle_place,
  35. convert_np_dtype_to_dtype_,
  36. core,
  37. dygraph_only,
  38. in_dynamic_mode,
  39. in_dynamic_or_pir_mode,
  40. in_pir_mode,
  41. )
  42. __all__ = []
  43. def _complex_to_real_dtype(dtype):
  44. if dtype == core.VarDesc.VarType.COMPLEX64:
  45. return core.VarDesc.VarType.FP32
  46. elif dtype == core.VarDesc.VarType.COMPLEX128:
  47. return core.VarDesc.VarType.FP64
  48. elif dtype == paddle.pir.core.DataType.COMPLEX64:
  49. return paddle.pir.core.DataType.FP32
  50. elif dtype == paddle.pir.core.DataType.COMPLEX128:
  51. return paddle.pir.core.DataType.FP64
  52. else:
  53. return dtype
  54. def _real_to_complex_dtype(dtype):
  55. if dtype == core.VarDesc.VarType.FP32:
  56. return core.VarDesc.VarType.COMPLEX64
  57. elif dtype == core.VarDesc.VarType.FP64:
  58. return core.VarDesc.VarType.COMPLEX128
  59. elif dtype == paddle.pir.core.DataType.FP32:
  60. return paddle.pir.core.DataType.COMPLEX64
  61. elif dtype == paddle.pir.core.DataType.FP64:
  62. return paddle.pir.core.DataType.COMPLEX128
  63. else:
  64. return dtype
  65. def create_global_var(
  66. shape, value, dtype, persistable=False, force_cpu=False, name=None
  67. ):
  68. """
  69. This function creates a new tensor variable with value in the global block(block 0).
  70. Args:
  71. shape (list[int]|tuple[int]): Shape of the variable
  72. value (float): The value of the variable. The new created
  73. variable will be filled with it.
  74. dtype (str): Data type of the variable
  75. persistable (bool, optional): If this variable is persistable.
  76. Default: False
  77. force_cpu (bool, optional): Force this variable to be on CPU.
  78. Default: False
  79. name (str, optional): For detailed information, please refer to
  80. :ref:`api_guide_Name` . Usually name is no need to set and None by default.
  81. Returns:
  82. Variable: The created Variable
  83. Examples:
  84. .. code-block:: python
  85. >>> import paddle
  86. >>> paddle.enable_static()
  87. >>> var = paddle.static.create_global_var(shape=[2,3], value=1.0, dtype='float32',
  88. ... persistable=True, force_cpu=True, name='new_var')
  89. """
  90. check_type(shape, 'shape', (list, tuple, np.ndarray), 'create_global_var')
  91. for item in shape:
  92. check_type(
  93. item,
  94. 'item of shape',
  95. (
  96. int,
  97. np.uint8,
  98. np.int8,
  99. np.int16,
  100. np.int32,
  101. np.int64,
  102. ),
  103. 'create_global_var',
  104. )
  105. check_dtype(
  106. dtype,
  107. 'dtype',
  108. [
  109. 'bool',
  110. 'float16',
  111. 'float32',
  112. 'float64',
  113. 'int8',
  114. 'int16',
  115. 'int32',
  116. 'int64',
  117. 'uint8',
  118. 'uint16',
  119. ],
  120. 'create_global_var',
  121. )
  122. helper = LayerHelper("global_var", **locals())
  123. var = helper.create_global_variable(
  124. dtype=dtype,
  125. shape=shape,
  126. persistable=persistable,
  127. name=name,
  128. stop_gradient=True,
  129. )
  130. helper.set_variable_initializer(
  131. var,
  132. initializer=paddle.nn.initializer.ConstantInitializer(
  133. value=float(value), force_cpu=force_cpu
  134. ),
  135. )
  136. return var
  137. def create_parameter(
  138. shape, dtype, name=None, attr=None, is_bias=False, default_initializer=None
  139. ):
  140. """
  141. This function creates a parameter. The parameter is a learnable variable, which can have
  142. gradient, and can be optimized.
  143. Note:
  144. This is a very low-level API. This API is useful when you create operator by your self, instead of using layers.
  145. Args:
  146. shape (list of int): Shape of the parameter
  147. dtype (str): Data type of the parameter. It can be set as 'float16', 'float32', 'float64'.
  148. name (str, optional): For detailed information, please refer to
  149. :ref:`api_guide_Name` . Usually name is no need to set and None by default.
  150. attr (ParamAttr, optional): Attribute object of the specified argument. For detailed information, please refer to
  151. :ref:`api_paddle_ParamAttr` None by default, which means that ParamAttr will be initialized as it is.
  152. is_bias (bool, optional): This can affect which default initializer is chosen
  153. when default_initializer is None. If is_bias,
  154. initializer.Constant(0.0) will be used. Otherwise,
  155. Xavier() will be used.
  156. default_initializer (Initializer, optional): Initializer for the parameter
  157. Returns:
  158. The created parameter.
  159. Examples:
  160. .. code-block:: python
  161. >>> import paddle
  162. >>> paddle.enable_static()
  163. >>> W = paddle.create_parameter(shape=[784, 200], dtype='float32')
  164. """
  165. check_type(shape, 'shape', (list, tuple, np.ndarray), 'create_parameter')
  166. for item in shape:
  167. check_type(
  168. item,
  169. 'item of shape',
  170. (
  171. int,
  172. np.uint8,
  173. np.int8,
  174. np.int16,
  175. np.int32,
  176. np.int64,
  177. ),
  178. 'create_parameter',
  179. )
  180. check_dtype(
  181. dtype,
  182. 'dtype',
  183. [
  184. 'bool',
  185. 'float16',
  186. 'uint16',
  187. 'float32',
  188. 'float64',
  189. 'int8',
  190. 'int16',
  191. 'int32',
  192. 'int64',
  193. 'uint8',
  194. ],
  195. 'create_parameter',
  196. )
  197. check_type(attr, 'attr', (type(None), ParamAttr), 'create_parameter')
  198. check_type(
  199. default_initializer,
  200. 'default_initializer',
  201. (type(None), paddle.nn.initializer.Initializer),
  202. 'create_parameter',
  203. )
  204. helper = LayerHelper("create_parameter", **locals())
  205. if attr is None:
  206. attr = ParamAttr(name=name)
  207. return helper.create_parameter(
  208. attr, shape, convert_dtype(dtype), is_bias, default_initializer
  209. )
  210. def create_tensor(dtype, name=None, persistable=False):
  211. """
  212. Create a variable, which will hold a Tensor with data type dtype.
  213. Args:
  214. dtype(string|numpy.dtype): the data type of Tensor to be created, the
  215. data type is bool, float16, float32, float64, int8, int16, int32 and int64.
  216. name(string, optional): The default value is None. Normally there is no need for
  217. user to set this property. For more information, please refer to :ref:`api_guide_Name`
  218. persistable(bool): Set the persistable flag of the create tensor.
  219. default value is False.
  220. Returns:
  221. Variable: The tensor to be created according to dtype.
  222. Examples:
  223. .. code-block:: python
  224. >>> import paddle
  225. >>> tensor = paddle.tensor.create_tensor(dtype='float32')
  226. """
  227. check_dtype(
  228. dtype,
  229. 'dtype',
  230. [
  231. 'bool',
  232. 'float16',
  233. 'float32',
  234. 'float64',
  235. 'int8',
  236. 'int32',
  237. 'int32',
  238. 'int64',
  239. ],
  240. 'create_tensor',
  241. )
  242. helper = LayerHelper("create_tensor", **locals())
  243. return helper.create_variable(
  244. name=helper.name, dtype=dtype, persistable=persistable
  245. )
  246. def linspace(start, stop, num, dtype=None, name=None):
  247. r"""
  248. Return fixed number of evenly spaced values within a given interval. Note: no gradient calculation is performed.
  249. Args:
  250. start(int|float|Tensor): The input :attr:`start` is start of range. It is a int, float, \
  251. or a 0-D Tensor with data type int32, int64, float32 or float64.
  252. stop(int|float|Tensor): The input :attr:`stop` is end of range. It is a int, float, \
  253. or a 0-D Tensor with data type int32, int64, float32 or float64.
  254. num(int|Tensor): The input :attr:`num` is given num of the sequence. It is an int, \
  255. or a 0-D Tensor with data type int32.
  256. dtype(np.dtype|str, optional): The data type of output tensor, it could be
  257. int32, int64, float32 and float64. Default: if None, the data type is float32.
  258. name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  259. Returns:
  260. Tensor: the output data type will be float32, float64. The 1-D tensor with fixed number of evenly spaced values, \
  261. the data shape of this tensor is :math:`[num]` . If the :attr:`num` is set 1, the output tensor just has \
  262. the value with input :attr:`start`.
  263. Examples:
  264. .. code-block:: python
  265. >>> import paddle
  266. >>> data = paddle.linspace(0, 10, 5, 'float32')
  267. >>> print(data.numpy())
  268. [0. 2.5 5. 7.5 10.]
  269. >>> data = paddle.linspace(0, 10, 1, 'float32')
  270. >>> print(data.numpy())
  271. [0.]
  272. """
  273. if dtype is None:
  274. dtype = paddle.get_default_dtype()
  275. tensor_num = num
  276. tensor_start = start
  277. tensor_stop = stop
  278. if not isinstance(num, (Variable, paddle.pir.Value)):
  279. check_type(num, 'num', (int), 'linspace')
  280. if not isinstance(dtype, (core.VarDesc.VarType, paddle.pir.core.DataType)):
  281. dtype = convert_np_dtype_to_dtype_(dtype)
  282. if not isinstance(start, (Variable, paddle.pir.Value)):
  283. with device_guard("cpu"):
  284. tensor_start = fill_constant([1], dtype, start, force_cpu=True)
  285. if not isinstance(stop, (Variable, paddle.pir.Value)):
  286. with device_guard("cpu"):
  287. tensor_stop = fill_constant([1], dtype, stop, force_cpu=True)
  288. if not isinstance(num, (Variable, paddle.pir.Value)):
  289. with device_guard("cpu"):
  290. tensor_num = fill_constant([1], 'int32', num, force_cpu=True)
  291. if in_dynamic_or_pir_mode():
  292. return _C_ops.linspace(
  293. tensor_start,
  294. tensor_stop,
  295. tensor_num,
  296. dtype,
  297. _current_expected_place(),
  298. )
  299. else:
  300. helper = LayerHelper("linspace", **locals())
  301. start_dtype = convert_dtype(tensor_start.dtype)
  302. stop_dtype = convert_dtype(tensor_stop.dtype)
  303. out_dtype = convert_dtype(dtype)
  304. if isinstance(start, Variable):
  305. check_dtype(
  306. start.dtype,
  307. 'start',
  308. ['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
  309. 'linspace',
  310. )
  311. else:
  312. check_type(start, 'start', (int, float), 'linspace')
  313. if isinstance(stop, Variable):
  314. check_dtype(
  315. stop.dtype,
  316. 'stop',
  317. ['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
  318. 'linspace',
  319. )
  320. else:
  321. check_type(stop, 'stop', (int, float), 'linspace')
  322. if isinstance(num, Variable):
  323. check_dtype(num.dtype, 'num', ['int32'], 'linspace')
  324. check_dtype(
  325. dtype,
  326. 'dtype',
  327. ['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
  328. 'linspace',
  329. )
  330. if (
  331. (stop_dtype == "float64" or start_dtype == "float64")
  332. and out_dtype in ["float32", "int32"]
  333. ) or (
  334. (stop_dtype == "int64" or start_dtype == "int64")
  335. and out_dtype == "int32"
  336. ):
  337. raise ValueError(
  338. f"The dtype of start/stop is {start_dtype}/{stop_dtype} but the attr(dtype) of linspace is {dtype}, "
  339. "which may cause data type overflows. Please reset attr(dtype) of linspace."
  340. )
  341. out = helper.create_variable_for_type_inference(dtype=dtype)
  342. helper.append_op(
  343. type='linspace',
  344. inputs={
  345. 'Start': tensor_start,
  346. 'Stop': tensor_stop,
  347. 'Num': tensor_num,
  348. },
  349. attrs={'dtype': dtype},
  350. outputs={'Out': [out]},
  351. )
  352. if isinstance(num, int):
  353. out.desc.set_shape((num,))
  354. return out
  355. def logspace(start, stop, num, base=10.0, dtype=None, name=None):
  356. r"""
  357. Return fixed number of logarithmical-evenly spaced values within the interval \
  358. :math:`[base^{start}, base^{stop}]`.
  359. Notes:
  360. This API does not compute the gradient.
  361. Args:
  362. start(int|float|Tensor): The input :attr:`start` is exponent of first entry in \
  363. the sequence. It is a scalar, or a 0-D Tensor of shape [] with input data \
  364. type int32, int64, float32 or float64.
  365. stop(int|float|Tensor): The input :attr:`stop` is exponent of last entry in the \
  366. sequence. It is a scalar, or a 0-D Tensor of shape [] with input data \
  367. type int32, int64, float32 or float64.
  368. num(int|Tensor): The input :attr:`num` is given number of items in the sequence. \
  369. It is an int scalar, or a 0-D Tensor of shape [] with data type int32.
  370. base(int|float|Tensor): The input :attr:`base` is base of the logarithm function. \
  371. It is a scalar, or a 0-D Tensor of shape [] with input data type int32, int64, \
  372. float32 or float64.
  373. dtype(np.dtype|str, optional): The data type of output tensor, it could be \
  374. int32, int64, float32 or float64. Default: if None, the data type is float32. \
  375. name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  376. Returns:
  377. Tensor: The output data type will be float32, float64. The 1-D tensor with \
  378. fixed number of logarithmical-evenly spaced values, the data shape of this \
  379. tensor is :math:`[num]`. If the :attr:`num` is set 1, the output tensor \
  380. just has the value with exponential of :attr:`start` with base :attr:`base`.
  381. Examples:
  382. .. code-block:: python
  383. >>> import paddle
  384. >>> data = paddle.logspace(0, 10, 5, 2, 'float32')
  385. >>> print(data.numpy())
  386. [1.0000000e+00 5.6568542e+00 3.2000000e+01 1.8101933e+02 1.0240000e+03]
  387. >>> data = paddle.logspace(0, 10, 1, 2, 'float32')
  388. >>> print(data.numpy())
  389. [1.]
  390. """
  391. if dtype is None:
  392. dtype = paddle.get_default_dtype()
  393. tensor_num = num
  394. tensor_start = start
  395. tensor_stop = stop
  396. tensor_base = base
  397. if not isinstance(num, (Variable, paddle.pir.Value)):
  398. check_type(num, 'num', (int), 'logspace')
  399. if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
  400. dtype = convert_np_dtype_to_dtype_(dtype)
  401. if not isinstance(start, (Variable, paddle.pir.Value)):
  402. with device_guard("cpu"):
  403. tensor_start = fill_constant([1], dtype, start)
  404. if not isinstance(stop, (Variable, paddle.pir.Value)):
  405. with device_guard("cpu"):
  406. tensor_stop = fill_constant([1], dtype, stop)
  407. if not isinstance(num, (Variable, paddle.pir.Value)):
  408. with device_guard("cpu"):
  409. tensor_num = fill_constant([1], 'int32', num)
  410. if not isinstance(base, (Variable, paddle.pir.Value)):
  411. with device_guard("cpu"):
  412. tensor_base = fill_constant([1], dtype, base)
  413. if in_dynamic_or_pir_mode():
  414. return _C_ops.logspace(
  415. tensor_start,
  416. tensor_stop,
  417. tensor_num,
  418. tensor_base,
  419. dtype,
  420. _current_expected_place(),
  421. )
  422. else:
  423. helper = LayerHelper("logspace", **locals())
  424. start_dtype = convert_dtype(tensor_start.dtype)
  425. stop_dtype = convert_dtype(tensor_stop.dtype)
  426. base_dtype = convert_dtype(tensor_base.dtype)
  427. out_dtype = convert_dtype(dtype)
  428. if isinstance(start, Variable):
  429. check_dtype(
  430. start.dtype,
  431. 'start',
  432. ['float32', 'float64', 'int32', 'int64'],
  433. 'logspace',
  434. )
  435. else:
  436. check_type(start, 'start', (int, float), 'logspace')
  437. if isinstance(stop, Variable):
  438. check_dtype(
  439. stop.dtype,
  440. 'stop',
  441. ['float32', 'float64', 'int32', 'int64'],
  442. 'logspace',
  443. )
  444. else:
  445. check_type(stop, 'stop', (int, float), 'logspace')
  446. if isinstance(num, Variable):
  447. check_dtype(num.dtype, 'num', ['int32'], 'logspace')
  448. if isinstance(base, Variable):
  449. check_dtype(
  450. base.dtype,
  451. 'base',
  452. ['float32', 'float64', 'int32', 'int64'],
  453. 'logspace',
  454. )
  455. else:
  456. check_type(base, 'base', (int, float), 'logspace')
  457. check_dtype(
  458. dtype, 'dtype', ['int32', 'int64', 'float32', 'float64'], 'logspace'
  459. )
  460. if (
  461. (
  462. stop_dtype == "float64"
  463. or start_dtype == "float64"
  464. or base_dtype == "float64"
  465. )
  466. and out_dtype in ["float32", "int32"]
  467. ) or (
  468. (
  469. stop_dtype == "int64"
  470. or start_dtype == "int64"
  471. or base_dtype == "int64"
  472. )
  473. and out_dtype == "int32"
  474. ):
  475. raise ValueError(
  476. f"The dtype of start/stop/base is {start_dtype}/{stop_dtype}/{base_dtype} but the attr(dtype) of logspace is {dtype}, "
  477. "which may cause data type overflows. Please reset attr(dtype) of logspace."
  478. )
  479. out = helper.create_variable_for_type_inference(dtype=dtype)
  480. helper.append_op(
  481. type='logspace',
  482. inputs={
  483. 'Start': tensor_start,
  484. 'Stop': tensor_stop,
  485. 'Num': tensor_num,
  486. 'Base': tensor_base,
  487. },
  488. attrs={'dtype': dtype},
  489. outputs={'Out': [out]},
  490. )
  491. if isinstance(num, int):
  492. out.desc.set_shape((num,))
  493. return out
  494. def _to_tensor_non_static(data, dtype=None, place=None, stop_gradient=True):
  495. def _handle_tensor_dtype(tensor, dtype):
  496. if dtype:
  497. if convert_dtype(dtype) != convert_dtype(tensor.dtype):
  498. return tensor.astype(convert_dtype(dtype))
  499. return tensor
  500. def _handle_np_dtype(ndarray, dtype):
  501. if dtype:
  502. if convert_dtype(dtype) != convert_dtype(ndarray.dtype):
  503. # should not ndarray.astype('uint16') directly, data bits is wrong
  504. if convert_dtype(dtype) in ['uint16']:
  505. return convert_float_to_uint16(ndarray.astype('float32'))
  506. else:
  507. return ndarray.astype(convert_dtype(dtype))
  508. return ndarray
  509. if isinstance(data, np.number): # Special case for numpy scalars
  510. data = np.array(data)
  511. if not isinstance(data, np.ndarray):
  512. if np.isscalar(data) and not isinstance(data, str):
  513. data = np.array(data)
  514. elif isinstance(data, (list, tuple)):
  515. data = np.array(data)
  516. if data.dtype == np.object_:
  517. raise ValueError(
  518. "\n\tFailed to convert input data to a regular ndarray :\n\t - Usually "
  519. "this means the input data contains nested lists with different lengths. "
  520. )
  521. elif isinstance(data, paddle.Tensor) and not in_dynamic_mode():
  522. data = data._copy_to(place, False)
  523. data = _handle_tensor_dtype(data, dtype)
  524. data.stop_gradient = stop_gradient
  525. return data
  526. elif isinstance(data, core.eager.Tensor) and in_dynamic_mode():
  527. data = data._copy_to(place, False)
  528. data = _handle_tensor_dtype(data, dtype)
  529. data.stop_gradient = stop_gradient
  530. return data
  531. elif isinstance(data, (core.LoDTensor, core.Tensor)):
  532. # should't expose it to users, just for internal use.
  533. # convert core.Tensor/core.LoDTensor to Tensor first
  534. # Currently, there is no copy when places are same
  535. if in_dynamic_mode():
  536. data = core.eager.Tensor(data)
  537. else:
  538. data = paddle.Tensor(data)
  539. if not data.place._equals(place):
  540. data = data._copy_to(place, False)
  541. data = _handle_tensor_dtype(data, dtype)
  542. data.stop_gradient = stop_gradient
  543. return data
  544. else:
  545. raise TypeError(
  546. f"Can't constructs a 'paddle.Tensor' with data type {type(data)}, data type must be scalar|list|tuple|np.ndarray|paddle.Tensor"
  547. )
  548. if not dtype:
  549. if data.dtype in [
  550. 'float16',
  551. 'float32',
  552. 'float64',
  553. 'complex64',
  554. 'complex128',
  555. ]:
  556. default_type = paddle.get_default_dtype()
  557. if np.iscomplexobj(data):
  558. default_type = (
  559. 'complex64'
  560. if default_type in ['float16', 'float32']
  561. else 'complex128'
  562. )
  563. data = _handle_np_dtype(data, default_type)
  564. # Windows default type is 'int32', while Linux/Mac is 'int64'. Unify they.
  565. if data.dtype in ['int32']:
  566. data = data.astype("int64")
  567. if dtype:
  568. data = _handle_np_dtype(data, dtype)
  569. if isinstance(data, np.ndarray):
  570. return core.eager.Tensor(
  571. value=data,
  572. place=place,
  573. persistable=False,
  574. zero_copy=False,
  575. name=None,
  576. stop_gradient=stop_gradient,
  577. )
  578. else:
  579. return paddle.Tensor(
  580. value=data,
  581. place=place,
  582. persistable=False,
  583. zero_copy=False,
  584. stop_gradient=stop_gradient,
  585. )
  586. def _to_tensor_static(data, dtype=None, stop_gradient=None):
  587. if isinstance(data, (Variable, paddle.pir.Value)):
  588. output = data
  589. if dtype is not None and dtype != data.dtype:
  590. output = paddle.cast(output, dtype)
  591. else:
  592. if isinstance(data, np.number): # Special case for numpy scalars
  593. data = np.array(data)
  594. if not isinstance(data, np.ndarray):
  595. if np.isscalar(data) and not isinstance(data, str):
  596. data = np.array(data)
  597. elif isinstance(data, (list, tuple)):
  598. try:
  599. '''
  600. In numpy version >= 1.24.0, case like:
  601. np.array([Variable, 1, 2])
  602. is not supported, it will raise error (numpy returns an numpy array with dtype='object' in version <= 1.23.5)
  603. Thus, process nested structure in except block
  604. '''
  605. data = np.array(data)
  606. # for numpy version <= 1.23.5
  607. if data.dtype == 'object':
  608. raise RuntimeError("Numpy get dtype `object`.")
  609. except:
  610. to_stack_list = [None] * len(data)
  611. for idx, d in enumerate(data):
  612. to_stack_list[idx] = _to_tensor_static(
  613. d, dtype, stop_gradient
  614. )
  615. data = paddle.stack(to_stack_list)
  616. else:
  617. raise RuntimeError(
  618. f"Do not support transform type `{type(data)}` to tensor"
  619. )
  620. # fix numpy default dtype
  621. if data.dtype in ['float16', 'float32', 'float64']:
  622. data = data.astype(paddle.get_default_dtype())
  623. # Windows default type is 'int32', while Linux/Mac is 'int64'. Unify they.
  624. elif data.dtype in ['int32']:
  625. data = data.astype("int64")
  626. if dtype:
  627. target_dtype = dtype
  628. elif hasattr(data, 'dtype') and data.dtype != 'object':
  629. target_dtype = data.dtype
  630. else:
  631. target_dtype = paddle.get_default_dtype()
  632. target_dtype = convert_dtype(target_dtype)
  633. if data.dtype == "int16":
  634. data = data.astype("int32")
  635. output = assign(data)
  636. if convert_dtype(output.dtype) != target_dtype:
  637. output = paddle.cast(output, target_dtype)
  638. output.stop_gradient = stop_gradient
  639. return output
  640. def to_tensor(data, dtype=None, place=None, stop_gradient=True):
  641. r"""
  642. Constructs a ``paddle.Tensor`` from ``data`` ,
  643. which can be scalar, tuple, list, numpy\.ndarray, paddle\.Tensor.
  644. If the ``data`` is already a Tensor, copy will be performed and return a new tensor.
  645. If you only want to change stop_gradient property, please call ``Tensor.stop_gradient = stop_gradient`` directly.
  646. .. code-block:: text
  647. We use the dtype conversion rules following this:
  648. Keep dtype
  649. np.number ───────────► paddle.Tensor
  650. (0-D Tensor)
  651. default_dtype
  652. Python Number ───────────────► paddle.Tensor
  653. (0-D Tensor)
  654. Keep dtype
  655. np.ndarray ───────────► paddle.Tensor
  656. Args:
  657. data(scalar|tuple|list|ndarray|Tensor): Initial data for the tensor.
  658. Can be a scalar, list, tuple, numpy\.ndarray, paddle\.Tensor.
  659. dtype(str|np.dtype, optional): The desired data type of returned tensor. Can be 'bool' , 'float16' ,
  660. 'float32' , 'float64' , 'int8' , 'int16' , 'int32' , 'int64' , 'uint8',
  661. 'complex64' , 'complex128'. Default: None, infers dtype from ``data``
  662. except for python float number which gets dtype from ``get_default_type`` .
  663. place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str, optional): The place to allocate Tensor. Can be
  664. CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is
  665. string, It can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where ``x`` is the index of the GPUs.
  666. stop_gradient(bool, optional): Whether to block the gradient propagation of Autograd. Default: True.
  667. Returns:
  668. Tensor: A Tensor constructed from ``data`` .
  669. Examples:
  670. .. code-block:: python
  671. >>> import paddle
  672. >>> type(paddle.to_tensor(1))
  673. <class 'paddle.Tensor'>
  674. >>> paddle.to_tensor(1)
  675. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  676. 1)
  677. >>> x = paddle.to_tensor(1, stop_gradient=False)
  678. >>> print(x)
  679. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=False,
  680. 1)
  681. >>> paddle.to_tensor(x) # A new tensor will be created with default stop_gradient=True
  682. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  683. 1)
  684. >>> paddle.to_tensor([[0.1, 0.2], [0.3, 0.4]], place=paddle.CPUPlace(), stop_gradient=False)
  685. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=False,
  686. [[0.10000000, 0.20000000],
  687. [0.30000001, 0.40000001]])
  688. >>> type(paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64'))
  689. <class 'paddle.Tensor'>
  690. >>> paddle.to_tensor([[1+1j, 2], [3+2j, 4]], dtype='complex64')
  691. Tensor(shape=[2, 2], dtype=complex64, place=Place(cpu), stop_gradient=True,
  692. [[(1+1j), (2+0j)],
  693. [(3+2j), (4+0j)]])
  694. """
  695. place = _get_paddle_place(place)
  696. if place is None:
  697. place = _current_expected_place_()
  698. if in_dynamic_mode():
  699. return _to_tensor_non_static(data, dtype, place, stop_gradient)
  700. # call assign for static graph
  701. else:
  702. re_exp = re.compile(r'[(](.+?)[)]', re.S)
  703. place_str = re.findall(re_exp, str(place))[0]
  704. with paddle.static.device_guard(place_str):
  705. return _to_tensor_static(data, dtype, stop_gradient)
  706. def full_like(x, fill_value, dtype=None, name=None):
  707. """
  708. This function creates a tensor filled with ``fill_value`` which has identical shape of ``x`` and ``dtype``.
  709. If the ``dtype`` is None, the data type of Tensor is same with ``x``.
  710. Args:
  711. x(Tensor): The input tensor which specifies shape and data type. The data type can be bool, float16, float32, float64, int32, int64.
  712. fill_value(bool|float|int): The value to fill the tensor with. Note: this value shouldn't exceed the range of the output data type.
  713. dtype(np.dtype|str, optional): The data type of output. The data type can be one
  714. of bool, float16, float32, float64, int32, int64. The default value is None, which means the output
  715. data type is the same as input.
  716. name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  717. Returns:
  718. Tensor: Tensor which is created according to ``x``, ``fill_value`` and ``dtype``.
  719. Examples:
  720. .. code-block:: python
  721. >>> import paddle
  722. >>> input = paddle.full(shape=[2, 3], fill_value=0.0, dtype='float32', name='input')
  723. >>> output = paddle.full_like(input, 2.0)
  724. >>> print(output.numpy())
  725. [[2. 2. 2.]
  726. [2. 2. 2.]]
  727. """
  728. if dtype is None:
  729. dtype = x.dtype
  730. else:
  731. if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
  732. dtype = convert_np_dtype_to_dtype_(dtype)
  733. if in_dynamic_mode():
  734. return _C_ops.full_like(x, fill_value, dtype, x.place)
  735. elif in_pir_mode():
  736. return _C_ops.full_like(x, fill_value, dtype, core.Place())
  737. else:
  738. helper = LayerHelper("full_like", **locals())
  739. check_variable_and_dtype(
  740. x,
  741. 'x',
  742. [
  743. 'bool',
  744. 'float16',
  745. 'float32',
  746. 'float64',
  747. 'int16',
  748. 'int32',
  749. 'int64',
  750. 'uint16',
  751. ],
  752. 'full_like',
  753. )
  754. check_dtype(
  755. dtype,
  756. 'dtype',
  757. [
  758. 'bool',
  759. 'float16',
  760. 'float32',
  761. 'float64',
  762. 'int16',
  763. 'int32',
  764. 'int64',
  765. 'uint16',
  766. ],
  767. 'full_like/zeros_like/ones_like',
  768. )
  769. out = helper.create_variable_for_type_inference(dtype=dtype)
  770. helper.append_op(
  771. type='fill_any_like',
  772. inputs={'X': [x]},
  773. attrs={'value': fill_value, "dtype": dtype},
  774. outputs={'Out': [out]},
  775. )
  776. out.stop_gradient = True
  777. return out
  778. def fill_constant(shape, dtype, value, force_cpu=False, out=None, name=None):
  779. if in_dynamic_or_pir_mode():
  780. place = _current_expected_place()
  781. if force_cpu:
  782. place = core.CPUPlace()
  783. if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
  784. dtype = convert_np_dtype_to_dtype_(dtype)
  785. if in_pir_mode() and isinstance(dtype, core.VarDesc.VarType):
  786. dtype = paddle.pir.core.vartype_to_datatype[dtype]
  787. if in_dynamic_mode():
  788. value = float(value)
  789. if isinstance(shape, (list, tuple)):
  790. shape = paddle.utils.convert_shape_to_list(shape)
  791. else:
  792. paddle.utils.check_shape(shape)
  793. if isinstance(shape, (list, tuple)):
  794. if paddle.utils._contain_var(shape):
  795. shape = paddle.utils.get_int_tensor_list(shape)
  796. elif isinstance(shape, paddle.pir.Value):
  797. pass
  798. else:
  799. raise TypeError("Shape only supports Value, or list, or tuple.")
  800. if out is None:
  801. out = _C_ops.full(shape, value, dtype, place)
  802. out.stop_gradient = True
  803. return out
  804. if out is not None:
  805. _C_ops.full_(out, shape, value, dtype, place)
  806. out.stop_gradient = True
  807. return out
  808. else:
  809. attrs = {'force_cpu': force_cpu}
  810. dtype = convert_dtype(dtype)
  811. if not isinstance(value, Variable):
  812. if dtype in ['int8', 'uint8', 'int16', 'int32', 'int64']:
  813. attrs['str_value'] = str(int(value))
  814. attrs['value'] = int(value)
  815. else:
  816. attrs['str_value'] = str(float(value))
  817. attrs['value'] = float(value)
  818. helper = LayerHelper("fill_constant", **locals())
  819. inputs = {}
  820. if isinstance(value, Variable):
  821. if convert_dtype(value.dtype) != dtype:
  822. value = paddle.cast(value, dtype)
  823. inputs['ValueTensor'] = value
  824. paddle.utils.check_shape(shape)
  825. check_dtype(
  826. dtype,
  827. 'dtype',
  828. [
  829. 'bool',
  830. 'float16',
  831. 'float32',
  832. 'float64',
  833. 'int8',
  834. 'uint8',
  835. 'int16',
  836. 'int32',
  837. 'int64',
  838. 'complex64',
  839. 'complex128',
  840. 'uint16',
  841. ],
  842. 'fill_constant',
  843. )
  844. check_type(shape, 'shape', (Variable, list, tuple), 'fill_constant')
  845. if out is not None:
  846. check_variable_and_dtype(
  847. out, 'out', [convert_dtype(dtype)], 'fill_constant'
  848. )
  849. helper = LayerHelper("fill_constant", **locals())
  850. paddle.utils.get_shape_tensor_inputs(
  851. inputs=inputs, attrs=attrs, shape=shape, op_type='fill_constant'
  852. )
  853. if out is None:
  854. out = helper.create_variable_for_type_inference(dtype=dtype)
  855. attrs['dtype'] = out.dtype
  856. helper.append_op(
  857. type='fill_constant',
  858. inputs=inputs,
  859. outputs={'Out': [out]},
  860. attrs=attrs,
  861. stop_gradient=True,
  862. )
  863. out.stop_gradient = True
  864. return out
  865. def ones(shape, dtype=None, name=None):
  866. """
  867. Create a Tensor of specified :attr:`shape` and :attr:`dtype` and fill it with 1.
  868. Args:
  869. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  870. If ``shape`` is a list or tuple, the elements of it should be integers or 0-D Tensor with shape [].
  871. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
  872. dtype (np.dtype|str, optional): Data type of output Tensor, it should be one of
  873. bool, float16, float32, float64, int32 and int64. If it is set to None, the data type will be float32.
  874. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  875. Returns:
  876. Tensor: A Tensor of data type :attr:`dtype` with shape :attr:`shape` and all elements are 1.
  877. Examples:
  878. .. code-block:: python
  879. >>> import paddle
  880. >>> # shape is a list/tuple
  881. >>> data1 = paddle.ones(shape=[3, 2])
  882. >>> print(data1.numpy())
  883. [[1. 1.]
  884. [1. 1.]
  885. [1. 1.]]
  886. >>> # shape is a Tensor
  887. >>> shape = paddle.to_tensor([3, 2])
  888. >>> data2 = paddle.ones(shape=shape)
  889. >>> print(data2.numpy())
  890. [[1. 1.]
  891. [1. 1.]
  892. [1. 1.]]
  893. >>> # shape is a Tensor List
  894. >>> shape = [paddle.to_tensor(3), paddle.to_tensor(2)]
  895. >>> data3 = paddle.ones(shape=shape)
  896. >>> print(data3.numpy())
  897. [[1. 1.]
  898. [1. 1.]
  899. [1. 1.]]
  900. """
  901. if dtype is None:
  902. dtype = paddle.get_default_dtype()
  903. return fill_constant(value=1.0, shape=shape, dtype=dtype, name=name)
  904. def ones_like(x, dtype=None, name=None):
  905. """
  906. Returns a Tensor filled with the value 1, with the same shape and
  907. data type (use ``dtype`` if ``dtype`` is not None) as ``x``.
  908. Args:
  909. x(Tensor): The input tensor which specifies shape and dtype. The
  910. dtype of ``x`` can be bool, float16, float32, float64, int32, int64.
  911. dtype(str|np.dtype, optional): The data type of the
  912. output tensor. Supported data types: bool, float16, float32, float64,
  913. int32, int64. If ``dtype`` is None, the data type is the same as ``x``.
  914. Default is None.
  915. name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  916. Returns:
  917. Tensor: A Tensor filled with the value 1, with the same shape and
  918. data type (use ``dtype`` if ``dtype`` is not None) as ``x``.
  919. Examples:
  920. .. code-block:: python
  921. >>> import paddle
  922. >>> x = paddle.to_tensor([1,2,3])
  923. >>> out1 = paddle.ones_like(x)
  924. >>> print(out1.numpy())
  925. [1 1 1]
  926. >>> out2 = paddle.ones_like(x, dtype='int32')
  927. >>> print(out2.numpy())
  928. [1 1 1]
  929. """
  930. return full_like(x=x, fill_value=1, dtype=dtype, name=name)
  931. def zeros(shape, dtype=None, name=None):
  932. """
  933. Creates a tensor of specified :attr:`shape` and :attr:`dtype`, and fills it with 0.
  934. Args:
  935. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  936. If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
  937. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
  938. dtype(np.dtype|str, optional): Data type of output Tensor, it supports
  939. bool, float16, float32, float64, int32 and int64. Default: if None, the data type is float32.
  940. name(str, optional): The default value is None. Normally there is no need for user to set this
  941. property. For more information, please refer to :ref:`api_guide_Name`.
  942. Returns:
  943. Tensor: A tensor of data type :attr:`dtype` with shape :attr:`shape` and all elements set to 0.
  944. Examples:
  945. .. code-block:: python
  946. >>> import paddle
  947. >>> # shape is a list/tuple
  948. >>> data1 = paddle.zeros(shape=[3, 2])
  949. >>> print(data1.numpy())
  950. [[0. 0.]
  951. [0. 0.]
  952. [0. 0.]]
  953. >>> # shape is a Tensor
  954. >>> shape = paddle.to_tensor([3, 2])
  955. >>> data2 = paddle.zeros(shape=shape)
  956. >>> print(data2.numpy())
  957. [[0. 0.]
  958. [0. 0.]
  959. [0. 0.]]
  960. >>> # shape is a Tensor List
  961. >>> shape = [paddle.to_tensor(3), paddle.to_tensor(2)]
  962. >>> data3 = paddle.zeros(shape=shape)
  963. >>> print(data3.numpy())
  964. [[0. 0.]
  965. [0. 0.]
  966. [0. 0.]]
  967. """
  968. if dtype is None:
  969. dtype = paddle.get_default_dtype()
  970. return fill_constant(value=0.0, shape=shape, dtype=dtype, name=name)
  971. def zeros_like(x, dtype=None, name=None):
  972. """
  973. Returns a Tensor filled with the value 0, with the same shape and
  974. data type (use ``dtype`` if ``dtype`` is not None) as ``x``.
  975. Args:
  976. x(Tensor): The input tensor which specifies shape and dtype. The
  977. dtype of ``x`` can be bool, float16, float32, float64, int32, int64.
  978. dtype(str|np.dtype, optional): The data type of the
  979. output tensor. Supported data types: bool, float16, float32, float64,
  980. int32, int64. If ``dtype`` is None, the data type is the same as ``x``.
  981. Default is None.
  982. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  983. Returns:
  984. Tensor: A Tensor filled with the value 0, with the same shape and
  985. data type (use ``dtype`` if ``dtype`` is not None) as ``x``.
  986. Examples:
  987. .. code-block:: python
  988. >>> import paddle
  989. >>> x = paddle.to_tensor([1, 2, 3])
  990. >>> out1 = paddle.zeros_like(x)
  991. >>> print(out1.numpy())
  992. [0 0 0]
  993. >>> out2 = paddle.zeros_like(x, dtype='int32')
  994. >>> print(out2.numpy())
  995. [0 0 0]
  996. """
  997. return full_like(x=x, fill_value=0, dtype=dtype, name=name)
  998. def eye(num_rows, num_columns=None, dtype=None, name=None):
  999. """
  1000. This function constructs 2-D Tensor with ones on the diagonal and zeros elsewhere.
  1001. Args:
  1002. num_rows(int): the number of rows in each batch Tensor.
  1003. num_columns(int, optional): the number of columns in each batch Tensor.
  1004. If None, default: num_rows.
  1005. dtype(np.dtype|str, optional): The data type of the returned Tensor.
  1006. It should be int32, int64, float16, float32, float64, complex64, complex128. Default: if None, the data type
  1007. is float32.
  1008. name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1009. Returns:
  1010. Tensor: An identity Tensor or LoDTensor of shape [num_rows, num_columns].
  1011. Examples:
  1012. .. code-block:: python
  1013. >>> import paddle
  1014. >>> data = paddle.eye(3, dtype='int32')
  1015. >>> print(data.numpy())
  1016. [[1 0 0]
  1017. [0 1 0]
  1018. [0 0 1]]
  1019. >>> data = paddle.eye(2, 3, dtype='int32')
  1020. >>> print(data.numpy())
  1021. [[1 0 0]
  1022. [0 1 0]]
  1023. """
  1024. def _check_attr(attr, message):
  1025. if isinstance(attr, ((Variable, core.eager.Tensor, paddle.pir.Value))):
  1026. assert len(attr.shape) == 1 and attr.shape[0] in [1, -1]
  1027. elif not isinstance(attr, int) or attr < 0:
  1028. raise TypeError(f"{message} should be a non-negative int.")
  1029. _check_attr(num_rows, "num_rows")
  1030. if dtype is None:
  1031. dtype = paddle.get_default_dtype()
  1032. if not isinstance(dtype, (core.VarDesc.VarType, paddle.pir.core.DataType)):
  1033. dtype = convert_np_dtype_to_dtype_(dtype)
  1034. if num_columns is not None:
  1035. _check_attr(num_columns, "num_columns")
  1036. else:
  1037. num_columns = num_rows
  1038. if in_dynamic_or_pir_mode():
  1039. out = _C_ops.eye(
  1040. num_rows, num_columns, dtype, _current_expected_place()
  1041. )
  1042. else:
  1043. helper = LayerHelper("eye", **locals())
  1044. check_dtype(
  1045. dtype,
  1046. 'dtype',
  1047. [
  1048. 'float16',
  1049. 'float32',
  1050. 'float64',
  1051. 'uint16',
  1052. 'int32',
  1053. 'int64',
  1054. 'complex64',
  1055. 'comple128',
  1056. ],
  1057. 'eye',
  1058. )
  1059. out = helper.create_variable_for_type_inference(dtype=dtype)
  1060. helper.append_op(
  1061. type='eye',
  1062. inputs={},
  1063. outputs={'Out': [out]},
  1064. attrs={
  1065. 'num_rows': num_rows,
  1066. 'num_columns': num_columns,
  1067. 'dtype': dtype,
  1068. },
  1069. stop_gradient=True,
  1070. )
  1071. out.stop_gradient = True
  1072. return out
  1073. def full(shape, fill_value, dtype=None, name=None):
  1074. """
  1075. Return a Tensor with the ``fill_value`` which size is same as ``shape``.
  1076. Args:
  1077. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  1078. If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
  1079. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
  1080. fill_value(bool|float|int|Tensor): The constant value used to initialize the Tensor to be created.
  1081. If ``fill_value`` is an Tensor, it should be an 0-D Tensor which represents a scalar.
  1082. dtype(np.dtype|str, optional): Data type of the output Tensor
  1083. which can be float16, float32, float64, int32, int64, if dtype is `None`, the data
  1084. type of created Tensor is `float32`.
  1085. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1086. Returns:
  1087. Tensor: Tensor which is created according to ``shape``, ``fill_value`` and ``dtype``.
  1088. Examples:
  1089. .. code-block:: python
  1090. >>> import paddle
  1091. >>> # shape is a list/tuple
  1092. >>> data1 = paddle.full(shape=[3, 2], fill_value=1.)
  1093. >>> print(data1.numpy())
  1094. [[1. 1.]
  1095. [1. 1.]
  1096. [1. 1.]]
  1097. >>> # shape is a Tensor
  1098. >>> shape = paddle.to_tensor([3, 2])
  1099. >>> data2 = paddle.full(shape=shape, fill_value=2.)
  1100. >>> print(data2.numpy())
  1101. [[2. 2.]
  1102. [2. 2.]
  1103. [2. 2.]]
  1104. >>> # shape is a Tensor List
  1105. >>> shape = [paddle.to_tensor(3), paddle.to_tensor(2)]
  1106. >>> data3 = paddle.full(shape=shape, fill_value=3.)
  1107. >>> print(data3.numpy())
  1108. [[3. 3.]
  1109. [3. 3.]
  1110. [3. 3.]]
  1111. >>> # fill_value is a Tensor.
  1112. >>> val = paddle.full([], 2.0, "float32")
  1113. >>> data5 = paddle.full(shape=[3, 2], fill_value=val)
  1114. >>> print(data5.numpy())
  1115. [[2. 2.]
  1116. [2. 2.]
  1117. [2. 2.]]
  1118. """
  1119. if dtype is None:
  1120. dtype = paddle.get_default_dtype()
  1121. return fill_constant(shape=shape, dtype=dtype, value=fill_value, name=name)
  1122. def arange(start=0, end=None, step=1, dtype=None, name=None):
  1123. """
  1124. Returns a 1-D Tensor with spaced values within a given interval.
  1125. Values are generated into the half-open interval [``start``, ``end``) with
  1126. the ``step``. (the interval including ``start`` but excluding ``end``).
  1127. If ``dtype`` is float32 or float64, we advise adding a small epsilon to
  1128. ``end`` to avoid floating point rounding errors when comparing against ``end``.
  1129. Parameters:
  1130. start(float|int|Tensor): Start of interval. The interval includes this
  1131. value. If ``end`` is None, the half-open interval is [0, ``start``).
  1132. If ``start`` is a Tensor, it is a 0-D Tensor which represents a scalar
  1133. and data type is int32, int64, float32, float64. Default is 0.
  1134. end(float|int|Tensor, optional): End of interval. The interval does not
  1135. include this value. If ``end`` is a Tensor, it is a 0-D Tensor which
  1136. represents a scalar and data type is int32, int64, float32, float64.
  1137. If ``end`` is None, the half-open interval is [0, ``start``).
  1138. Default is None.
  1139. step(float|int|Tensor, optional): Spacing between values. For any out,
  1140. it is the instance between two adjacent values, out[i+1] - out[i].
  1141. If ``step`` is a Tensor, it is a 0-D Tensor which represents a scalar
  1142. and data type is int32, int64, float32, float64. . Default is 1.
  1143. dtype(str|np.dtype, optional): The data type of the
  1144. output tensor. Supported data types: int32, int64, float32, float64.
  1145. If ``dtype`` is None, the data type is float32. Default is None.
  1146. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1147. Returns:
  1148. Tensor: A 1-D Tensor with values from the interval [``start``, ``end``)
  1149. taken with common difference ``step`` beginning from ``start``. Its
  1150. data type is set by ``dtype``.
  1151. Examples:
  1152. .. code-block:: python
  1153. >>> import paddle
  1154. >>> out1 = paddle.arange(5)
  1155. >>> print(out1.numpy())
  1156. [0 1 2 3 4]
  1157. >>> out2 = paddle.arange(3, 9, 2.0)
  1158. >>> print(out2.numpy())
  1159. [3. 5. 7.]
  1160. >>> # use 4.999 instead of 5.0 to avoid floating point rounding errors
  1161. >>> out3 = paddle.arange(4.999, dtype='float32')
  1162. >>> print(out3.numpy())
  1163. [0. 1. 2. 3. 4.]
  1164. >>> start_var = paddle.to_tensor(3)
  1165. >>> out4 = paddle.arange(start_var, 7)
  1166. >>> print(out4.numpy())
  1167. [3 4 5 6]
  1168. """
  1169. if end is None:
  1170. end = start
  1171. start = 0
  1172. if dtype is None:
  1173. for val in [start, end, step]:
  1174. if isinstance(val, (Variable, paddle.pir.Value)):
  1175. if not paddle.is_integer(val):
  1176. dtype = paddle.get_default_dtype()
  1177. break
  1178. else:
  1179. dtype = 'int64'
  1180. else:
  1181. if not isinstance(val, np.integer) and not isinstance(val, int):
  1182. dtype = paddle.get_default_dtype()
  1183. break
  1184. else:
  1185. dtype = 'int64'
  1186. out_shape = None
  1187. is_value_input = (
  1188. not isinstance(start, (Variable, paddle.pir.Value))
  1189. and not isinstance(end, (Variable, paddle.pir.Value))
  1190. and not isinstance(step, (Variable, paddle.pir.Value))
  1191. )
  1192. if not in_dynamic_mode() and is_value_input:
  1193. out_shape = [int(math.ceil((end - start) / step))]
  1194. if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
  1195. dtype = convert_np_dtype_to_dtype_(dtype)
  1196. if is_value_input and in_pir_mode():
  1197. return _C_ops.arange(start, end, step, dtype, _current_expected_place())
  1198. if not isinstance(start, (Variable, paddle.pir.Value)):
  1199. with device_guard("cpu"):
  1200. start = fill_constant([1], dtype, start, force_cpu=True)
  1201. elif start.dtype != dtype:
  1202. start = paddle.cast(start, dtype)
  1203. if not isinstance(end, (Variable, paddle.pir.Value)):
  1204. with device_guard("cpu"):
  1205. end = fill_constant([1], dtype, end, force_cpu=True)
  1206. elif end.dtype != dtype:
  1207. end = paddle.cast(end, dtype)
  1208. if not isinstance(step, (Variable, paddle.pir.Value)):
  1209. with device_guard("cpu"):
  1210. step = fill_constant([1], dtype, step, force_cpu=True)
  1211. elif step.dtype != dtype:
  1212. step = paddle.cast(step, dtype)
  1213. if in_dynamic_or_pir_mode():
  1214. return _C_ops.arange(start, end, step, dtype, _current_expected_place())
  1215. else:
  1216. check_dtype(
  1217. dtype,
  1218. 'dtype',
  1219. ['float32', 'float64', 'int32', 'int64', 'float16', 'uint16'],
  1220. 'range/arange',
  1221. )
  1222. helper = LayerHelper('range', **locals())
  1223. out = helper.create_variable_for_type_inference(dtype, shape=out_shape)
  1224. helper.append_op(
  1225. type='range',
  1226. inputs={'Start': start, 'End': end, 'Step': step},
  1227. outputs={'Out': out},
  1228. )
  1229. out.stop_gradient = True
  1230. if out_shape is not None:
  1231. out.desc.set_shape(out_shape)
  1232. return out
  1233. def _tril_triu_op(helper):
  1234. """Base op of tril_op and triu_op"""
  1235. op_type = helper.layer_type
  1236. x = helper.kwargs.get('x', None)
  1237. assert x is not None, f'x cannot be None in {op_type}'
  1238. check_variable_and_dtype(
  1239. x,
  1240. 'x',
  1241. [
  1242. 'float16',
  1243. 'uint16',
  1244. 'float32',
  1245. 'float64',
  1246. 'int32',
  1247. 'int64',
  1248. 'bool',
  1249. 'complex64',
  1250. 'complex128',
  1251. ],
  1252. op_type,
  1253. )
  1254. if len(x.shape) < 2:
  1255. raise ValueError(f"x shape in {op_type} must be at least 2-D")
  1256. diagonal = helper.kwargs.get('diagonal', 0)
  1257. if not isinstance(diagonal, (int,)):
  1258. raise TypeError(f"diagonal in {op_type} must be a python Int")
  1259. name = helper.kwargs.get('name', None)
  1260. if name is None:
  1261. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  1262. else:
  1263. out = helper.create_variable(
  1264. name=name, dtype=x.dtype, persistable=False
  1265. )
  1266. helper.append_op(
  1267. type="tril_triu",
  1268. inputs={"X": x},
  1269. attrs={
  1270. "diagonal": diagonal,
  1271. "lower": True if op_type == 'tril' else False,
  1272. },
  1273. outputs={"Out": out},
  1274. )
  1275. return out
  1276. def tril(x, diagonal=0, name=None):
  1277. r"""
  1278. Returns the lower triangular part of a matrix (2-D tensor) or batch
  1279. of matrices :attr:`x`, the other elements of the result tensor are set
  1280. to 0. The lower triangular part of the matrix is defined as the elements
  1281. on and below the diagonal.
  1282. Args:
  1283. x (Tensor): The input x which is a Tensor.
  1284. Support data types: ``bool``, ``float64``, ``float32``, ``int32``, ``int64``, ``complex64``, ``complex128``.
  1285. diagonal (int, optional): The diagonal to consider, default value is 0.
  1286. If :attr:`diagonal` = 0, all elements on and below the main diagonal are
  1287. retained. A positive value includes just as many diagonals above the main
  1288. diagonal, and similarly a negative value excludes just as many diagonals below
  1289. the main diagonal. The main diagonal are the set of indices
  1290. :math:`\{(i, i)\}` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where
  1291. :math:`d_{1}, d_{2}` are the dimensions of the matrix.
  1292. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1293. Returns:
  1294. Tensor: Results of lower triangular operation by the specified diagonal of input tensor x,
  1295. it's data type is the same as x's Tensor.
  1296. Examples:
  1297. .. code-block:: python
  1298. >>> import paddle
  1299. >>> data = paddle.arange(1, 13, dtype="int64").reshape([3,-1])
  1300. >>> print(data)
  1301. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1302. [[1 , 2 , 3 , 4 ],
  1303. [5 , 6 , 7 , 8 ],
  1304. [9 , 10, 11, 12]])
  1305. >>> tril1 = paddle.tril(data)
  1306. >>> print(tril1)
  1307. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1308. [[1 , 0 , 0 , 0 ],
  1309. [5 , 6 , 0 , 0 ],
  1310. [9 , 10, 11, 0 ]])
  1311. >>> # example 2, positive diagonal value
  1312. >>> tril2 = paddle.tril(data, diagonal=2)
  1313. >>> print(tril2)
  1314. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1315. [[1 , 2 , 3 , 0 ],
  1316. [5 , 6 , 7 , 8 ],
  1317. [9 , 10, 11, 12]])
  1318. >>> # example 3, negative diagonal value
  1319. >>> tril3 = paddle.tril(data, diagonal=-1)
  1320. >>> print(tril3)
  1321. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1322. [[0 , 0 , 0 , 0 ],
  1323. [5 , 0 , 0 , 0 ],
  1324. [9 , 10, 0 , 0 ]])
  1325. """
  1326. if in_dynamic_or_pir_mode():
  1327. return _C_ops.tril(x, diagonal)
  1328. else:
  1329. return _tril_triu_op(LayerHelper('tril', **locals()))
  1330. @inplace_apis_in_dygraph_only
  1331. def tril_(x, diagonal=0, name=None):
  1332. r"""
  1333. Inplace version of ``tril`` API, the output Tensor will be inplaced with input ``x``.
  1334. Please refer to :ref:`api_paddle_tril`.
  1335. """
  1336. if in_dynamic_mode():
  1337. return _C_ops.tril_(x, diagonal)
  1338. def triu(x, diagonal=0, name=None):
  1339. r"""
  1340. Return the upper triangular part of a matrix (2-D tensor) or batch of matrices
  1341. :attr:`x`, the other elements of the result tensor are set to 0.
  1342. The upper triangular part of the matrix is defined as the elements on and
  1343. above the diagonal.
  1344. Args:
  1345. x (Tensor): The input x which is a Tensor.
  1346. Support data types: ``float64``, ``float32``, ``int32``, ``int64``, ``complex64``, ``complex128``.
  1347. diagonal (int, optional): The diagonal to consider, default value is 0.
  1348. If :attr:`diagonal` = 0, all elements on and above the main diagonal are
  1349. retained. A positive value excludes just as many diagonals above the main
  1350. diagonal, and similarly a negative value includes just as many diagonals below
  1351. the main diagonal. The main diagonal are the set of indices
  1352. :math:`\{(i, i)\}` for :math:`i \in [0, \min\{d_{1}, d_{2}\} - 1]` where
  1353. :math:`d_{1}, d_{2}` are the dimensions of the matrix.
  1354. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1355. Returns:
  1356. Tensor: Results of upper triangular operation by the specified diagonal of input tensor x,
  1357. it's data type is the same as x's Tensor.
  1358. Examples:
  1359. .. code-block:: python
  1360. >>> import paddle
  1361. >>> x = paddle.arange(1, 13, dtype="int64").reshape([3,-1])
  1362. >>> print(x)
  1363. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1364. [[1 , 2 , 3 , 4 ],
  1365. [5 , 6 , 7 , 8 ],
  1366. [9 , 10, 11, 12]])
  1367. >>> # example 1, default diagonal
  1368. >>> triu1 = paddle.tensor.triu(x)
  1369. >>> print(triu1)
  1370. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1371. [[1 , 2 , 3 , 4 ],
  1372. [0 , 6 , 7 , 8 ],
  1373. [0 , 0 , 11, 12]])
  1374. >>> # example 2, positive diagonal value
  1375. >>> triu2 = paddle.tensor.triu(x, diagonal=2)
  1376. >>> print(triu2)
  1377. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1378. [[0, 0, 3, 4],
  1379. [0, 0, 0, 8],
  1380. [0, 0, 0, 0]])
  1381. >>> # example 3, negative diagonal value
  1382. >>> triu3 = paddle.tensor.triu(x, diagonal=-1)
  1383. >>> print(triu3)
  1384. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1385. [[1 , 2 , 3 , 4 ],
  1386. [5 , 6 , 7 , 8 ],
  1387. [0 , 10, 11, 12]])
  1388. """
  1389. if in_dynamic_or_pir_mode():
  1390. return _C_ops.triu(x, diagonal)
  1391. else:
  1392. return _tril_triu_op(LayerHelper('triu', **locals()))
  1393. @inplace_apis_in_dygraph_only
  1394. def triu_(x, diagonal=0, name=None):
  1395. r"""
  1396. Inplace version of ``triu`` API, the output Tensor will be inplaced with input ``x``.
  1397. Please refer to :ref:`api_paddle_triu`.
  1398. """
  1399. if in_dynamic_mode():
  1400. return _C_ops.triu_(x, diagonal)
  1401. def meshgrid(*args, **kwargs):
  1402. """
  1403. Takes a list of N tensors as input :attr:`*args`, each of which is 1-dimensional vector, and creates N-dimensional grids.
  1404. Args:
  1405. *args(Tensor|list of Tensor) : tensors (tuple(list) of tensor): the shapes of input k tensors are (N1,),
  1406. (N2,),..., (Nk,). Support data types: ``float64``, ``bfloat16``, ``float16``, ``float32``, ``int32``, ``int64``, ``complex64``, ``complex128``.
  1407. **kwargs (optional): Currently, only accept name in **kwargs
  1408. The default value is None. Normally there is no need for
  1409. user to set this property. For more information, please refer to :ref:`api_guide_Name`.
  1410. Returns:
  1411. Tensor: k tensors. The shape of each tensor is (N1, N2, ..., Nk)
  1412. Examples:
  1413. .. code-block:: python
  1414. >>> import paddle
  1415. >>> x = paddle.randint(low=0, high=100, shape=[100])
  1416. >>> y = paddle.randint(low=0, high=100, shape=[200])
  1417. >>> grid_x, grid_y = paddle.meshgrid(x, y)
  1418. >>> print(grid_x.shape)
  1419. [100, 200]
  1420. >>> print(grid_y.shape)
  1421. [100, 200]
  1422. """
  1423. if len(args) == 1 and isinstance(args[0], (list, tuple)):
  1424. args = args[0]
  1425. if in_dynamic_or_pir_mode():
  1426. return _C_ops.meshgrid(list(args))
  1427. else:
  1428. name = kwargs.get("name", None)
  1429. helper = LayerHelper('meshgrid', **locals())
  1430. if not isinstance(args, (list, tuple)):
  1431. raise TypeError(
  1432. "The type of input args in meshgrid should be list."
  1433. )
  1434. for id, input_ in enumerate(args):
  1435. check_dtype(
  1436. input_.dtype,
  1437. 'create data type',
  1438. [
  1439. 'uint16',
  1440. 'float16',
  1441. 'float32',
  1442. 'float64',
  1443. 'int32',
  1444. 'int64',
  1445. 'complex64',
  1446. 'complex128',
  1447. ],
  1448. 'meshgrid',
  1449. )
  1450. num = len(args)
  1451. out = [
  1452. helper.create_variable_for_type_inference(dtype=args[i].dtype)
  1453. for i in range(num)
  1454. ]
  1455. helper.append_op(
  1456. type='meshgrid', inputs={'X': list(args)}, outputs={'Out': out}
  1457. )
  1458. return out
  1459. def diag_embed(input, offset=0, dim1=-2, dim2=-1):
  1460. """
  1461. Creates a tensor whose diagonals of certain 2D planes (specified by dim1 and dim2)
  1462. are filled by ``input``. By default, a 2D plane formed by the last two dimensions
  1463. of the returned tensor will be selected.
  1464. The argument ``offset`` determines which diagonal is generated:
  1465. - If offset = 0, it is the main diagonal.
  1466. - If offset > 0, it is above the main diagonal.
  1467. - If offset < 0, it is below the main diagonal.
  1468. Args:
  1469. input(Tensor|numpy.ndarray): The input tensor. Must be at least 1-dimensional. The input data type should be float32, float64, int32, int64.
  1470. offset(int, optional): Which diagonal to consider. Default: 0 (main diagonal).
  1471. dim1(int, optional): The first dimension with respect to which to take diagonal. Default: -2.
  1472. dim2(int, optional): The second dimension with respect to which to take diagonal. Default: -1.
  1473. Returns:
  1474. Tensor, the output data type is the same as input data type.
  1475. Examples:
  1476. .. code-block:: python
  1477. >>> import paddle
  1478. >>> diag_embed_input = paddle.arange(6)
  1479. >>> diag_embed_output1 = paddle.diag_embed(diag_embed_input)
  1480. >>> print(diag_embed_output1)
  1481. Tensor(shape=[6, 6], dtype=int64, place=Place(cpu), stop_gradient=True,
  1482. [[0, 0, 0, 0, 0, 0],
  1483. [0, 1, 0, 0, 0, 0],
  1484. [0, 0, 2, 0, 0, 0],
  1485. [0, 0, 0, 3, 0, 0],
  1486. [0, 0, 0, 0, 4, 0],
  1487. [0, 0, 0, 0, 0, 5]])
  1488. >>> diag_embed_output2 = paddle.diag_embed(diag_embed_input, offset=-1, dim1=0,dim2=1 )
  1489. >>> print(diag_embed_output2)
  1490. Tensor(shape=[7, 7], dtype=int64, place=Place(cpu), stop_gradient=True,
  1491. [[0, 0, 0, 0, 0, 0, 0],
  1492. [0, 0, 0, 0, 0, 0, 0],
  1493. [0, 1, 0, 0, 0, 0, 0],
  1494. [0, 0, 2, 0, 0, 0, 0],
  1495. [0, 0, 0, 3, 0, 0, 0],
  1496. [0, 0, 0, 0, 4, 0, 0],
  1497. [0, 0, 0, 0, 0, 5, 0]])
  1498. >>> diag_embed_input_2dim = paddle.reshape(diag_embed_input,[2,3])
  1499. >>> print(diag_embed_input_2dim)
  1500. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1501. [[0, 1, 2],
  1502. [3, 4, 5]])
  1503. >>> diag_embed_output3 = paddle.diag_embed(diag_embed_input_2dim,offset= 0, dim1=0, dim2=2 )
  1504. >>> print(diag_embed_output3)
  1505. Tensor(shape=[3, 2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1506. [[[0, 0, 0],
  1507. [3, 0, 0]],
  1508. [[0, 1, 0],
  1509. [0, 4, 0]],
  1510. [[0, 0, 2],
  1511. [0, 0, 5]]])
  1512. """
  1513. if not isinstance(input, Variable):
  1514. input = assign(input)
  1515. if in_dynamic_or_pir_mode():
  1516. return _C_ops.diag_embed(input, offset, dim1, dim2)
  1517. inputs = {'Input': [input]}
  1518. attrs = {'offset': offset, 'dim1': dim1, 'dim2': dim2}
  1519. def __check_input(input, offset, dim1, dim2):
  1520. check_dtype(
  1521. input.dtype,
  1522. 'Input',
  1523. ['int32', 'int64', 'float16', 'float32', 'float64'],
  1524. 'diag_embed',
  1525. )
  1526. input_shape = list(input.shape)
  1527. assert len(input_shape) >= 1, (
  1528. "Input must be at least 1-dimensional, "
  1529. "But received Input's dimensional: %s.\n" % len(input_shape)
  1530. )
  1531. assert np.abs(dim1) <= len(input_shape), (
  1532. "Dim1 is out of range (expected to be in range of [%d, %d], but got %d).\n"
  1533. % (-(len(input_shape) + 1), len(input_shape), dim1)
  1534. )
  1535. assert np.abs(dim2) <= len(input_shape), (
  1536. "Dim2 is out of range (expected to be in range of [%d, %d], but got %d).\n"
  1537. % (-(len(input_shape) + 1), len(input_shape), dim2)
  1538. )
  1539. dim1_ = dim1 if dim1 >= 0 else len(input_shape) + dim1 + 1
  1540. dim2_ = dim2 if dim2 >= 0 else len(input_shape) + dim2 + 1
  1541. assert dim1_ != dim2_, (
  1542. "dim1 and dim2 cannot be the same dimension."
  1543. "But received dim1 = %d, dim2 = %d\n" % (dim1, dim2)
  1544. )
  1545. __check_input(input, offset, dim1, dim2)
  1546. helper = LayerHelper("diag_embed", **locals())
  1547. out = helper.create_variable_for_type_inference(dtype=input.dtype)
  1548. helper.append_op(
  1549. type='diag_embed',
  1550. inputs={'Input': [input]},
  1551. attrs={'offset': offset, 'dim1': dim1, 'dim2': dim2},
  1552. outputs={'Out': [out]},
  1553. )
  1554. out.stop_gradient = True
  1555. return out
  1556. def diagflat(x, offset=0, name=None):
  1557. """
  1558. If ``x`` is a vector (1-D tensor), a 2-D square tensor with the elements of ``x`` as the diagonal is returned.
  1559. If ``x`` is a tensor (more than 1-D), a 2-D square tensor with the elements of flattened ``x`` as the diagonal is returned.
  1560. The argument ``offset`` controls the diagonal offset.
  1561. If ``offset`` = 0, it is the main diagonal.
  1562. If ``offset`` > 0, it is superdiagonal.
  1563. If ``offset`` < 0, it is subdiagonal.
  1564. Args:
  1565. x (Tensor): The input tensor. It can be any shape. Its data type should be float16, float32, float64, int32, int64.
  1566. offset (int, optional): The diagonal offset. A positive value represents superdiagonal, 0 represents the main diagonal, and a negative value represents subdiagonal. Default: 0 (main diagonal).
  1567. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1568. Returns:
  1569. Tensor, a square matrix. The output data type is the same as input data type.
  1570. Examples:
  1571. .. code-block:: python
  1572. :name: diagflat-example-1
  1573. >>> import paddle
  1574. >>> x = paddle.to_tensor([1, 2, 3])
  1575. >>> y = paddle.diagflat(x)
  1576. >>> print(y)
  1577. Tensor(shape=[3, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1578. [[1, 0, 0],
  1579. [0, 2, 0],
  1580. [0, 0, 3]])
  1581. >>> y = paddle.diagflat(x, offset=1)
  1582. >>> print(y)
  1583. Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1584. [[0, 1, 0, 0],
  1585. [0, 0, 2, 0],
  1586. [0, 0, 0, 3],
  1587. [0, 0, 0, 0]])
  1588. >>> y = paddle.diagflat(x, offset=-1)
  1589. >>> print(y)
  1590. Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1591. [[0, 0, 0, 0],
  1592. [1, 0, 0, 0],
  1593. [0, 2, 0, 0],
  1594. [0, 0, 3, 0]])
  1595. .. code-block:: python
  1596. :name: diagflat-example-2
  1597. >>> import paddle
  1598. >>> x = paddle.to_tensor([[1, 2], [3, 4]])
  1599. >>> y = paddle.diagflat(x)
  1600. >>> print(y)
  1601. Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1602. [[1, 0, 0, 0],
  1603. [0, 2, 0, 0],
  1604. [0, 0, 3, 0],
  1605. [0, 0, 0, 4]])
  1606. >>> y = paddle.diagflat(x, offset=1)
  1607. >>> print(y)
  1608. Tensor(shape=[5, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
  1609. [[0, 1, 0, 0, 0],
  1610. [0, 0, 2, 0, 0],
  1611. [0, 0, 0, 3, 0],
  1612. [0, 0, 0, 0, 4],
  1613. [0, 0, 0, 0, 0]])
  1614. >>> y = paddle.diagflat(x, offset=-1)
  1615. >>> print(y)
  1616. Tensor(shape=[5, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
  1617. [[0, 0, 0, 0, 0],
  1618. [1, 0, 0, 0, 0],
  1619. [0, 2, 0, 0, 0],
  1620. [0, 0, 3, 0, 0],
  1621. [0, 0, 0, 4, 0]])
  1622. """
  1623. if in_dynamic_or_pir_mode():
  1624. if len(x.shape) <= 1:
  1625. return _C_ops.diag(x, offset, 0)
  1626. else:
  1627. y = _C_ops.flatten(x, 0, -1)
  1628. return _C_ops.diag(y, offset, 0)
  1629. else:
  1630. padding_value = 0
  1631. check_type(x, 'x', (Variable), 'diagflat')
  1632. check_dtype(
  1633. x.dtype,
  1634. 'x',
  1635. ['float16', 'float32', 'float64', 'int32', 'int64', 'uint16'],
  1636. 'diagflat',
  1637. )
  1638. check_type(offset, 'offset', (int), 'diagflat')
  1639. helper = LayerHelper("diagflat", **locals())
  1640. out1 = helper.create_variable_for_type_inference(dtype=x.dtype)
  1641. out1_shape = helper.create_variable_for_type_inference(x.dtype)
  1642. out2 = helper.create_variable_for_type_inference(dtype=x.dtype)
  1643. if len(x.shape) <= 1:
  1644. helper.append_op(
  1645. type='diag_v2',
  1646. inputs={'X': x},
  1647. outputs={'Out': out2},
  1648. attrs={'offset': offset, 'padding_value': padding_value},
  1649. )
  1650. else:
  1651. helper.append_op(
  1652. type='flatten_contiguous_range',
  1653. inputs={'X': x},
  1654. outputs={'Out': out1, 'XShape': out1_shape},
  1655. attrs={'start_axis': 0, 'stop_axis': -1},
  1656. )
  1657. out1.stop_gradient = True
  1658. helper.append_op(
  1659. type='diag_v2',
  1660. inputs={'X': out1},
  1661. outputs={'Out': out2},
  1662. attrs={'offset': offset, 'padding_value': padding_value},
  1663. )
  1664. out2.stop_gradient = True
  1665. return out2
  1666. def diag(x, offset=0, padding_value=0, name=None):
  1667. """
  1668. If ``x`` is a vector (1-D tensor), a 2-D square tensor with the elements of ``x`` as the diagonal is returned.
  1669. If ``x`` is a matrix (2-D tensor), a 1-D tensor with the diagonal elements of ``x`` is returned.
  1670. The argument ``offset`` controls the diagonal offset:
  1671. If ``offset`` = 0, it is the main diagonal.
  1672. If ``offset`` > 0, it is superdiagonal.
  1673. If ``offset`` < 0, it is subdiagonal.
  1674. Args:
  1675. x (Tensor): The input tensor. Its shape is either 1-D or 2-D. Its data type should be float16, float32, float64, int32, int64, complex64, complex128.
  1676. offset (int, optional): The diagonal offset. A positive value represents superdiagonal, 0 represents the main diagonal, and a negative value represents subdiagonal.
  1677. padding_value (int|float, optional): Use this value to fill the area outside the specified diagonal band. Only takes effect when the input is a 1-D Tensor. The default value is 0.
  1678. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1679. Returns:
  1680. Tensor, a square matrix or a vector. The output data type is the same as input data type.
  1681. Examples:
  1682. .. code-block:: python
  1683. :name: diag-example-1
  1684. >>> import paddle
  1685. >>> paddle.disable_static()
  1686. >>> x = paddle.to_tensor([1, 2, 3])
  1687. >>> y = paddle.diag(x)
  1688. >>> print(y)
  1689. Tensor(shape=[3, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1690. [[1, 0, 0],
  1691. [0, 2, 0],
  1692. [0, 0, 3]])
  1693. >>> y = paddle.diag(x, offset=1)
  1694. >>> print(y)
  1695. Tensor(shape=[4, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1696. [[0, 1, 0, 0],
  1697. [0, 0, 2, 0],
  1698. [0, 0, 0, 3],
  1699. [0, 0, 0, 0]])
  1700. >>> y = paddle.diag(x, padding_value=6)
  1701. >>> print(y)
  1702. Tensor(shape=[3, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1703. [[1, 6, 6],
  1704. [6, 2, 6],
  1705. [6, 6, 3]])
  1706. .. code-block:: python
  1707. :name: diag-example-2
  1708. >>> import paddle
  1709. >>> paddle.disable_static()
  1710. >>> x = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])
  1711. >>> y = paddle.diag(x)
  1712. >>> print(y)
  1713. Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1714. [1, 5])
  1715. >>> y = paddle.diag(x, offset=1)
  1716. >>> print(y)
  1717. Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1718. [2, 6])
  1719. >>> y = paddle.diag(x, offset=-1)
  1720. >>> print(y)
  1721. Tensor(shape=[1], dtype=int64, place=Place(cpu), stop_gradient=True,
  1722. [4])
  1723. """
  1724. if in_dynamic_or_pir_mode():
  1725. return _C_ops.diag(x, offset, padding_value)
  1726. else:
  1727. check_type(x, 'x', (Variable), 'diag_v2')
  1728. check_dtype(
  1729. x.dtype,
  1730. 'x',
  1731. [
  1732. 'float16',
  1733. 'uint16',
  1734. 'float32',
  1735. 'float64',
  1736. 'uint16',
  1737. 'int32',
  1738. 'int64',
  1739. 'complex64',
  1740. 'complex128',
  1741. ],
  1742. 'diag_v2',
  1743. )
  1744. check_type(offset, 'offset', (int), 'diag_v2')
  1745. check_type(padding_value, 'padding_value', (int, float), 'diag_v2')
  1746. if len(x.shape) != 1 and len(x.shape) != 2:
  1747. raise ValueError(
  1748. f"The dimension of input x must be either 1 or 2, but received {len(x.shape)}"
  1749. )
  1750. helper = LayerHelper("diag_v2", **locals())
  1751. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  1752. helper.append_op(
  1753. type='diag_v2',
  1754. inputs={'X': x},
  1755. outputs={'Out': out},
  1756. attrs={'offset': offset, 'padding_value': padding_value},
  1757. )
  1758. out.stop_gradient = True
  1759. return out
  1760. def empty(shape, dtype=None, name=None):
  1761. """
  1762. Returns a Tensor with uninitialized data which size is same as ``shape``.
  1763. Args:
  1764. shape (tuple|list|Tensor): Shape of the Tensor to be created. The data type is ``int32`` or ``int64`` .
  1765. If ``shape`` is a list or tuple, each element of it should be integer or 0-D Tensor with shape [].
  1766. If ``shape`` is an Tensor, it should be an 1-D Tensor which represents a list.
  1767. dtype(np.dtype|str, optional): Data type of the output Tensor
  1768. which can be bool, float16, float32, float64, int32, int64, complex64, complex128 if dtype is `None`, the data
  1769. type of created Tensor use global default dtype (see ``get_default_dtype``
  1770. for details).
  1771. name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1772. Returns:
  1773. Tensor: Tensor which is created according to ``shape`` and ``dtype``, and is uninitialized.
  1774. Examples:
  1775. .. code-block:: python
  1776. >>> import paddle
  1777. >>> # shape is a list/tuple
  1778. >>> data1 = paddle.empty(shape=[3, 2])
  1779. >>> print(data1.numpy())
  1780. >>> # doctest: +SKIP('change everytime')
  1781. [[1. 1.]
  1782. [1. 1.]
  1783. [1. 1.]]
  1784. >>> # shape is a Tensor
  1785. >>> shape = paddle.to_tensor([3, 2])
  1786. >>> data2 = paddle.empty(shape=shape)
  1787. >>> print(data2.numpy())
  1788. >>> # doctest: +SKIP('change everytime')
  1789. [[1. 1.]
  1790. [1. 1.]
  1791. [1. 1.]]
  1792. >>> # shape is a Tensor List
  1793. >>> shape = [paddle.to_tensor(3), paddle.to_tensor(2)]
  1794. >>> data3 = paddle.empty(shape=shape)
  1795. >>> print(data3.numpy())
  1796. >>> # doctest: +SKIP('change everytime')
  1797. [[1. 1.]
  1798. [1. 1.]
  1799. [1. 1.]]
  1800. """
  1801. if dtype is None:
  1802. dtype = paddle.get_default_dtype()
  1803. dtype = convert_dtype(dtype)
  1804. if in_dynamic_or_pir_mode():
  1805. if in_dynamic_mode():
  1806. shape = paddle.utils.convert_shape_to_list(shape)
  1807. else:
  1808. check_dtype(
  1809. dtype,
  1810. 'dtype',
  1811. [
  1812. 'bool',
  1813. 'float16',
  1814. 'float32',
  1815. 'float64',
  1816. 'uint16',
  1817. 'int8',
  1818. 'int16',
  1819. 'int32',
  1820. 'int64',
  1821. 'complex64',
  1822. 'complex128',
  1823. ],
  1824. 'empty',
  1825. )
  1826. paddle.utils.check_shape(shape)
  1827. if isinstance(shape, np.ndarray):
  1828. shape = shape.tolist()
  1829. if isinstance(shape, (list, tuple)):
  1830. if paddle.utils._contain_var(shape):
  1831. shape = paddle.utils.get_int_tensor_list(shape)
  1832. elif isinstance(shape, paddle.pir.Value):
  1833. pass
  1834. else:
  1835. raise TypeError("Shape only supports Value, or list, or tuple.")
  1836. out = _C_ops.empty(
  1837. shape, convert_np_dtype_to_dtype_(dtype), _current_expected_place()
  1838. )
  1839. out.stop_gradient = True
  1840. return out
  1841. else:
  1842. helper = LayerHelper("empty", **locals())
  1843. inputs = {}
  1844. check_dtype(
  1845. dtype,
  1846. 'dtype',
  1847. [
  1848. 'bool',
  1849. 'float16',
  1850. 'float32',
  1851. 'float64',
  1852. 'int8',
  1853. 'int16',
  1854. 'int32',
  1855. 'int64',
  1856. 'complex64',
  1857. 'complex128',
  1858. ],
  1859. 'empty',
  1860. )
  1861. check_type(shape, 'shape', (Variable, list, tuple), 'empty')
  1862. if isinstance(shape, Variable):
  1863. check_dtype(shape.dtype, 'shape', ['int32', 'int64'], 'empty')
  1864. attrs = {}
  1865. paddle.utils.get_shape_tensor_inputs(
  1866. inputs=inputs, attrs=attrs, shape=shape, op_type='empty'
  1867. )
  1868. out = helper.create_variable_for_type_inference(dtype=dtype)
  1869. attrs['dtype'] = convert_np_dtype_to_dtype_(dtype)
  1870. helper.append_op(
  1871. type='empty',
  1872. inputs=inputs,
  1873. outputs={'Out': [out]},
  1874. attrs=attrs,
  1875. stop_gradient=True,
  1876. )
  1877. out.stop_gradient = True
  1878. return out
  1879. def empty_like(x, dtype=None, name=None):
  1880. """
  1881. Returns a Tensor with uninitialized data which has identical shape of ``x`` and ``dtype``.
  1882. If the ``dtype`` is None, the data type of Tensor is same with ``x``.
  1883. Args:
  1884. x(Tensor): The input tensor which specifies shape and data type. The data type can be bool, float16, float32, float64, int32, int64.
  1885. dtype(np.dtype|str, optional): The data type of output. The data type can be one
  1886. of bool, float16, float32, float64, int32, int64. The default value is None, which means the output
  1887. data type is the same as input.
  1888. name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  1889. Returns:
  1890. Tensor: Tensor which is created according to ``x`` and ``dtype``, and is uninitialized.
  1891. Examples:
  1892. .. code-block:: python
  1893. >>> import paddle
  1894. >>> paddle.set_device("cpu") # and use cpu device
  1895. >>> x = paddle.randn([2, 3], 'float32')
  1896. >>> output = paddle.empty_like(x)
  1897. >>> print(output)
  1898. >>> # doctest: +SKIP('change everytime')
  1899. [[1.8491974e+20 1.8037303e+28 1.7443726e+28]
  1900. [4.9640171e+28 3.0186127e+32 5.6715899e-11]]
  1901. """
  1902. if dtype is None:
  1903. dtype = x.dtype
  1904. dtype = convert_dtype(dtype)
  1905. if in_dynamic_mode():
  1906. out = _C_ops.empty(
  1907. x.shape,
  1908. convert_np_dtype_to_dtype_(dtype),
  1909. _current_expected_place(),
  1910. )
  1911. out.stop_gradient = True
  1912. return out
  1913. elif in_pir_mode():
  1914. shape = paddle.shape(x)
  1915. out = _C_ops.empty(
  1916. shape,
  1917. convert_np_dtype_to_dtype_(dtype),
  1918. _current_expected_place(),
  1919. )
  1920. out.stop_gradient = True
  1921. return out
  1922. else:
  1923. helper = LayerHelper("empty_like", **locals())
  1924. check_variable_and_dtype(
  1925. x,
  1926. 'x',
  1927. [
  1928. 'bool',
  1929. 'float16',
  1930. 'float32',
  1931. 'float64',
  1932. 'int8',
  1933. 'int16',
  1934. 'int32',
  1935. 'int64',
  1936. 'uint16',
  1937. 'complex64',
  1938. 'complex128',
  1939. ],
  1940. 'empty_like',
  1941. )
  1942. check_dtype(
  1943. dtype,
  1944. 'dtype',
  1945. [
  1946. 'bool',
  1947. 'float16',
  1948. 'float32',
  1949. 'float64',
  1950. 'int8',
  1951. 'int16',
  1952. 'int32',
  1953. 'int64',
  1954. 'uint16',
  1955. 'complex64',
  1956. 'complex128',
  1957. ],
  1958. 'empty_like',
  1959. )
  1960. out = helper.create_variable_for_type_inference(dtype=dtype)
  1961. inputs = {}
  1962. attrs = {}
  1963. attrs['dtype'] = convert_np_dtype_to_dtype_(dtype)
  1964. shape = paddle.shape(x)
  1965. paddle.utils.get_shape_tensor_inputs(
  1966. inputs=inputs, attrs=attrs, shape=shape, op_type='empty_like'
  1967. )
  1968. helper.append_op(
  1969. type='empty',
  1970. inputs=inputs,
  1971. outputs={'Out': [out]},
  1972. attrs=attrs,
  1973. stop_gradient=True,
  1974. )
  1975. out.stop_gradient = True
  1976. return out
  1977. def assign(x, output=None):
  1978. """
  1979. Copy value of the :attr:`x` to the :attr:`output`.
  1980. Parameters:
  1981. x (Tensor|np.ndarray|list|tuple|scalar): A Tensor, numpy ndarray, tuple/list of scalar,
  1982. or scalar. Its data type can be float16, float32, float64, int32, int64 or bool. Note: the float64 data will be converted to float32 because of current platform protobuf
  1983. data limitation.
  1984. output (Tensor, optional): A Tensor. If :attr:`output` is None, a new Tensor will be created as :attr:`output`. Default: None.
  1985. Returns:
  1986. Tensor: A Tensor with the same shape, data type and value as :attr:`x`.
  1987. Examples:
  1988. .. code-block:: python
  1989. >>> import paddle
  1990. >>> import numpy as np
  1991. >>> data = paddle.full(shape=[3, 2], fill_value=2.5, dtype='float64')
  1992. >>> print(data.numpy())
  1993. [[2.5 2.5]
  1994. [2.5 2.5]
  1995. [2.5 2.5]]
  1996. >>> array = np.array([[1, 1],
  1997. ... [3, 4],
  1998. ... [1, 3]]).astype(np.int64)
  1999. >>> result1 = paddle.zeros(shape=[3, 3], dtype='float32')
  2000. >>> paddle.assign(array, result1)
  2001. >>> print(result1.numpy())
  2002. [[1 1]
  2003. [3 4]
  2004. [1 3]]
  2005. >>> result2 = paddle.assign(data)
  2006. >>> print(result2.numpy())
  2007. [[2.5 2.5]
  2008. [2.5 2.5]
  2009. [2.5 2.5]]
  2010. >>> result3 = paddle.assign(np.array([[2.5, 2.5], [2.5, 2.5], [2.5, 2.5]], dtype='float32'))
  2011. >>> print(result3.numpy())
  2012. [[2.5 2.5]
  2013. [2.5 2.5]
  2014. [2.5 2.5]]
  2015. """
  2016. # speed up
  2017. if x is output and isinstance(x, (Variable, paddle.pir.Value)):
  2018. return x
  2019. input = x
  2020. helper = LayerHelper('assign', **locals())
  2021. check_type(
  2022. input,
  2023. 'input',
  2024. (
  2025. Variable,
  2026. paddle.pir.Value,
  2027. np.ndarray,
  2028. list,
  2029. tuple,
  2030. float,
  2031. int,
  2032. bool,
  2033. ),
  2034. 'assign',
  2035. )
  2036. if np.isscalar(input) and not isinstance(input, str):
  2037. input = np.array([input])
  2038. elif isinstance(input, (list, tuple)):
  2039. input = np.array(input)
  2040. # NOTE(Aurelius84): Why we judge core.Tensor?
  2041. # In case of @to_static, a Tensor can be as input of `assign`,
  2042. # but in_dynamic_mode()==False under @to_static, which means
  2043. # isinstance(Tensor, Variable) == False. It will cause return None
  2044. # after this api.
  2045. if isinstance(input, (Variable, core.eager.Tensor, paddle.pir.Value)):
  2046. if in_dynamic_mode():
  2047. if output is None:
  2048. output = _C_ops.assign(input)
  2049. else:
  2050. _C_ops.assign_out_(input, output)
  2051. elif in_pir_mode():
  2052. if output is None:
  2053. output = _C_ops.assign(input)
  2054. else:
  2055. _C_ops.assign_out_(input, output)
  2056. else:
  2057. check_dtype(
  2058. input.dtype,
  2059. 'input',
  2060. [
  2061. 'float16',
  2062. 'uint16',
  2063. 'float32',
  2064. 'float64',
  2065. 'int32',
  2066. 'int64',
  2067. 'uint8',
  2068. 'int8',
  2069. 'bool',
  2070. 'complex64',
  2071. 'complex128',
  2072. ],
  2073. 'assign',
  2074. '(When the type of input in assign is Variable.)',
  2075. )
  2076. if output is None:
  2077. output = helper.create_variable_for_type_inference(
  2078. dtype=input.dtype
  2079. )
  2080. helper.append_op(
  2081. type='assign', inputs={'X': [input]}, outputs={'Out': [output]}
  2082. )
  2083. elif isinstance(input, np.ndarray):
  2084. # We now support the form of [var, VAR...] if the Var.shape=[1,]
  2085. if len(input.shape) > 0 and any(
  2086. isinstance(x, (Variable, paddle.pir.Value)) for x in input
  2087. ):
  2088. # We only deal with the case where the list is nested one level, convert all scalars into variables, and then use stack to process. It is necessary to ensure the consistency of types.
  2089. if not all(
  2090. x.shape == (1,)
  2091. for x in input
  2092. if isinstance(
  2093. x, (Variable, core.eager.Tensor, paddle.pir.Value)
  2094. )
  2095. ):
  2096. raise TypeError(
  2097. "Unsupport paddle.assign([Variable, Variable...]) with non-scalar variable."
  2098. )
  2099. def convert_scalar(x):
  2100. if not isinstance(
  2101. x, (Variable, core.eager.Tensor, paddle.pir.Value)
  2102. ):
  2103. return assign(x)
  2104. return x
  2105. to_stack_list = list(map(convert_scalar, input))
  2106. ret = paddle.stack(to_stack_list)
  2107. ret = paddle.squeeze(ret, -1)
  2108. return ret
  2109. if input.dtype == 'object':
  2110. """may be this form [[Var], [Var], [3], [4]], we reject them."""
  2111. raise TypeError(
  2112. "The type of received input == `object`, it is not supported to convert to tensor, such as [[Var], [Var], [3], [4]]"
  2113. )
  2114. dtype = convert_np_dtype_to_dtype_(input.dtype)
  2115. check_dtype(
  2116. dtype,
  2117. 'input',
  2118. [
  2119. 'float32',
  2120. 'float64',
  2121. 'int32',
  2122. 'int64',
  2123. 'bool',
  2124. 'complex64',
  2125. 'complex128',
  2126. ],
  2127. 'assign',
  2128. '(When the type of input in assign is numpy array.)',
  2129. )
  2130. value_name = "values"
  2131. values = input.ravel().tolist()
  2132. if input.size > 1024 * 1024:
  2133. raise ValueError(
  2134. "The size of input is too big. Please consider "
  2135. "saving it to file and 'load_op' to load it"
  2136. )
  2137. if in_dynamic_or_pir_mode():
  2138. if output is None:
  2139. output = zeros(list(input.shape), dtype)
  2140. if in_dynamic_mode():
  2141. _C_ops.assign_value_(
  2142. output,
  2143. list(input.shape),
  2144. dtype,
  2145. values,
  2146. _current_expected_place(),
  2147. )
  2148. else:
  2149. output = _C_ops.assign_value_(
  2150. output,
  2151. list(input.shape),
  2152. dtype,
  2153. values,
  2154. _current_expected_place(),
  2155. )
  2156. else:
  2157. if output is None:
  2158. output = helper.create_variable_for_type_inference(
  2159. dtype=input.dtype
  2160. )
  2161. helper.append_op(
  2162. type='assign_value',
  2163. outputs={'Out': [output]},
  2164. attrs={
  2165. 'dtype': dtype,
  2166. 'shape': list(input.shape),
  2167. value_name: values,
  2168. },
  2169. )
  2170. return output
  2171. def clone(x, name=None):
  2172. """
  2173. Returns a copy of input Tensor. It will always have a Tensor copy.
  2174. In addition, This function is derivable, so gradients will flow back from the output to input.
  2175. Parameters:
  2176. x (Tensor): The input Tensor.
  2177. name(str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  2178. Returns:
  2179. Tensor, A Tensor copied from ``input``.
  2180. Examples:
  2181. .. code-block:: python
  2182. >>> import paddle
  2183. >>> import numpy as np
  2184. >>> x = paddle.ones([2])
  2185. >>> x.stop_gradient = False
  2186. >>> x.retain_grads()
  2187. >>> clone_x = paddle.clone(x)
  2188. >>> clone_x.retain_grads()
  2189. >>> y = clone_x**3
  2190. >>> y.backward()
  2191. >>> print(clone_x.grad.numpy())
  2192. [3. 3.]
  2193. >>> print(x.grad.numpy())
  2194. [3. 3.]
  2195. """
  2196. return x.clone()
  2197. # NOTE(zhiqiu): not public
  2198. def _memcpy(input, place=None, output=None):
  2199. """
  2200. The OP copies the :attr:`input` to the :attr:`output`.
  2201. NOTE: currently, only support CUDAPlace <-> CUDAPinnedPlace.
  2202. Parameters:
  2203. input (Tensor): A tensor. Its data type supports float16, float32, float64, int32, int64, and bool.
  2204. device (Place): Target place for the output.
  2205. output (Tensor, optional): A tensor. If :attr:`output` is None, a new tensor will
  2206. be created as :attr:`output`. Default: None.
  2207. Returns:
  2208. Tensor, A tensor with the same shape, data type and value as :attr:`input`.
  2209. Examples:
  2210. .. code-block:: python
  2211. >>> import paddle
  2212. >>> data = paddle.full(shape=[3, 2], fill_value=2.5, dtype='float64')
  2213. >>> print(data.numpy())
  2214. [[2.5 2.5]
  2215. [2.5 2.5]
  2216. [2.5 2.5]]
  2217. >>> # doctest: +SKIP('NOTE(zhiqiu): not public')
  2218. >>> result = paddle._memcpy(data, place=paddle.CPUPlace())
  2219. >>> print(result2)
  2220. [[2.5 2.5]
  2221. [2.5 2.5]
  2222. [2.5 2.5]]
  2223. """
  2224. dst_place_type = -1
  2225. if place is None:
  2226. dst_place_type = -1
  2227. else:
  2228. p = core.Place()
  2229. p.set_place(place)
  2230. if p.is_cpu_place():
  2231. dst_place_type = 0
  2232. elif p.is_gpu_place():
  2233. dst_place_type = 1
  2234. elif p.is_cuda_pinned_place():
  2235. dst_place_type = 2
  2236. elif p.is_xpu_place():
  2237. dst_place_type = 3
  2238. if in_pir_mode():
  2239. return _C_ops.memcpy(input, dst_place_type)
  2240. helper = LayerHelper('memcpy', **locals())
  2241. check_type(input, 'input', (Variable), 'memcpy')
  2242. if isinstance(input, (Variable, core.eager.Tensor)):
  2243. check_dtype(
  2244. input.dtype,
  2245. 'input',
  2246. [
  2247. 'float16',
  2248. 'uint16',
  2249. 'float32',
  2250. 'float64',
  2251. 'int32',
  2252. 'int64',
  2253. 'uint8',
  2254. 'int8',
  2255. 'bool',
  2256. ],
  2257. 'memcpy',
  2258. '(When the type of input in memcpy is Variable.)',
  2259. )
  2260. if output is None:
  2261. output = helper.create_variable_for_type_inference(dtype=input.dtype)
  2262. attrs = {'dst_place_type': dst_place_type}
  2263. helper.append_op(
  2264. type='memcpy',
  2265. inputs={'X': [input]},
  2266. outputs={'Out': [output]},
  2267. attrs=attrs,
  2268. )
  2269. return output
  2270. def complex(real, imag, name=None):
  2271. """Return a complex tensor given the real and image component.
  2272. Args:
  2273. real (Tensor): The real component. The data type should be 'float32' or 'float64'.
  2274. imag (Tensor): The image component. The data type should be the same as ``real``.
  2275. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  2276. Returns:
  2277. Tensor: The output tensor. The data type is 'complex64' or 'complex128', with the same precision as ``real`` and ``imag``.
  2278. Note:
  2279. ``paddle.complex`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  2280. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  2281. Examples:
  2282. .. code-block:: python
  2283. >>> import paddle
  2284. >>> x = paddle.arange(2, dtype=paddle.float32).unsqueeze(-1)
  2285. >>> y = paddle.arange(3, dtype=paddle.float32)
  2286. >>> z = paddle.complex(x, y)
  2287. >>> print(z)
  2288. Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
  2289. [[0j , 1j , 2j ],
  2290. [(1+0j), (1+1j), (1+2j)]])
  2291. """
  2292. if in_dynamic_or_pir_mode():
  2293. return _C_ops.complex(real, imag)
  2294. else:
  2295. check_variable_and_dtype(
  2296. real, 'real', ['float32', 'float64'], 'complex'
  2297. )
  2298. check_variable_and_dtype(
  2299. imag, 'imag', ['float32', 'float64'], 'complex'
  2300. )
  2301. op_type = "complex"
  2302. helper = LayerHelper(op_type, **locals())
  2303. inputs = {"X": real, "Y": imag}
  2304. out = helper.create_variable_for_type_inference(
  2305. dtype=_real_to_complex_dtype(real.dtype)
  2306. )
  2307. outputs = {"Out": out}
  2308. attrs = {}
  2309. helper.append_op(
  2310. type=op_type, inputs=inputs, attrs=attrs, outputs=outputs
  2311. )
  2312. return out
  2313. def tril_indices(row, col, offset=0, dtype='int64'):
  2314. """
  2315. Return the indices of the lower triangular part of the 2-D matrix
  2316. whose row and col is known. Indices are ordered based on row and then columns.
  2317. The lower triangular part of the matrix is defined as the elements on
  2318. and below the diagonal.
  2319. Args:
  2320. row (int): The input x which is a int number describe the number of row of the matrix.
  2321. col (int): The input x which is a int number describe the number of col of the matrix.
  2322. offset (int, optional): The offset to consider, default value is 0.
  2323. - If offset = 0, all elements on and below the main diagonal are retained.
  2324. - If offset > 0, include just as many diagonals above the main diagonal.
  2325. - If offset < 0, excludes just as many diagonals below the main diagonal.
  2326. dtype (int, optional): the data type of the output tensor, can be int32, int64.
  2327. Returns:
  2328. Tensor: Results of the indices of lower triangular part of a row * col matrix,
  2329. where the first row contains row coordinates of and the second row contains column coordinates.
  2330. Examples:
  2331. .. code-block:: python
  2332. >>> import paddle
  2333. >>> # example 1, default offset value
  2334. >>> data1 = paddle.tril_indices(4,4,0)
  2335. >>> print(data1)
  2336. Tensor(shape=[2, 10], dtype=int64, place=Place(cpu), stop_gradient=True,
  2337. [[0, 1, 1, 2, 2, 2, 3, 3, 3, 3],
  2338. [0, 0, 1, 0, 1, 2, 0, 1, 2, 3]])
  2339. >>> # example 2, positive offset value
  2340. >>> data2 = paddle.tril_indices(4,4,2)
  2341. >>> print(data2)
  2342. Tensor(shape=[2, 15], dtype=int64, place=Place(cpu), stop_gradient=True,
  2343. [[0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3],
  2344. [0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3]])
  2345. >>> # example 3, negative offset value
  2346. >>> data3 = paddle.tril_indices(4,4,-1)
  2347. >>> print(data3)
  2348. Tensor(shape=[2, 6], dtype=int64, place=Place(cpu), stop_gradient=True,
  2349. [[1, 2, 2, 3, 3, 3],
  2350. [0, 0, 1, 0, 1, 2]])
  2351. """
  2352. if not isinstance(dtype, core.VarDesc.VarType):
  2353. dtype = convert_np_dtype_to_dtype_(dtype)
  2354. if not isinstance(row, int) or row < 0:
  2355. raise TypeError("row should be a non-negative int")
  2356. if col is not None:
  2357. if not isinstance(col, int) or col < 0:
  2358. raise TypeError("col should be a non-negative int")
  2359. else:
  2360. col = row
  2361. if in_dynamic_or_pir_mode():
  2362. if col is None:
  2363. col = row
  2364. out = _C_ops.tril_indices(
  2365. row, col, offset, dtype, _current_expected_place()
  2366. )
  2367. return out
  2368. else:
  2369. if not isinstance(offset, int):
  2370. raise TypeError("offset should be a int")
  2371. helper = LayerHelper("tril_indices", **locals())
  2372. out = helper.create_variable_for_type_inference(dtype=dtype)
  2373. helper.append_op(
  2374. type='tril_indices',
  2375. inputs={},
  2376. outputs={'out': [out]},
  2377. attrs={'rows': row, 'cols': col, 'offset': offset, 'dtype': dtype},
  2378. )
  2379. return out
  2380. def triu_indices(row, col=None, offset=0, dtype='int64'):
  2381. """
  2382. Return the indices of the upper triangular part of the 2-D matrix
  2383. whose row and col is known. Indices are ordered based on row and then columns.
  2384. The upper triangular part of the matrix is defined as the elements on
  2385. and above the diagonal.
  2386. Args:
  2387. row (int): The input x which is a int number describe the number of row of the matrix.
  2388. col (int, optional): The input x which is a int number describe the number of col of the matrix.
  2389. default value for col is None, then it will be set equal to row, indicting a square matrix.
  2390. offset (int, optional): The offset to consider, default value is 0.
  2391. - If offset = 0, all elements on and above the main diagonal are retained.
  2392. - If offset > 0, include just as few diagonals above the main diagonal.
  2393. - If offset < 0, excludes just as few diagonals below the main diagonal.
  2394. dtype (str|np.dtype|paddle.dtype, optional): the data type of the output tensor,
  2395. can be int32, int64, default value is int64.
  2396. Returns:
  2397. Tensor: Results of the indices of upper triangular part of a row * col matrix,
  2398. where the first row contains row coordinates of and the second row contains column coordinates.
  2399. Examples:
  2400. .. code-block:: python
  2401. >>> import paddle
  2402. >>> # example 1, default offset value
  2403. >>> data1 = paddle.triu_indices(4,4,0)
  2404. >>> print(data1.numpy())
  2405. [[0 0 0 0 1 1 1 2 2 3]
  2406. [0 1 2 3 1 2 3 2 3 3]]
  2407. >>> # example 2, positive offset value
  2408. >>> data2 = paddle.triu_indices(4,4,2)
  2409. >>> print(data2.numpy())
  2410. [[0 0 1]
  2411. [2 3 3]]
  2412. >>> # example 3, negative offset value
  2413. >>> data3 = paddle.triu_indices(4,4,-1)
  2414. >>> print(data3.numpy())
  2415. [[0 0 0 0 1 1 1 1 2 2 2 3 3]
  2416. [0 1 2 3 0 1 2 3 1 2 3 2 3]]
  2417. """
  2418. if not isinstance(dtype, core.VarDesc.VarType):
  2419. dtype = convert_np_dtype_to_dtype_(dtype)
  2420. if not isinstance(row, int) or row < 0:
  2421. raise TypeError("row should be a non-negative int")
  2422. if col is not None:
  2423. if not isinstance(col, int) or col < 0:
  2424. raise TypeError("col should be a non-negative int")
  2425. else:
  2426. col = row
  2427. if in_dynamic_or_pir_mode():
  2428. if col is None:
  2429. col = row
  2430. out = _C_ops.triu_indices(
  2431. row, col, offset, dtype, _current_expected_place()
  2432. )
  2433. return out
  2434. else:
  2435. if not isinstance(offset, int):
  2436. raise TypeError("offset should be a int")
  2437. helper = LayerHelper("triu_indices", **locals())
  2438. out = helper.create_variable_for_type_inference(dtype=dtype)
  2439. helper.append_op(
  2440. type='triu_indices',
  2441. inputs={},
  2442. outputs={'out': [out]},
  2443. attrs={'row': row, 'col': col, 'offset': offset, 'dtype': dtype},
  2444. )
  2445. return out
  2446. def polar(abs, angle, name=None):
  2447. """Return a Cartesian coordinates corresponding to the polar coordinates complex tensor given the ``abs`` and ``angle`` component.
  2448. Args:
  2449. abs (Tensor): The abs component. The data type should be 'float32' or 'float64'.
  2450. angle (Tensor): The angle component. The data type should be the same as ``abs``.
  2451. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  2452. Returns:
  2453. Tensor: The output tensor. The data type is 'complex64' or 'complex128', with the same precision as ``abs`` and ``angle``.
  2454. Note:
  2455. ``paddle.polar`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  2456. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  2457. Examples:
  2458. .. code-block:: python
  2459. >>> import paddle
  2460. >>> import numpy as np
  2461. >>> abs = paddle.to_tensor([1, 2], dtype=paddle.float64)
  2462. >>> angle = paddle.to_tensor([np.pi / 2, 5 * np.pi / 4], dtype=paddle.float64)
  2463. >>> out = paddle.polar(abs, angle)
  2464. >>> print(out)
  2465. Tensor(shape=[2], dtype=complex128, place=Place(cpu), stop_gradient=True,
  2466. [ (6.123233995736766e-17+1j) ,
  2467. (-1.4142135623730954-1.414213562373095j)])
  2468. """
  2469. check_variable_and_dtype(abs, 'abs', ['float32', 'float64'], 'paddle.polar')
  2470. check_variable_and_dtype(
  2471. angle, 'angle', ['float32', 'float64'], 'paddle.polar'
  2472. )
  2473. return paddle.complex(abs * paddle.cos(angle), abs * paddle.sin(angle))
  2474. @dygraph_only
  2475. def cauchy_(x, loc=0, scale=1, name=None):
  2476. """Fills the tensor with numbers drawn from the Cauchy distribution.
  2477. Args:
  2478. x (Tensor): the tensor will be filled, The data type is float32 or float64.
  2479. loc (scalar, optional): Location of the peak of the distribution. The data type is float32 or float64.
  2480. scale (scalar, optional): The half-width at half-maximum (HWHM). The data type is float32 or float64. Must be positive values.
  2481. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  2482. Returns:
  2483. Tensor: input tensor with numbers drawn from the Cauchy distribution.
  2484. Examples:
  2485. .. code-block:: python
  2486. >>> import paddle
  2487. >>> x = paddle.randn([3, 4])
  2488. >>> x.cauchy_(1, 2)
  2489. >>> # doctest: +SKIP('random check')
  2490. >>> print(x)
  2491. Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  2492. [[ 3.80087137, 2.25415039, 2.77960515, 7.64125967],
  2493. [ 0.76541221, 2.74023032, 1.99383152, -0.12685823],
  2494. [ 1.45228469, 1.76275957, -4.30458832, 34.74880219]])
  2495. """
  2496. x.normal_()
  2497. loc = paddle.to_tensor(loc).astype(x.dtype)
  2498. half = paddle.to_tensor(0.5).astype(x.dtype)
  2499. x.subtract_(half).scale_(np.pi).tan_().scale_(scale).add_(loc)
  2500. return x
  2501. @dygraph_only
  2502. def geometric_(x, probs, name=None):
  2503. """Fills the tensor with numbers drawn from the Geometric distribution.
  2504. Args:
  2505. x (Tensor): the tensor will be filled, The data type is float32 or float64.
  2506. probs (Real|Tensor): Probability parameter.
  2507. The value of probs must be positive. When the parameter is a tensor, probs is probability of success for each trial.
  2508. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  2509. Returns:
  2510. Tensor: input tensor with numbers drawn from the Geometric distribution.
  2511. Examples:
  2512. .. code-block:: python
  2513. >>> import paddle
  2514. >>> x = paddle.randn([3, 4])
  2515. >>> x.geometric_(0.3)
  2516. >>> # doctest: +SKIP('random check')
  2517. >>> print(x)
  2518. Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  2519. [[2.42739224, 4.78268528, 1.23302543, 3.76555204],
  2520. [1.38877118, 0.16075331, 0.16401523, 2.47349310],
  2521. [1.72872102, 2.76533413, 0.33410925, 1.63351011]])
  2522. """
  2523. tiny = np.finfo(dtype=convert_dtype(x.dtype)).tiny
  2524. probs = paddle.to_tensor(probs).astype(x.dtype)
  2525. x.uniform_(min=float(tiny), max=float(1))
  2526. x.log_().divide_(paddle.log1p(-(probs)))
  2527. return x