You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

math_ops.py 130 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595
  1. # Copyright 2020 Huawei Technologies Co., Ltd
  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. # ============================================================================
  15. """Operators for math."""
  16. import copy
  17. import numpy as np
  18. from ... import context
  19. from .. import signature as sig
  20. from ..._checkparam import Validator as validator
  21. from ..._checkparam import Rel
  22. from ...common import dtype as mstype
  23. from ...common.tensor import Tensor
  24. from .._utils import get_broadcast_shape
  25. from ..primitive import PrimitiveWithInfer, PrimitiveWithCheck, prim_attr_register, _run_op
  26. def _infer_shape_reduce(x, axis, keep_dims, prim_name):
  27. """Common infer for reduce operator"""
  28. def reduce_one_axis(one_axis):
  29. validator.check_int_range(one_axis, -dim, dim, Rel.INC_LEFT, 'axis', prim_name)
  30. if one_axis < 0:
  31. one_axis += dim
  32. axis_reduce.add(one_axis)
  33. validator.check_value_type('axis', axis, [int, tuple, list], prim_name)
  34. dim = len(x)
  35. axis_reduce = set()
  36. if isinstance(axis, int):
  37. reduce_one_axis(axis)
  38. else:
  39. if not axis:
  40. if keep_dims:
  41. return [1] * dim
  42. return []
  43. for index, one_axis in enumerate(axis):
  44. validator.check_value_type('axis[%d]' % index, one_axis, [int], prim_name)
  45. reduce_one_axis(one_axis)
  46. out_shape = []
  47. for i in range(dim):
  48. if i in axis_reduce:
  49. if keep_dims:
  50. out_shape.append(1)
  51. else:
  52. out_shape.append(x[i])
  53. return out_shape
  54. class _BinaryOp(PrimitiveWithInfer):
  55. """
  56. Define binary operators.
  57. """
  58. __mindspore_signature__ = (sig.sig_dtype.T, sig.sig_dtype.T)
  59. @prim_attr_register
  60. def __init__(self):
  61. """Initialize _BinaryOp"""
  62. self.init_prim_io_names(inputs=['x', 'y'], outputs=['output'])
  63. def infer_shape(self, x_shape, y_shape):
  64. return get_broadcast_shape(x_shape, y_shape, self.name)
  65. class _MathBinaryOp(_BinaryOp):
  66. """
  67. Define math binary operators.
  68. """
  69. @staticmethod
  70. def do_infer_dtype(x_dtype, y_dtype, valid_dtype=mstype.number_type, prim_name=None):
  71. args_type = {"x": x_dtype, "y": y_dtype}
  72. validator.check_tensor_type_same(args_type, valid_dtype, prim_name)
  73. return x_dtype
  74. def infer_dtype(self, x_dtype, y_dtype):
  75. return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, mstype.number_type, self.name)
  76. class _BitwiseBinaryOp(_MathBinaryOp):
  77. """
  78. Define bitwise binary operators.
  79. """
  80. @prim_attr_register
  81. def __init__(self):
  82. """Initialize _BitwiseBinaryOp"""
  83. self.init_prim_io_names(inputs=['x1', 'x2'], outputs=['y'])
  84. @staticmethod
  85. def _check_bitwise_op_input_type(x1_type, x2_type, prim):
  86. args = {'x1': x1_type, 'x2': x2_type}
  87. valid_types = mstype.int_type + mstype.uint_type
  88. validator.check_tensor_type_same(args, valid_types, prim)
  89. return x1_type
  90. def infer_dtype(self, x1_type, x2_type):
  91. return _BitwiseBinaryOp._check_bitwise_op_input_type(x1_type, x2_type, self.name)
  92. class TensorAdd(_MathBinaryOp):
  93. """
  94. Adds two input tensors element-wise.
  95. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  96. The inputs must be two tensors or one tensor and one scalar.
  97. When the inputs are two tensors,
  98. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  99. When the inputs are one tensor and one scalar,
  100. the scalar could only be a constant.
  101. Inputs:
  102. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  103. or a tensor whose data type is number or bool.
  104. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number, or a bool when the first input
  105. is a tensor, or a tensor whose data type is number or bool.
  106. Outputs:
  107. Tensor, the shape is the same as the one after broadcasting,
  108. and the data type is the one with higher precision or higher digits among the two inputs.
  109. Examples:
  110. >>> add = P.TensorAdd()
  111. >>> input_x = Tensor(np.array([1,2,3]).astype(np.float32))
  112. >>> input_y = Tensor(np.array([4,5,6]).astype(np.float32))
  113. >>> add(input_x, input_y)
  114. [5,7,9]
  115. """
  116. def infer_value(self, x, y):
  117. if x is not None and y is not None:
  118. x = x.asnumpy()
  119. y = y.asnumpy()
  120. out = x + y
  121. out = np.array(out, x.dtype)
  122. return Tensor(out)
  123. return None
  124. class AssignAdd(PrimitiveWithInfer):
  125. """
  126. Updates a `Parameter` by adding a value to it.
  127. Inputs of `variable` and `value` comply with the implicit type conversion rules to make the data types consistent.
  128. If they have different data types, lower priority data type will be converted to
  129. relatively highest priority data type.
  130. If `value` is a number, the number is automatically converted to Tensor,
  131. and the data type is consistent with the Tensor data type involved in the operation.
  132. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  133. Inputs:
  134. - **variable** (Parameter) - The `Parameter`.
  135. - **value** (Union[numbers.Number, Tensor]) - The value to be added to the `variable`.
  136. It must have the same shape as `variable` if it is a Tensor.
  137. Examples:
  138. >>> class Net(Cell):
  139. >>> def __init__(self):
  140. >>> super(Net, self).__init__()
  141. >>> self.AssignAdd = P.AssignAdd()
  142. >>> self.variable = mindspore.Parameter(initializer(1, [1], mindspore.int64), name="global_step")
  143. >>>
  144. >>> def construct(self, x):
  145. >>> self.AssignAdd(self.variable, x)
  146. >>> return self.variable
  147. >>>
  148. >>> net = Net()
  149. >>> value = Tensor(np.ones([1]).astype(np.int64)*100)
  150. >>> net(value)
  151. """
  152. __mindspore_signature__ = (
  153. sig.make_sig('x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
  154. sig.make_sig('value', dtype=sig.sig_dtype.T)
  155. )
  156. @prim_attr_register
  157. def __init__(self):
  158. """Initialize AssignAdd"""
  159. self.init_prim_io_names(inputs=['ref', 'value'], outputs=['output'])
  160. def infer_shape(self, variable, value):
  161. return value
  162. def infer_dtype(self, variable, value):
  163. args = {"variable": variable, "value": value}
  164. validator.check_scalar_or_tensor_type_same(args, mstype.number_type, self.name)
  165. return value
  166. class AssignSub(PrimitiveWithInfer):
  167. """
  168. Updates a `Parameter` by subtracting a value from it.
  169. Inputs of `variable` and `value` comply with the implicit type conversion rules to make the data types consistent.
  170. If they have different data types, lower priority data type will be converted to
  171. relatively highest priority data type.
  172. If `value` is a number, the number is automatically converted to Tensor,
  173. and the data type is consistent with the Tensor data type involved in the operation.
  174. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  175. Inputs:
  176. - **variable** (Parameter) - The `Parameter`.
  177. - **value** (Union[numbers.Number, Tensor]) - The value to be subtracted from the `variable`.
  178. It must have the same shape as `variable` if it is a Tensor.
  179. Examples:
  180. >>> class Net(Cell):
  181. >>> def __init__(self):
  182. >>> super(Net, self).__init__()
  183. >>> self.AssignSub = P.AssignSub()
  184. >>> self.variable = mindspore.Parameter(initializer(1, [1], mindspore.int32), name="global_step")
  185. >>>
  186. >>> def construct(self, x):
  187. >>> self.AssignSub(self.variable, x)
  188. >>> return self.variable
  189. >>>
  190. >>> net = Net()
  191. >>> value = Tensor(np.ones([1]).astype(np.int32)*100)
  192. >>> net(value)
  193. """
  194. __mindspore_signature__ = (
  195. sig.make_sig('variable', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
  196. sig.make_sig('value', dtype=sig.sig_dtype.T)
  197. )
  198. @prim_attr_register
  199. def __init__(self):
  200. """Initialize AssignSub"""
  201. def infer_shape(self, variable, value):
  202. return value
  203. def infer_dtype(self, variable, value):
  204. args = {"variable": variable, "value": value}
  205. validator.check_scalar_or_tensor_type_same(args, mstype.number_type, self.name)
  206. return value
  207. class _Reduce(PrimitiveWithInfer):
  208. """
  209. Definition of base class of reduction class operators.
  210. Args:
  211. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  212. If false, don't keep these dimensions.
  213. """
  214. __mindspore_signature__ = (
  215. sig.make_sig('input_x'),
  216. sig.make_sig('axis', default=())
  217. )
  218. @prim_attr_register
  219. def __init__(self, keep_dims=False):
  220. """Initialize Reduce"""
  221. validator.check_value_type('keep_dims', keep_dims, [bool], self.name)
  222. self.init_prim_io_names(inputs=['input_x', 'axis'], outputs=['y'])
  223. self.add_prim_attr("io_format", "ND")
  224. def __call__(self, x, axis=()):
  225. args = [x, axis]
  226. output = _run_op(self, self.name, args)
  227. return output
  228. def do_infer(self, input_x, axis, valid_dtype=mstype.number_type):
  229. """ return meta infos of input parameters """
  230. axis_v = axis['value']
  231. input_shp = input_x['shape']
  232. args = {'input_x': input_x['dtype']}
  233. validator.check_tensor_type_same(args, valid_dtype, self.name)
  234. if axis_v is None:
  235. raise ValueError(f"For {self.name}, axis must be const.")
  236. input_shp = _infer_shape_reduce(input_shp, axis_v, self.keep_dims, self.name)
  237. value = None
  238. if input_x['value'] is not None:
  239. prim_map = {
  240. 'ReduceSum': np.sum,
  241. 'ReduceMax': np.max,
  242. 'ReduceMin': np.min,
  243. }
  244. np_reduce_func = prim_map.get(self.name, None)
  245. if np_reduce_func is not None:
  246. value = input_x['value'].asnumpy()
  247. if not axis_v:
  248. axis_v = [i for i in range(len(input_x['shape']))]
  249. axis_v = tuple(axis_v)
  250. value = np_reduce_func(value, axis_v, keepdims=self.keep_dims)
  251. value = np.array(value)
  252. value = Tensor(value)
  253. return {'shape': input_shp,
  254. 'dtype': input_x['dtype'],
  255. 'value': value}
  256. def __infer__(self, input_x, axis):
  257. return self.do_infer(input_x, axis)
  258. class ReduceMean(_Reduce):
  259. """
  260. Reduce a dimension of a tensor by averaging all elements in the dimension.
  261. The dtype of the tensor to be reduced is number.
  262. Args:
  263. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  264. If false, don't keep these dimensions. Default: False.
  265. Inputs:
  266. - **input_x** (Tensor[Number]) - The input tensor.
  267. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  268. Only constant value is allowed. Must be in the range [-rank(input_x), rank(input_x)).
  269. Outputs:
  270. Tensor, has the same dtype as the `input_x`.
  271. - If axis is (), and keep_dims is False,
  272. the output is a 0-D tensor representing the mean of all elements in the input tensor.
  273. - If axis is int, set as 2, and keep_dims is False,
  274. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  275. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  276. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  277. Examples:
  278. >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  279. >>> op = P.ReduceMean(keep_dims=True)
  280. >>> output = op(input_x, 1)
  281. >>> output.shape
  282. (3, 1, 5, 6)
  283. """
  284. class ReduceSum(_Reduce):
  285. """
  286. Reduce a dimension of a tensor by summing all elements in the dimension.
  287. The dtype of the tensor to be reduced is number.
  288. Args:
  289. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  290. If false, don't keep these dimensions. Default: False.
  291. Inputs:
  292. - **input_x** (Tensor[Number]) - The input tensor.
  293. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  294. Only constant value is allowed. Must be in the range [-rank(input_x), rank(input_x)).
  295. Outputs:
  296. Tensor, has the same dtype as the `input_x`.
  297. - If axis is (), and keep_dims is False,
  298. the output is a 0-D tensor representing the sum of all elements in the input tensor.
  299. - If axis is int, set as 2, and keep_dims is False,
  300. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  301. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  302. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  303. Examples:
  304. >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  305. >>> op = P.ReduceSum(keep_dims=True)
  306. >>> output = op(input_x, 1)
  307. >>> output.shape
  308. (3, 1, 5, 6)
  309. """
  310. @prim_attr_register
  311. def __init__(self, keep_dims=False):
  312. """Initialize ReduceSum"""
  313. super(ReduceSum, self).__init__(keep_dims)
  314. self.__setattr_flag__ = True
  315. class ReduceAll(_Reduce):
  316. """
  317. Reduce a dimension of a tensor by the "logical and" of all elements in the dimension.
  318. The dtype of the tensor to be reduced is bool.
  319. Args:
  320. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  321. If false, don't keep these dimensions.
  322. Default : False, don't keep these reduced dimensions.
  323. Inputs:
  324. - **input_x** (Tensor[bool]) - The input tensor.
  325. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  326. Only constant value is allowed. Must be in the range [-rank(input_x), rank(input_x)).
  327. Outputs:
  328. Tensor, the dtype is bool.
  329. - If axis is (), and keep_dims is False,
  330. the output is a 0-D tensor representing the "logical and" of all elements in the input tensor.
  331. - If axis is int, set as 2, and keep_dims is False,
  332. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  333. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  334. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  335. Examples:
  336. >>> input_x = Tensor(np.array([[True, False], [True, True]]))
  337. >>> op = P.ReduceAll(keep_dims=True)
  338. >>> output = op(input_x, 1)
  339. [[False]
  340. [True ]]
  341. """
  342. def __infer__(self, input_x, axis):
  343. return self.do_infer(input_x, axis, (mstype.bool_,))
  344. class ReduceAny(_Reduce):
  345. """
  346. Reduce a dimension of a tensor by the "logical OR" of all elements in the dimension.
  347. The dtype of the tensor to be reduced is bool.
  348. Args:
  349. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  350. If false, don't keep these dimensions.
  351. Default : False, don't keep these reduced dimensions.
  352. Inputs:
  353. - **input_x** (Tensor[bool]) - The input tensor.
  354. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  355. Only constant value is allowed. Must be in the range [-rank(input_x), rank(input_x)).
  356. Outputs:
  357. Tensor, the dtype is bool.
  358. - If axis is (), and keep_dims is False,
  359. the output is a 0-D tensor representing the "logical or" of all elements in the input tensor.
  360. - If axis is int, set as 2, and keep_dims is False,
  361. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  362. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  363. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  364. Examples:
  365. >>> input_x = Tensor(np.array([[True, False], [True, True]]))
  366. >>> op = P.ReduceAny(keep_dims=True)
  367. >>> output = op(input_x, 1)
  368. [[True],
  369. [True]]
  370. """
  371. def __infer__(self, input_x, axis):
  372. return self.do_infer(input_x, axis, (mstype.bool_,))
  373. class ReduceMax(_Reduce):
  374. """
  375. Reduce a dimension of a tensor by the maximum value in this dimension.
  376. The dtype of the tensor to be reduced is number.
  377. Args:
  378. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  379. If false, don't keep these dimensions.
  380. Default : False, don't keep these reduced dimensions.
  381. Inputs:
  382. - **input_x** (Tensor[Number]) - The input tensor.
  383. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  384. Only constant value is allowed. Must be in the range [-rank(input_x), rank(input_x)).
  385. Outputs:
  386. Tensor, has the same dtype as the `input_x`.
  387. - If axis is (), and keep_dims is False,
  388. the output is a 0-D tensor representing the maximum of all elements in the input tensor.
  389. - If axis is int, set as 2, and keep_dims is False,
  390. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  391. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  392. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  393. Examples:
  394. >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  395. >>> op = P.ReduceMax(keep_dims=True)
  396. >>> output = op(input_x, 1)
  397. """
  398. @prim_attr_register
  399. def __init__(self, keep_dims=False):
  400. """ReduceMax"""
  401. super(ReduceMax, self).__init__(keep_dims)
  402. self.__setattr_flag__ = True
  403. def __infer__(self, input_x, axis):
  404. return self.do_infer(input_x, axis, mstype.number_type + (mstype.bool_,))
  405. class ReduceMin(_Reduce):
  406. """
  407. Reduce a dimension of a tensor by the minimum value in the dimension.
  408. The dtype of the tensor to be reduced is number.
  409. Args:
  410. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  411. If false, don't keep these dimensions.
  412. Default : False, don't keep these reduced dimensions.
  413. Inputs:
  414. - **input_x** (Tensor[Number]) - The input tensor.
  415. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  416. Only constant value is allowed. Must be in the range [-rank(input_x), rank(input_x)).
  417. Outputs:
  418. Tensor, has the same dtype as the `input_x`.
  419. - If axis is (), and keep_dims is False,
  420. the output is a 0-D tensor representing the minimum of all elements in the input tensor.
  421. - If axis is int, set as 2, and keep_dims is False,
  422. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  423. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  424. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  425. Examples:
  426. >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  427. >>> op = P.ReduceMin(keep_dims=True)
  428. >>> output = op(input_x, 1)
  429. >>> output.shape
  430. (3, 1, 5, 6)
  431. """
  432. class ReduceProd(_Reduce):
  433. """
  434. Reduce a dimension of a tensor by multiplying all elements in the dimension.
  435. The dtype of the tensor to be reduced is number.
  436. Args:
  437. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  438. If false, don't keep these dimensions.
  439. Default : False, don't keep these reduced dimensions.
  440. Inputs:
  441. - **input_x** (Tensor[Number]) - The input tensor.
  442. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  443. Only constant value is allowed. Must be in the range [-rank(input_x), rank(input_x)).
  444. Outputs:
  445. Tensor, has the same dtype as the `input_x`.
  446. - If axis is (), and keep_dims is False,
  447. the output is a 0-D tensor representing the product of all elements in the input tensor.
  448. - If axis is int, set as 2, and keep_dims is False,
  449. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  450. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  451. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  452. Examples:
  453. >>> input_x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  454. >>> op = P.ReduceProd(keep_dims=True)
  455. >>> output = op(input_x, 1)
  456. """
  457. class CumProd(PrimitiveWithInfer):
  458. """
  459. Compute the cumulative product of the tensor x along axis.
  460. Args:
  461. exclusive (bool): If true, perform exclusive cumulative product. Default: False.
  462. reverse (bool): If true, reverse the result along axis. Default: False
  463. Inputs:
  464. - **input_x** (Tensor[Number]) - The input tensor.
  465. - **axis** (int) - The dimensions to compute the cumulative product.
  466. Only constant value is allowed.
  467. Outputs:
  468. Tensor, has the same shape and dtype as the `input_x`.
  469. Examples:
  470. >>> input_x = Tensor(np.array([a, b, c]).astype(np.float32))
  471. >>> op0 = P.CumProd()
  472. >>> output = op0(input_x, 0) # output=[a, a * b, a * b * c]
  473. >>> op1 = P.CumProd(exclusive=True)
  474. >>> output = op1(input_x, 0) # output=[1, a, a * b]
  475. >>> op2 = P.CumProd(reverse=True)
  476. >>> output = op2(input_x, 0) # output=[a * b * c, b * c, c]
  477. >>> op3 = P.CumProd(exclusive=True, reverse=True)
  478. >>> output = op3(input_x, 0) # output=[b * c, c, 1]
  479. """
  480. @prim_attr_register
  481. def __init__(self, exclusive=False, reverse=False):
  482. cls_name = self.name
  483. self.exclusive = validator.check_value_type("exclusive", exclusive, [bool], cls_name)
  484. self.reverse = validator.check_value_type("reverse", reverse, [bool], cls_name)
  485. self.init_prim_io_names(inputs=['x', 'axis'], outputs=['y'])
  486. def infer_shape(self, x_shape, axis_shape):
  487. return x_shape
  488. def infer_dtype(self, x_type, axis_type):
  489. cls_name = self.name
  490. validator.check_tensor_type_same({'x': x_type}, mstype.number_type, cls_name)
  491. validator.check_subclass("axis", axis_type, mstype.int_, cls_name)
  492. return x_type
  493. def infer_value(self, x, axis):
  494. if axis is None:
  495. raise ValueError(f"For {self.name}, axis must be const.")
  496. class MatMul(PrimitiveWithInfer):
  497. """
  498. Multiplies matrix `a` and matrix `b`.
  499. The rank of input tensors must equal to `2`.
  500. Args:
  501. transpose_a (bool): If true, `a` is transposed before multiplication. Default: False.
  502. transpose_b (bool): If true, `b` is transposed before multiplication. Default: False.
  503. Inputs:
  504. - **input_x** (Tensor) - The first tensor to be multiplied. The shape of the tensor is :math:`(N, C)`. If
  505. `transpose_a` is True, its shape must be :math:`(N, C)` after transposing.
  506. - **input_y** (Tensor) - The second tensor to be multiplied. The shape of the tensor is :math:`(C, M)`. If
  507. `transpose_b` is True, its shape must be :math:`(C, M)` after transpose.
  508. Outputs:
  509. Tensor, the shape of the output tensor is :math:`(N, M)`.
  510. Examples:
  511. >>> input_x1 = Tensor(np.ones(shape=[1, 3]), mindspore.float32)
  512. >>> input_x2 = Tensor(np.ones(shape=[3, 4]), mindspore.float32)
  513. >>> matmul = P.MatMul()
  514. >>> output = matmul(input_x1, input_x2)
  515. """
  516. @prim_attr_register
  517. def __init__(self, transpose_a=False, transpose_b=False):
  518. self.init_prim_io_names(inputs=['x1', 'x2'], outputs=['output'])
  519. cls_name = self.name
  520. validator.check_value_type("transpose_a", transpose_a, [bool], cls_name)
  521. validator.check_value_type("transpose_b", transpose_b, [bool], cls_name)
  522. self.add_prim_attr("io_format", "ND")
  523. def check_shape_size(self, x1, x2):
  524. if len(x1) != 2 or len(x2) != 2:
  525. raise ValueError('P.MatMul inputs x1, x2 should has the same dimension size and '
  526. + f'equal to 2, while x1 size is ({len(x1)}) and x2 size is ({len(x2)}).')
  527. def infer_shape(self, x1, x2):
  528. self.check_shape_size(x1, x2)
  529. cls_name = self.name
  530. # expected dimension of x, y, x:[...,a,b] y:[..., c,d], the dim size should be the same except the last two
  531. for i in range(len(x1) - 2):
  532. if x1[i] != x2[i]:
  533. raise ValueError(f'For \'{cls_name}\' shape in dim[{i}] not the same, '
  534. + f'while x1 is {x1[i]}, x2 is {x2[i]}')
  535. # validate whether last two dims satisfying matrix multiply
  536. x1_last = x1[-2:]
  537. x2_last = x2[-2:]
  538. # x1_col = x1_last[1] if (not transpose_a) else x1_last[0]
  539. x1_col = x1_last[not self.transpose_a]
  540. # x2_row = x2_last[0] if (not transpose_b) else x2_last[1]
  541. x2_row = x2_last[self.transpose_b]
  542. if x1_col != x2_row:
  543. raise ValueError(f'For \'{cls_name}\' evaluator shapes of inputs can not do this operator,'
  544. + f' got {x1_col} and {x2_row}, with x1 shape {x1}(transpose_a={self.transpose_a})'
  545. + f', x2 shape {x2}(transpose_b={self.transpose_b}).')
  546. # set attribute
  547. self.add_prim_attr('transpose_x1', self.transpose_a)
  548. self.add_prim_attr('transpose_x2', self.transpose_b)
  549. ret_dims = x1[: -2] + [x1_last[self.transpose_a], x2_last[not self.transpose_b]]
  550. return ret_dims
  551. def infer_dtype(self, x1, x2):
  552. args = {"x1": x1, "x2": x2}
  553. validator.check_tensor_type_same(args, mstype.float_type + mstype.int_type, self.name)
  554. if x1.element_type() == mstype.int8:
  555. return mstype.tensor_type(mstype.int32)
  556. return x1
  557. class BatchMatMul(MatMul):
  558. """
  559. Computes matrix multiplication between two tensors by batch
  560. `result[..., :, :] = tensor(a[..., :, :]) * tensor(b[..., :, :])`.
  561. The two input tensors must have the same rank and the rank must be not less than `3`.
  562. Args:
  563. transpose_a (bool): If true, the last two dimensions of `a` is transposed before multiplication.
  564. Default: False.
  565. transpose_b (bool): If true, the last two dimensions of `b` is transposed before multiplication.
  566. Default: False.
  567. Inputs:
  568. - **input_x** (Tensor) - The first tensor to be multiplied. The shape of the tensor is :math:`(*B, N, C)`,
  569. where :math:`*B` represents the batch size which can be multidimensional, :math:`N` and :math:`C` are the
  570. size of the last two dimensions. If `transpose_a` is True, its shape must be :math:`(*B, C, N)`.
  571. - **input_y** (Tensor) - The second tensor to be multiplied. The shape of the tensor is :math:`(*B, C, M)`. If
  572. `transpose_b` is True, its shape must be :math:`(*B, M, C)`.
  573. Outputs:
  574. Tensor, the shape of the output tensor is :math:`(*B, N, M)`.
  575. Examples:
  576. >>> input_x = Tensor(np.ones(shape=[2, 4, 1, 3]), mindspore.float32)
  577. >>> input_y = Tensor(np.ones(shape=[2, 4, 3, 4]), mindspore.float32)
  578. >>> batmatmul = P.BatchMatMul()
  579. >>> output = batmatmul(input_x, input_y)
  580. >>>
  581. >>> input_x = Tensor(np.ones(shape=[2, 4, 3, 1]), mindspore.float32)
  582. >>> input_y = Tensor(np.ones(shape=[2, 4, 3, 4]), mindspore.float32)
  583. >>> batmatmul = P.BatchMatMul(transpose_a=True)
  584. >>> output = batmatmul(input_x, input_y)
  585. """
  586. @prim_attr_register
  587. def __init__(self, transpose_a=False, transpose_b=False):
  588. self.init_prim_io_names(inputs=['x1', 'x2'], outputs=['output'])
  589. cls_name = self.name
  590. validator.check_value_type("transpose_a", transpose_a, [bool], cls_name)
  591. validator.check_value_type("transpose_b", transpose_b, [bool], cls_name)
  592. def check_shape_size(self, x, y):
  593. if len(x) != len(y) or len(x) < 3:
  594. raise ValueError('For \'BatchMatMul\' input x, y should be the same dimension size and should be '
  595. 'greater or equal to 3,' + f' while x size = {len(x)}, y size= {len(y)}')
  596. class CumSum(PrimitiveWithInfer):
  597. """
  598. Computes the cumulative sum of input tensor along axis.
  599. Args:
  600. exclusive (bool): If true, perform exclusive mode. Default: False.
  601. reverse (bool): If true, perform inverse cumulative sum. Default: False.
  602. Inputs:
  603. - **input** (Tensor) - The input tensor to accumulate.
  604. - **axis** (int) - The axis to accumulate the tensor's value. Only constant value is allowed.
  605. Must be in the range [-rank(input), rank(input)).
  606. Outputs:
  607. Tensor, the shape of the output tensor is consistent with the input tensor's.
  608. Examples:
  609. >>> input = Tensor(np.array([[3, 4, 6, 10],[1, 6, 7, 9],[4, 3, 8, 7],[1, 3, 7, 9]]).astype(np.float32))
  610. >>> cumsum = P.CumSum()
  611. >>> output = cumsum(input, 1)
  612. [[ 3. 7. 13. 23.]
  613. [ 1. 7. 14. 23.]
  614. [ 4. 7. 15. 22.]
  615. [ 1. 4. 11. 20.]]
  616. """
  617. @prim_attr_register
  618. def __init__(self, exclusive=False, reverse=False):
  619. """Initialize cumsum"""
  620. cls_name = self.name
  621. validator.check_value_type('exclusive', exclusive, [bool], cls_name)
  622. validator.check_value_type('reverse', reverse, [bool], cls_name)
  623. self.init_prim_io_names(inputs=['x', 'axis'], outputs=['y'])
  624. def __infer__(self, x, axis):
  625. cls_name = self.name
  626. x_shp = x['shape']
  627. if axis['value'] is None:
  628. raise ValueError(f"For {self.name}, axis must be const.")
  629. validator.check_value_type('axis', axis['value'], [int], cls_name)
  630. valid_types = [mstype.uint8, mstype.int8, mstype.int32, mstype.float16, mstype.float32]
  631. validator.check_tensor_type_same({'x': x['dtype']}, valid_types, cls_name)
  632. return {'shape': x_shp,
  633. 'dtype': x['dtype'],
  634. 'value': None}
  635. class AddN(PrimitiveWithInfer):
  636. """
  637. Computes addition of all input tensors element-wise.
  638. All input tensors must have the same shape.
  639. Inputs:
  640. - **input_x** (Union(tuple[Tensor], list[Tensor])) - The input tuple or list
  641. is made up of multiple tensors whose dtype is number or bool to be added together.
  642. Outputs:
  643. Tensor, has the same shape and dtype as each entry of the `input_x`.
  644. Examples:
  645. >>> class NetAddN(nn.Cell):
  646. >>> def __init__(self):
  647. >>> super(NetAddN, self).__init__()
  648. >>> self.addN = P.AddN()
  649. >>>
  650. >>> def construct(self, *z):
  651. >>> return self.addN(z)
  652. >>>
  653. >>> net = NetAddN()
  654. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  655. >>> input_y = Tensor(np.array([4, 5, 6]), mindspore.float32)
  656. >>> net(input_x, input_y, input_x, input_y)
  657. [10.0, 14.0, 18.0]
  658. """
  659. @prim_attr_register
  660. def __init__(self):
  661. self.init_prim_io_names(inputs=["inputs"], outputs=["sum"])
  662. def check_elim(self, inputs):
  663. if len(inputs) != 1:
  664. return (False, None)
  665. if isinstance(inputs[0], Tensor):
  666. return (True, inputs[0])
  667. raise TypeError("Expecting Tensor, got : {}".format(type(inputs[0])))
  668. def infer_shape(self, inputs):
  669. cls_name = self.name
  670. validator.check_int(len(inputs), 1, Rel.GE, "inputs", cls_name)
  671. self.add_prim_attr('n', len(inputs))
  672. shp0 = inputs[0]
  673. for i, shp in enumerate(inputs):
  674. validator.check(f"shape of inputs[{i}]", shp, 'shape of inputs[0]', shp0, Rel.EQ, cls_name)
  675. return shp0
  676. def infer_dtype(self, inputs):
  677. cls_name = self.name
  678. validator.check_value_type("inputs", inputs, [tuple, list], cls_name)
  679. validator.check_int(len(inputs), 1, Rel.GE, "inputs", cls_name)
  680. args = {}
  681. contains_undetermined = False
  682. for i, dtype in enumerate(inputs):
  683. args[f"inputs[{i}]"] = dtype
  684. if dtype == mstype.undetermined:
  685. contains_undetermined = True
  686. if not contains_undetermined:
  687. validator.check_tensor_type_same(args, mstype.number_type + (mstype.bool_,), cls_name)
  688. return inputs[0]
  689. def infer_value(self, inputs):
  690. if inputs is None:
  691. return None
  692. for x in inputs:
  693. if x is None:
  694. return None
  695. added = copy.deepcopy(inputs[0].asnumpy())
  696. for x in inputs[1:]:
  697. added += x.asnumpy()
  698. out = np.array(added, inputs[0].asnumpy().dtype)
  699. return Tensor(out)
  700. class AccumulateNV2(PrimitiveWithInfer):
  701. """
  702. Computes accumulation of all input tensors element-wise.
  703. AccumulateNV2 is similar to AddN, but there is a significant difference
  704. among them: AccumulateNV2 will not wait for all of its inputs to be ready
  705. before summing. That is to say, AccumulateNV2 is able to save
  706. memory when inputs are ready at different time since the minimum temporary
  707. storage is proportional to the output size rather than the input size.
  708. Inputs:
  709. - **input_x** (Union(tuple[Tensor], list[Tensor])) - The input tuple or list
  710. is made up of multiple tensors whose dtype is number to be added together.
  711. Outputs:
  712. Tensor, has the same shape and dtype as each entry of the `input_x`.
  713. Examples:
  714. >>> class NetAccumulateNV2(nn.Cell):
  715. >>> def __init__(self):
  716. >>> super(NetAccumulateNV2, self).__init__()
  717. >>> self.accumulateNV2 = P.AccumulateNV2()
  718. >>>
  719. >>> def construct(self, *z):
  720. >>> return self.accumulateNV2(z)
  721. >>>
  722. >>> net = NetAccumulateNV2()
  723. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  724. >>> input_y = Tensor(np.array([4, 5, 6]), mindspore.float32)
  725. >>> net(input_x, input_y, input_x, input_y)
  726. Tensor([10., 14., 18.], shape=(3,), dtype=mindspore.float32)
  727. """
  728. @prim_attr_register
  729. def __init__(self):
  730. self.__setattr_flag__ = True
  731. self.init_prim_io_names(inputs=["inputs"], outputs=["sum"])
  732. def check_elim(self, inputs):
  733. if len(inputs) != 1:
  734. return (False, None)
  735. if isinstance(inputs[0], Tensor):
  736. return (True, inputs[0])
  737. raise TypeError("Expecting Tensor, got : {}".format(type(inputs[0])))
  738. def infer_shape(self, inputs):
  739. cls_name = self.name
  740. validator.check_int(len(inputs), 1, Rel.GE, "inputs", cls_name)
  741. self.add_prim_attr('n', len(inputs))
  742. shp0 = inputs[0]
  743. for i, shp in enumerate(inputs):
  744. validator.check(f"shape of inputs[{i}]", shp, 'shape of inputs[0]', shp0, Rel.EQ, cls_name)
  745. return shp0
  746. def infer_dtype(self, inputs):
  747. cls_name = self.name
  748. validator.check_value_type("inputs", inputs, [tuple, list], cls_name)
  749. validator.check_int(len(inputs), 1, Rel.GE, "inputs", cls_name)
  750. args = {}
  751. for i, dtype in enumerate(inputs):
  752. args[f"inputs[{i}]"] = dtype
  753. validator.check_tensor_type_same(args, mstype.number_type + (mstype.bool_,), cls_name)
  754. return inputs[0]
  755. class Neg(PrimitiveWithInfer):
  756. """
  757. Returns a tensor with negative values of the input tensor element-wise.
  758. Inputs:
  759. - **input_x** (Tensor) - The input tensor whose dtype is number.
  760. Outputs:
  761. Tensor, has the same shape and dtype as input.
  762. Examples:
  763. >>> neg = P.Neg()
  764. >>> input_x = Tensor(np.array([1, 2, -1, 2, 0, -3.5]), mindspore.float32)
  765. >>> result = neg(input_x)
  766. [-1. -2. 1. -2. 0. 3.5]
  767. """
  768. @prim_attr_register
  769. def __init__(self):
  770. """Initialize Neg"""
  771. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  772. def infer_shape(self, input_x):
  773. return input_x
  774. def infer_dtype(self, input_x):
  775. validator.check_tensor_type_same({"input_x": input_x}, mstype.number_type, self.name)
  776. return input_x
  777. def infer_value(self, input_x):
  778. if input_x is not None:
  779. input_x = input_x.asnumpy()
  780. out = np.array(-input_x, input_x.dtype)
  781. return Tensor(out)
  782. return None
  783. class InplaceAdd(PrimitiveWithInfer):
  784. """
  785. Adds v into specified rows of x. Computes y = x; y[i,] += v.
  786. Args:
  787. indices (Union[int, tuple]): Indices into the left-most dimension of x, and determines which rows of x
  788. to add with v. It is an integer or a tuple, whose value is in [0, the first dimension size of x).
  789. Inputs:
  790. - **input_x** (Tensor) - The first input is a tensor whose data type is float16, float32 or int32.
  791. - **input_v** (Tensor) - The second input is a tensor that has the same dimension sizes as x except
  792. the first dimension, which must be the same as indices's size. It has the same data type with `input_x`.
  793. Outputs:
  794. Tensor, has the same shape and dtype as input_x.
  795. Examples:
  796. >>> indices = (0, 1)
  797. >>> input_x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32)
  798. >>> input_v = Tensor(np.array([[0.5, 1.0], [1.0, 1.5]]), mindspore.float32)
  799. >>> inplaceAdd = P.InplaceAdd(indices)
  800. >>> inplaceAdd(input_x, input_v)
  801. [[1.5 3.]
  802. [4. 5.5]
  803. [5. 6.]]
  804. """
  805. @prim_attr_register
  806. def __init__(self, indices):
  807. """Initialize InplaceAdd"""
  808. self.init_prim_io_names(inputs=['x', 'v'], outputs=['y'])
  809. self.indices = indices
  810. validator.check_value_type('indices', indices, [tuple, int], self.name)
  811. if isinstance(indices, int):
  812. self.indices = (indices,)
  813. for item in self.indices:
  814. validator.check_value_type("item of indices", item, [int], self.name)
  815. def infer_dtype(self, x_dtype, v_dtype):
  816. args = {'x': x_dtype, 'v': v_dtype}
  817. valid_type = [mstype.int32, mstype.float16, mstype.float32]
  818. validator.check_tensor_type_same(args, valid_type, self.name)
  819. return x_dtype
  820. def infer_shape(self, x_shape, v_shape):
  821. validator.check("x", len(x_shape), "v", len(v_shape), Rel.EQ, self.name)
  822. validator.check("size of indices", len(self.indices), "v's first dimension", v_shape[0],
  823. Rel.EQ, self.name)
  824. for i in self.indices:
  825. if i < 0 or i >= x_shape[0]:
  826. raise ValueError(f'The value of indices must be in [0, {x_shape[0]}), but got {i}.')
  827. x_rank = len(x_shape)
  828. for idx in range(x_rank)[1:]:
  829. validator.check('v dim %d' % idx, v_shape[idx], "x dim %d" % idx, x_shape[idx], Rel.EQ, self.name)
  830. return x_shape
  831. class InplaceSub(PrimitiveWithInfer):
  832. """
  833. Subtracts v into specified rows of x. Computes y = x; y[i, :] -= v.
  834. Args:
  835. indices (Union[int, tuple]): Indices into the left-most dimension of x, and determines which rows of x
  836. to subtract with v. It is a int or tuple, whose value is in [0, the first dimension size of x).
  837. Inputs:
  838. - **input_x** (Tensor) - The first input is a tensor whose data type is float16, float32 or int32.
  839. - **input_v** (Tensor) - The second input is a tensor who has the same dimension sizes as x except
  840. the first dimension, which must be the same as indices's size. It has the same data type with `input_x`.
  841. Outputs:
  842. Tensor, has the same shape and dtype as input_x.
  843. Examples:
  844. >>> indices = (0, 1)
  845. >>> input_x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32)
  846. >>> input_v = Tensor(np.array([[0.5, 1.0], [1.0, 1.5]]), mindspore.float32)
  847. >>> inplaceSub = P.InplaceSub(indices)
  848. >>> inplaceSub(input_x, input_v)
  849. [[0.5 1.]
  850. [2. 2.5]
  851. [5. 6.]]
  852. """
  853. @prim_attr_register
  854. def __init__(self, indices):
  855. """Initialize InplaceSub"""
  856. self.init_prim_io_names(inputs=['x', 'v'], outputs=['y'])
  857. self.indices = indices
  858. validator.check_value_type('indices', indices, [tuple, int], self.name)
  859. if isinstance(indices, int):
  860. self.indices = (indices,)
  861. for item in self.indices:
  862. validator.check_value_type("item of indices", item, [int], self.name)
  863. def infer_dtype(self, x_dtype, v_dtype):
  864. args = {'x': x_dtype, 'v': v_dtype}
  865. valid_type = [mstype.int32, mstype.float16, mstype.float32]
  866. validator.check_tensor_type_same(args, valid_type, self.name)
  867. return x_dtype
  868. def infer_shape(self, x_shape, v_shape):
  869. validator.check("x", len(x_shape), "v", len(v_shape), Rel.EQ, self.name)
  870. validator.check("size of indices", len(self.indices), "v's first dimension", v_shape[0],
  871. Rel.EQ, self.name)
  872. for i in self.indices:
  873. if i < 0 or i >= x_shape[0]:
  874. raise ValueError(f'The value of indices must be in [0, {x_shape[0]}), but got {i}.')
  875. x_rank = len(x_shape)
  876. for idx in range(x_rank)[1:]:
  877. validator.check('v dim %d' % idx, v_shape[idx], "x dim %d" % idx, x_shape[idx], Rel.EQ, self.name)
  878. return x_shape
  879. class Sub(_MathBinaryOp):
  880. """
  881. Subtracts the second input tensor from the first input tensor element-wise.
  882. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  883. The inputs must be two tensors or one tensor and one scalar.
  884. When the inputs are two tensors,
  885. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  886. When the inputs are one tensor and one scalar,
  887. the scalar could only be a constant.
  888. Inputs:
  889. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  890. or a tensor whose data type is number or bool.
  891. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number, or a bool when the first input
  892. is a tensor, or a tensor whose data type is number or bool.
  893. Outputs:
  894. Tensor, the shape is the same as the one after broadcasting,
  895. and the data type is the one with higher precision or higher digits among the two inputs.
  896. Examples:
  897. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  898. >>> input_y = Tensor(np.array([4, 5, 6]), mindspore.int32)
  899. >>> sub = P.Sub()
  900. >>> sub(input_x, input_y)
  901. [-3, -3, -3]
  902. """
  903. def infer_value(self, x, y):
  904. if x is not None and y is not None:
  905. x = x.asnumpy()
  906. y = y.asnumpy()
  907. out = x - y
  908. out = np.array(out, x.dtype)
  909. return Tensor(out)
  910. return None
  911. class Mul(_MathBinaryOp):
  912. """
  913. Multiplies two tensors element-wise.
  914. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  915. The inputs must be two tensors or one tensor and one scalar.
  916. When the inputs are two tensors,
  917. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  918. When the inputs are one tensor and one scalar,
  919. the scalar could only be a constant.
  920. Inputs:
  921. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  922. a bool or a tensor whose data type is number or bool.
  923. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  924. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  925. Outputs:
  926. Tensor, the shape is the same as the one after broadcasting,
  927. and the data type is the one with higher precision or higher digits among the two inputs.
  928. Examples:
  929. >>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  930. >>> input_y = Tensor(np.array([4.0, 5.0, 6.0]), mindspore.float32)
  931. >>> mul = P.Mul()
  932. >>> mul(input_x, input_y)
  933. [4, 10, 18]
  934. """
  935. def infer_value(self, x, y):
  936. if x is not None and y is not None:
  937. x = x.asnumpy()
  938. y = y.asnumpy()
  939. out = x * y
  940. out = np.array(out, x.dtype)
  941. return Tensor(out)
  942. return None
  943. class SquaredDifference(_MathBinaryOp):
  944. """
  945. Subtracts the second input tensor from the first input tensor element-wise and returns square of it.
  946. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  947. The inputs must be two tensors or one tensor and one scalar.
  948. When the inputs are two tensors,
  949. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  950. When the inputs are one tensor and one scalar,
  951. the scalar could only be a constant.
  952. Inputs:
  953. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  954. or a tensor whose data type is float16, float32, int32 or bool.
  955. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number, or a bool when the first input
  956. is a tensor or a tensor whose data type isfloat16, float32, int32 or bool.
  957. Outputs:
  958. Tensor, the shape is the same as the one after broadcasting,
  959. and the data type is the one with higher precision or higher digits among the two inputs.
  960. Examples:
  961. >>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  962. >>> input_y = Tensor(np.array([2.0, 4.0, 6.0]), mindspore.float32)
  963. >>> squared_difference = P.SquaredDifference()
  964. >>> squared_difference(input_x, input_y)
  965. [1.0, 4.0, 9.0]
  966. """
  967. def infer_dtype(self, x_dtype, y_dtype):
  968. valid_type = [mstype.float16, mstype.float32, mstype.int32]
  969. return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, valid_type, self.name)
  970. class Square(PrimitiveWithInfer):
  971. """
  972. Returns square of a tensor element-wise.
  973. Inputs:
  974. - **input_x** (Tensor) - The input tensor whose dtype is number.
  975. Outputs:
  976. Tensor, has the same shape and dtype as the `input_x`.
  977. Examples:
  978. >>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  979. >>> square = P.Square()
  980. >>> square(input_x)
  981. [1.0, 4.0, 9.0]
  982. """
  983. @prim_attr_register
  984. def __init__(self):
  985. """Initialize Square"""
  986. self.init_prim_io_names(inputs=['input_x'], outputs=['output'])
  987. def infer_shape(self, x_shape):
  988. return x_shape
  989. def infer_dtype(self, x_type):
  990. validator.check_tensor_type_same({"x": x_type}, mstype.number_type, self.name)
  991. return x_type
  992. def infer_value(self, x):
  993. if x is not None:
  994. x = x.asnumpy()
  995. out = x * x
  996. out = np.array(out, x.dtype)
  997. return Tensor(out)
  998. return None
  999. class Rsqrt(PrimitiveWithInfer):
  1000. """
  1001. Computes reciprocal of square root of input tensor element-wise.
  1002. Inputs:
  1003. - **input_x** (Tensor) - The input of Rsqrt. Each element must be a non-negative number.
  1004. Outputs:
  1005. Tensor, has the same type and shape as `input_x`.
  1006. Examples:
  1007. >>> input_tensor = Tensor([[4, 4], [9, 9]], mindspore.float32)
  1008. >>> rsqrt = P.Rsqrt()
  1009. >>> rsqrt(input_tensor)
  1010. [[0.5, 0.5], [0.333333, 0.333333]]
  1011. """
  1012. @prim_attr_register
  1013. def __init__(self):
  1014. """Initialize Rsqrt"""
  1015. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  1016. def infer_shape(self, x_shape):
  1017. return x_shape
  1018. def infer_dtype(self, x_type):
  1019. validator.check_tensor_type_same({"x": x_type}, mstype.number_type, self.name)
  1020. return x_type
  1021. def infer_value(self, x):
  1022. if x is not None:
  1023. x = x.asnumpy()
  1024. out = 1.0 / np.sqrt(x)
  1025. out = np.array(out, x.dtype)
  1026. return Tensor(out)
  1027. return None
  1028. class Sqrt(PrimitiveWithCheck):
  1029. """
  1030. Returns square root of a tensor element-wise.
  1031. Inputs:
  1032. - **input_x** (Tensor) - The input tensor whose dtype is number.
  1033. Outputs:
  1034. Tensor, has the same shape as the `input_x`.
  1035. Examples:
  1036. >>> input_x = Tensor(np.array([1.0, 4.0, 9.0]), mindspore.float32)
  1037. >>> sqrt = P.Sqrt()
  1038. >>> sqrt(input_x)
  1039. [1.0, 2.0, 3.0]
  1040. """
  1041. @prim_attr_register
  1042. def __init__(self):
  1043. """Initialize Sqrt"""
  1044. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  1045. def check_dtype(self, x_type):
  1046. validator.check_tensor_type_same({"x": x_type}, mstype.number_type, self.name)
  1047. def infer_value(self, x):
  1048. if x is not None:
  1049. x = x.asnumpy()
  1050. out = np.sqrt(x)
  1051. out = np.array(out, x.dtype)
  1052. return Tensor(out)
  1053. return None
  1054. class Reciprocal(PrimitiveWithInfer):
  1055. """
  1056. Returns reciprocal of a tensor element-wise.
  1057. Inputs:
  1058. - **input_x** (Tensor) - The input tensor.
  1059. Outputs:
  1060. Tensor, has the same shape as the `input_x`.
  1061. Examples:
  1062. >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1063. >>> reciprocal = P.Reciprocal()
  1064. >>> reciprocal(input_x)
  1065. [1.0, 0.5, 0.25]
  1066. """
  1067. @prim_attr_register
  1068. def __init__(self):
  1069. """Initialize Reciprocal"""
  1070. if context.get_context("device_target") == "GPU":
  1071. self.target = "GPU"
  1072. else:
  1073. self.target = "OTHER"
  1074. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1075. def infer_shape(self, x):
  1076. return x
  1077. def infer_dtype(self, x):
  1078. validator.check_subclass("x", x, mstype.tensor, self.name)
  1079. return x
  1080. def infer_value(self, x):
  1081. if x is not None:
  1082. x = x.asnumpy()
  1083. out = 1.0 / x
  1084. out = np.array(out, x.dtype)
  1085. return Tensor(out)
  1086. return None
  1087. class Pow(_MathBinaryOp):
  1088. """
  1089. Computes a tensor to the power of the second input.
  1090. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1091. The inputs must be two tensors or one tensor and one scalar.
  1092. When the inputs are two tensors,
  1093. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1094. When the inputs are one tensor and one scalar,
  1095. the scalar could only be a constant.
  1096. Inputs:
  1097. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1098. a bool or a tensor whose data type is number or bool.
  1099. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1100. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1101. Outputs:
  1102. Tensor, the shape is the same as the one after broadcasting,
  1103. and the data type is the one with higher precision or higher digits among the two inputs.
  1104. Examples:
  1105. >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1106. >>> input_y = 3.0
  1107. >>> pow = P.Pow()
  1108. >>> pow(input_x, input_y)
  1109. [1.0, 8.0, 64.0]
  1110. >>>
  1111. >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1112. >>> input_y = Tensor(np.array([2.0, 4.0, 3.0]), mindspore.float32)
  1113. >>> pow = P.Pow()
  1114. >>> pow(input_x, input_y)
  1115. [1.0, 16.0, 64.0]
  1116. """
  1117. def infer_value(self, x, power):
  1118. if x is not None and power is not None:
  1119. x = x.asnumpy()
  1120. power = power.asnumpy()
  1121. out = np.power(x, power)
  1122. out = np.array(out, x.dtype)
  1123. return Tensor(out)
  1124. return None
  1125. class Exp(PrimitiveWithInfer):
  1126. """
  1127. Returns exponential of a tensor element-wise.
  1128. Inputs:
  1129. - **input_x** (Tensor) - The input tensor. The data type mast be float16 or float32.
  1130. Outputs:
  1131. Tensor, has the same shape and dtype as the `input_x`.
  1132. Examples:
  1133. >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1134. >>> exp = P.Exp()
  1135. >>> exp(input_x)
  1136. [ 2.71828183, 7.3890561 , 54.59815003]
  1137. """
  1138. @prim_attr_register
  1139. def __init__(self):
  1140. """Initialize Exp"""
  1141. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1142. def infer_shape(self, x_shape):
  1143. return x_shape
  1144. def infer_dtype(self, x_type):
  1145. validator.check_subclass("x", x_type, mstype.tensor, self.name)
  1146. return x_type
  1147. def infer_value(self, x):
  1148. if x is not None:
  1149. x = x.asnumpy()
  1150. out = np.exp(x)
  1151. out = np.array(out, x.dtype)
  1152. return Tensor(out)
  1153. return None
  1154. class Expm1(PrimitiveWithInfer):
  1155. """
  1156. Returns exponential then minus 1 of a tensor element-wise.
  1157. Inputs:
  1158. - **input_x** (Tensor) - The input tensor. With float16 or float32 data type.
  1159. Outputs:
  1160. Tensor, has the same shape as the `input_x`.
  1161. Examples:
  1162. >>> input_x = Tensor(np.array([0.0, 1.0, 2.0, 4.0]), mindspore.float32)
  1163. >>> expm1 = P.Expm1()
  1164. >>> expm1(input_x)
  1165. [ 0., 1.71828183, 6.3890561 , 53.59815003]
  1166. """
  1167. @prim_attr_register
  1168. def __init__(self):
  1169. """Initialize Exp"""
  1170. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1171. def infer_shape(self, x_shape):
  1172. return x_shape
  1173. def infer_dtype(self, x_type):
  1174. validator.check_subclass("x", x_type, mstype.tensor, self.name)
  1175. validator.check_tensor_type_same({"x": x_type}, [mstype.float16, mstype.float32], self.name)
  1176. return x_type
  1177. class HistogramFixedWidth(PrimitiveWithInfer):
  1178. """
  1179. Returns a rank 1 histogram counting the number of entries in values that fall into every bin. The bins are equal
  1180. width and determined by the arguments range and nbins.
  1181. Args:
  1182. dtype (str): An optional attribute. Must be one of the following types: "int32", "int64". Default: "int32".
  1183. nbins (int): The number of histogram bins, the type is a positive integer.
  1184. Inputs:
  1185. - **x** (Tensor) - Numeric Tensor. Must be one of the following types: int32, float32, float16.
  1186. - **range** (Tensor) - Must has the same data type as `x`, and the shape is [2].
  1187. x <= range[0] will be mapped to hist[0], x >= range[1] will be mapped to hist[-1].
  1188. Outputs:
  1189. Tensor, the type is int32.
  1190. Examples:
  1191. >>> x = Tensor([-1.0, 0.0, 1.5, 2.0, 5.0, 15], mindspore.float16)
  1192. >>> range = Tensor([0.0, 5.0], mindspore.float16)
  1193. >>> hist = P.HistogramFixedWidth(5)
  1194. >>> hist(x, range)
  1195. [2 1 1 0 2]
  1196. """
  1197. @prim_attr_register
  1198. def __init__(self, nbins, dtype='int32'):
  1199. self.nbins = validator.check_value_type("nbins", nbins, [int], self.name)
  1200. validator.check_int(nbins, 1, Rel.GE, "nbins", self.name)
  1201. valid_values = ['int32', 'int64']
  1202. self.dtype = validator.check_string(dtype, valid_values, "dtype", self.name)
  1203. self.init_prim_io_names(inputs=['x', 'range'], outputs=['y'])
  1204. def infer_shape(self, x_shape, range_shape):
  1205. return (self.nbins,)
  1206. def infer_dtype(self, x_dtype, range_dtype):
  1207. validator.check_subclass("x", x_dtype, mstype.tensor, self.name)
  1208. valid_types = (mstype.float16, mstype.float32, mstype.int32)
  1209. validator.check_tensor_type_same({"x": x_dtype}, valid_types, self.name)
  1210. validator.check_tensor_type_same({"range": range_dtype}, valid_types, self.name)
  1211. y_dtype = mstype.int32
  1212. return y_dtype
  1213. class Log(PrimitiveWithInfer):
  1214. """
  1215. Returns the natural logarithm of a tensor element-wise.
  1216. Inputs:
  1217. - **input_x** (Tensor) - The input tensor. With float16 or float32 data type. The value must be greater than 0.
  1218. Outputs:
  1219. Tensor, has the same shape as the `input_x`.
  1220. Examples:
  1221. >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1222. >>> log = P.Log()
  1223. >>> log(input_x)
  1224. [0.0, 0.69314718, 1.38629436]
  1225. """
  1226. @prim_attr_register
  1227. def __init__(self):
  1228. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1229. def infer_shape(self, x):
  1230. return x
  1231. def infer_dtype(self, x):
  1232. validator.check_subclass("x", x, mstype.tensor, self.name)
  1233. return x
  1234. def infer_value(self, x):
  1235. if x is not None:
  1236. x = x.asnumpy()
  1237. out = np.log(x)
  1238. out = np.array(out, x.dtype)
  1239. return Tensor(out)
  1240. return None
  1241. class Log1p(PrimitiveWithInfer):
  1242. """
  1243. Returns the natural logarithm of one plus the input tensor element-wise.
  1244. Inputs:
  1245. - **input_x** (Tensor) - The input tensor. With float16 or float32 data type. The value must be greater than -1.
  1246. Outputs:
  1247. Tensor, has the same shape as the `input_x`.
  1248. Examples:
  1249. >>> input_x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1250. >>> log1p = P.Log1p()
  1251. >>> log1p(input_x)
  1252. [0.6931472, 1.0986123, 1.609438]
  1253. """
  1254. @prim_attr_register
  1255. def __init__(self):
  1256. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1257. def infer_shape(self, x):
  1258. return x
  1259. def infer_dtype(self, x):
  1260. validator.check_subclass("x", x, mstype.tensor, self.name)
  1261. validator.check_tensor_type_same({"x": x}, [mstype.float16, mstype.float32], self.name)
  1262. return x
  1263. class Erf(PrimitiveWithInfer):
  1264. r"""
  1265. Computes the Gauss error function of `input_x` element-wise.
  1266. Inputs:
  1267. - **input_x** (Tensor) - The input tensor. The data type must be float16 or float32.
  1268. Outputs:
  1269. Tensor, has the same shape and dtype as the `input_x`.
  1270. Examples:
  1271. >>> input_x = Tensor(np.array([-1, 0, 1, 2, 3]), mindspore.float32)
  1272. >>> erf = P.Erf()
  1273. >>> erf(input_x)
  1274. [-0.8427168, 0., 0.8427168, 0.99530876, 0.99997765]
  1275. """
  1276. @prim_attr_register
  1277. def __init__(self):
  1278. """Initialize Erf"""
  1279. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1280. def infer_shape(self, x_shape):
  1281. return x_shape
  1282. def infer_dtype(self, x_type):
  1283. validator.check_tensor_type_same({"x": x_type}, [mstype.float16, mstype.float32], self.name)
  1284. return x_type
  1285. class Erfc(PrimitiveWithInfer):
  1286. r"""
  1287. Computes the complementary error function of `input_x` element-wise.
  1288. Inputs:
  1289. - **input_x** (Tensor) - The input tensor. The data type must be float16 or float32.
  1290. Outputs:
  1291. Tensor, has the same shape and dtype as the `input_x`.
  1292. Examples:
  1293. >>> input_x = Tensor(np.array([-1, 0, 1, 2, 3]), mindspore.float32)
  1294. >>> erfc = P.Erfc()
  1295. >>> erfc(input_x)
  1296. [1.8427168, 0., 0.1572832, 0.00469124, 0.00002235]
  1297. """
  1298. @prim_attr_register
  1299. def __init__(self):
  1300. """Initialize Erfc"""
  1301. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1302. def infer_shape(self, x_shape):
  1303. return x_shape
  1304. def infer_dtype(self, x_type):
  1305. validator.check_tensor_type_same({"x": x_type}, [mstype.float16, mstype.float32], self.name)
  1306. return x_type
  1307. class Minimum(_MathBinaryOp):
  1308. """
  1309. Computes the minimum of input tensors element-wise.
  1310. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1311. The inputs must be two tensors or one tensor and one scalar.
  1312. When the inputs are two tensors,
  1313. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1314. When the inputs are one tensor and one scalar,
  1315. the scalar could only be a constant.
  1316. Inputs:
  1317. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1318. a bool or a tensor whose data type is number or bool.
  1319. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1320. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1321. Outputs:
  1322. Tensor, the shape is the same as the one after broadcasting,
  1323. and the data type is the one with higher precision or higher digits among the two inputs.
  1324. Examples:
  1325. >>> input_x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.float32)
  1326. >>> input_y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
  1327. >>> minimum = P.Minimum()
  1328. >>> minimum(input_x, input_y)
  1329. [1.0, 2.0, 3.0]
  1330. """
  1331. def infer_value(self, x, y):
  1332. if x is not None and y is not None:
  1333. x = x.asnumpy()
  1334. y = y.asnumpy()
  1335. out = np.minimum(x, y)
  1336. out = np.array(out, x.dtype)
  1337. return Tensor(out)
  1338. return None
  1339. class Maximum(_MathBinaryOp):
  1340. """
  1341. Computes the maximum of input tensors element-wise.
  1342. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1343. The inputs must be two tensors or one tensor and one scalar.
  1344. When the inputs are two tensors,
  1345. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1346. When the inputs are one tensor and one scalar,
  1347. the scalar could only be a constant.
  1348. Inputs:
  1349. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1350. a bool or a tensor whose data type is number or bool.
  1351. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1352. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1353. Outputs:
  1354. Tensor, the shape is the same as the one after broadcasting,
  1355. and the data type is the one with higher precision or higher digits among the two inputs.
  1356. Examples:
  1357. >>> input_x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.float32)
  1358. >>> input_y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
  1359. >>> maximum = P.Maximum()
  1360. >>> maximum(input_x, input_y)
  1361. [4.0, 5.0, 6.0]
  1362. """
  1363. def infer_value(self, x, y):
  1364. if x is not None and y is not None:
  1365. x = x.asnumpy()
  1366. y = y.asnumpy()
  1367. out = np.maximum(x, y)
  1368. out = np.array(out, x.dtype)
  1369. return Tensor(out)
  1370. return None
  1371. class RealDiv(_MathBinaryOp):
  1372. """
  1373. Divide the first input tensor by the second input tensor in floating-point type element-wise.
  1374. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1375. The inputs must be two tensors or one tensor and one scalar.
  1376. When the inputs are two tensors,
  1377. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1378. When the inputs are one tensor and one scalar,
  1379. the scalar could only be a constant.
  1380. Inputs:
  1381. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1382. a bool or a tensor whose data type is number or bool.
  1383. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1384. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1385. Outputs:
  1386. Tensor, the shape is the same as the one after broadcasting,
  1387. and the data type is the one with higher precision or higher digits among the two inputs.
  1388. Examples:
  1389. >>> input_x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  1390. >>> input_y = Tensor(np.array([4.0, 5.0, 6.0]), mindspore.float32)
  1391. >>> realdiv = P.RealDiv()
  1392. >>> realdiv(input_x, input_y)
  1393. [0.25, 0.4, 0.5]
  1394. """
  1395. def infer_value(self, x, y):
  1396. if x is not None and y is not None:
  1397. x = x.asnumpy()
  1398. y = y.asnumpy()
  1399. out = x / y
  1400. out = np.array(out, x.dtype)
  1401. return Tensor(out)
  1402. return None
  1403. class Div(_MathBinaryOp):
  1404. """
  1405. Computes the quotient of dividing the first input tensor by the second input tensor element-wise.
  1406. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1407. The inputs must be two tensors or one tensor and one scalar.
  1408. When the inputs are two tensors,
  1409. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1410. When the inputs are one tensor and one scalar,
  1411. the scalar could only be a constant.
  1412. Inputs:
  1413. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1414. a bool or a tensor whose data type is number or bool.
  1415. - **input_y** (Union[Tensor, Number, bool]) - When the first input is a tensor, The second input
  1416. could be a number, a bool, or a tensor whose data type is number or bool. When the first input
  1417. is a number or a bool, the second input must be a tensor whose data type is number or bool.
  1418. Outputs:
  1419. Tensor, the shape is the same as the one after broadcasting,
  1420. and the data type is the one with higher precision or higher digits among the two inputs.
  1421. Examples:
  1422. >>> input_x = Tensor(np.array([-4.0, 5.0, 6.0]), mindspore.float32)
  1423. >>> input_y = Tensor(np.array([3.0, 2.0, 3.0]), mindspore.float32)
  1424. >>> div = P.Div()
  1425. >>> div(input_x, input_y)
  1426. [-1.3, 2.5, 2.0]
  1427. """
  1428. def infer_value(self, x, y):
  1429. if x is not None and y is not None:
  1430. x = x.asnumpy()
  1431. y = y.asnumpy()
  1432. out = np.array(x / y, x.dtype)
  1433. return Tensor(out)
  1434. return None
  1435. class DivNoNan(_MathBinaryOp):
  1436. """
  1437. Computes a safe divide which returns 0 if the y is zero.
  1438. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1439. The inputs must be two tensors or one tensor and one scalar.
  1440. When the inputs are two tensors,
  1441. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1442. When the inputs are one tensor and one scalar,
  1443. the scalar could only be a constant.
  1444. Inputs:
  1445. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1446. a bool or a tensor whose data type is number or bool.
  1447. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1448. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1449. Outputs:
  1450. Tensor, the shape is the same as the one after broadcasting,
  1451. and the data type is the one with higher precision or higher digits among the two inputs.
  1452. Examples:
  1453. >>> input_x = Tensor(np.array([-1.0, 0., 1.0, 5.0, 6.0]), mindspore.float32)
  1454. >>> input_y = Tensor(np.array([0., 0., 0., 2.0, 3.0]), mindspore.float32)
  1455. >>> div_no_nan = P.DivNoNan()
  1456. >>> div_no_nan(input_x, input_y)
  1457. [0., 0., 0., 2.5, 2.0]
  1458. """
  1459. def infer_value(self, x, y):
  1460. if x is not None and y is not None:
  1461. x = x.asnumpy()
  1462. y = y.asnumpy()
  1463. with np.errstate(divide='ignore', invalid='ignore'):
  1464. out = np.true_divide(x, y)
  1465. out[~np.isfinite(out)] = 0
  1466. return out
  1467. return None
  1468. class FloorDiv(_MathBinaryOp):
  1469. """
  1470. Divide the first input tensor by the second input tensor element-wise and round down to the closest integer.
  1471. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1472. The inputs must be two tensors or one tensor and one scalar.
  1473. When the inputs are two tensors,
  1474. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1475. When the inputs are one tensor and one scalar,
  1476. the scalar could only be a constant.
  1477. Inputs:
  1478. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1479. a bool or a tensor whose data type is number or bool.
  1480. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1481. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1482. Outputs:
  1483. Tensor, the shape is the same as the one after broadcasting,
  1484. and the data type is the one with higher precision or higher digits among the two inputs.
  1485. Examples:
  1486. >>> input_x = Tensor(np.array([2, 4, -1]), mindspore.int32)
  1487. >>> input_y = Tensor(np.array([3, 3, 3]), mindspore.int32)
  1488. >>> floor_div = P.FloorDiv()
  1489. >>> floor_div(input_x, input_y)
  1490. [0, 1, -1]
  1491. """
  1492. class TruncateDiv(_MathBinaryOp):
  1493. """
  1494. Divide the first input tensor by the second input tensor element-wise for integer types, negative numbers will
  1495. round fractional quantities towards zero.
  1496. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1497. The inputs must be two tensors or one tensor and one scalar.
  1498. When the inputs are two tensors,
  1499. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1500. When the inputs are one tensor and one scalar,
  1501. the scalar could only be a constant.
  1502. Inputs:
  1503. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  1504. or a tensor whose data type is number or bool.
  1505. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number, or a bool when the first input
  1506. is a tensor, or a tensor whose data type is number or bool.
  1507. Outputs:
  1508. Tensor, the shape is the same as the one after broadcasting,
  1509. and the data type is the one with higher precision or higher digits among the two inputs.
  1510. Examples:
  1511. >>> input_x = Tensor(np.array([2, 4, -1]), mindspore.int32)
  1512. >>> input_y = Tensor(np.array([3, 3, 3]), mindspore.int32)
  1513. >>> truncate_div = P.TruncateDiv()
  1514. >>> truncate_div(input_x, input_y)
  1515. [0, 1, 0]
  1516. """
  1517. class TruncateMod(_MathBinaryOp):
  1518. """
  1519. Returns element-wise remainder of division.
  1520. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1521. The inputs must be two tensors or one tensor and one scalar.
  1522. When the inputs are two tensors,
  1523. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1524. When the inputs are one tensor and one scalar,
  1525. the scalar could only be a constant.
  1526. Inputs:
  1527. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  1528. or a tensor whose data type is number or bool.
  1529. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number, or a bool when the first input
  1530. is a tensor, or a tensor whose data type is number or bool.
  1531. Outputs:
  1532. Tensor, the shape is the same as the one after broadcasting,
  1533. and the data type is the one with higher precision or higher digits among the two inputs.
  1534. Examples:
  1535. >>> input_x = Tensor(np.array([2, 4, -1]), mindspore.int32)
  1536. >>> input_y = Tensor(np.array([3, 3, 3]), mindspore.int32)
  1537. >>> truncate_mod = P.TruncateMod()
  1538. >>> truncate_mod(input_x, input_y)
  1539. [2, 1, -1]
  1540. """
  1541. class Mod(_MathBinaryOp):
  1542. """
  1543. Computes the remainder of dividing the first input tensor by the second input tensor element-wise.
  1544. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1545. The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors,
  1546. both dtypes cannot be bool, and the shapes of them could be broadcast. When the inputs are one tensor
  1547. and one scalar, the scalar could only be a constant.
  1548. Inputs:
  1549. - **input_x** (Union[Tensor, Number]) - The first input is a number or a tensor whose data type is number.
  1550. - **input_y** (Union[Tensor, Number]) - When the first input is a tensor, The second input
  1551. could be a number or a tensor whose data type is number. When the first input is a number,
  1552. the second input must be a tensor whose data type is number.
  1553. Outputs:
  1554. Tensor, the shape is the same as the one after broadcasting,
  1555. and the data type is the one with higher precision or higher digits among the two inputs.
  1556. Raises:
  1557. ValueError: When `input_x` and `input_y` are not the same dtype.
  1558. Examples:
  1559. >>> input_x = Tensor(np.array([-4.0, 5.0, 6.0]), mindspore.float32)
  1560. >>> input_y = Tensor(np.array([3.0, 2.0, 3.0]), mindspore.float32)
  1561. >>> mod = P.Mod()
  1562. >>> mod(input_x, input_y)
  1563. [-1. 1. 0.]
  1564. """
  1565. def infer_value(self, x, y):
  1566. if x is not None and y is not None:
  1567. x = x.asnumpy()
  1568. y = y.asnumpy()
  1569. return Tensor(np.fmod(x, y))
  1570. return None
  1571. class Floor(PrimitiveWithInfer):
  1572. """
  1573. Round a tensor down to the closest integer element-wise.
  1574. Inputs:
  1575. - **input_x** (Tensor) - The input tensor. Its element data type must be float.
  1576. Outputs:
  1577. Tensor, has the same shape as `input_x`.
  1578. Examples:
  1579. >>> input_x = Tensor(np.array([1.1, 2.5, -1.5]), mindspore.float32)
  1580. >>> floor = P.Floor()
  1581. >>> floor(input_x)
  1582. [1.0, 2.0, -2.0]
  1583. """
  1584. @prim_attr_register
  1585. def __init__(self):
  1586. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1587. def infer_shape(self, x_shape):
  1588. return x_shape
  1589. def infer_dtype(self, x_dtype):
  1590. validator.check_tensor_type_same({"x": x_dtype}, mstype.float_type, self.name)
  1591. return x_dtype
  1592. class FloorMod(_MathBinaryOp):
  1593. """
  1594. Compute the remainder of division element-wise.
  1595. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1596. The inputs must be two tensors or one tensor and one scalar.
  1597. When the inputs are two tensors,
  1598. dtypes of them cannot be both bool , and the shapes of them could be broadcast.
  1599. When the inputs are one tensor and one scalar,
  1600. the scalar could only be a constant.
  1601. Inputs:
  1602. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1603. a bool or a tensor whose data type is number or bool.
  1604. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1605. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1606. Outputs:
  1607. Tensor, the shape is the same as the one after broadcasting,
  1608. and the data type is the one with higher precision or higher digits among the two inputs.
  1609. Examples:
  1610. >>> input_x = Tensor(np.array([2, 4, -1]), mindspore.int32)
  1611. >>> input_y = Tensor(np.array([3, 3, 3]), mindspore.int32)
  1612. >>> floor_mod = P.FloorMod()
  1613. >>> floor_mod(input_x, input_y)
  1614. [2, 1, 2]
  1615. """
  1616. class Ceil(PrimitiveWithInfer):
  1617. """
  1618. Round a tensor up to the closest integer element-wise.
  1619. Inputs:
  1620. - **input_x** (Tensor) - The input tensor. It's element data type must be float16 or float32.
  1621. Outputs:
  1622. Tensor, has the same shape as `input_x`.
  1623. Examples:
  1624. >>> input_x = Tensor(np.array([1.1, 2.5, -1.5]), mindspore.float32)
  1625. >>> ceil_op = P.Ceil()
  1626. >>> ceil_op(input_x)
  1627. [2.0, 3.0, -1.0]
  1628. """
  1629. @prim_attr_register
  1630. def __init__(self):
  1631. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1632. def infer_shape(self, x_shape):
  1633. return x_shape
  1634. def infer_dtype(self, x_dtype):
  1635. validator.check_tensor_type_same({"x": x_dtype}, [mstype.float16, mstype.float32], self.name)
  1636. return x_dtype
  1637. class Xdivy(_MathBinaryOp):
  1638. """
  1639. Divide the first input tensor by the second input tensor element-wise. Returns zero when `x` is zero.
  1640. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1641. The inputs must be two tensors or one tensor and one scalar.
  1642. When the inputs are two tensors,
  1643. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1644. When the inputs are one tensor and one scalar,
  1645. the scalar could only be a constant.
  1646. Inputs:
  1647. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  1648. or a tensor whose data type is float16, float32 or bool.
  1649. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number,
  1650. or a bool when the first input is a tensor, or a tensor whose data type is float16, float32 or bool.
  1651. Outputs:
  1652. Tensor, the shape is the same as the one after broadcasting,
  1653. and the data type is the one with higher precision or higher digits among the two inputs.
  1654. Examples:
  1655. >>> input_x = Tensor(np.array([2, 4, -1]), mindspore.float32)
  1656. >>> input_y = Tensor(np.array([2, 2, 2]), mindspore.float32)
  1657. >>> xdivy = P.Xdivy()
  1658. >>> xdivy(input_x, input_y)
  1659. [1.0, 2.0, -0.5]
  1660. """
  1661. def infer_dtype(self, x_dtype, y_dtype):
  1662. return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, [mstype.float16, mstype.float32], self.name)
  1663. class Xlogy(_MathBinaryOp):
  1664. """
  1665. Computes first input tensor multiplied by the logarithm of second input tensor element-wise.
  1666. Returns zero when `x` is zero.
  1667. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1668. The inputs must be two tensors or one tensor and one scalar.
  1669. When the inputs are two tensors,
  1670. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1671. When the inputs are one tensor and one scalar,
  1672. the scalar could only be a constant.
  1673. Inputs:
  1674. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1675. a bool or a tensor whose data type is float16, float32 or bool.
  1676. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1677. a bool when the first input is a tensor or a tensor whose data type is float16, float32 or bool.
  1678. The value must be positive.
  1679. Outputs:
  1680. Tensor, the shape is the same as the one after broadcasting,
  1681. and the data type is the one with higher precision or higher digits among the two inputs.
  1682. Examples:
  1683. >>> input_x = Tensor(np.array([-5, 0, 4]), mindspore.float32)
  1684. >>> input_y = Tensor(np.array([2, 2, 2]), mindspore.float32)
  1685. >>> xlogy = P.Xlogy()
  1686. >>> xlogy(input_x, input_y)
  1687. [-3.465736, 0.0, 2.7725887]
  1688. """
  1689. def infer_dtype(self, x_dtype, y_dtype):
  1690. return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, [mstype.float16, mstype.float32], self.name)
  1691. class Acosh(PrimitiveWithInfer):
  1692. """
  1693. Compute inverse hyperbolic cosine of the input element-wise.
  1694. Inputs:
  1695. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  1696. Outputs:
  1697. Tensor, has the same shape as `input_x`.
  1698. Examples:
  1699. >>> acosh = P.Acosh()
  1700. >>> input_x = Tensor(np.array([1.0, 1.5, 3.0, 100.0]), mindspore.float32)
  1701. >>> output = acosh(input_x)
  1702. """
  1703. @prim_attr_register
  1704. def __init__(self):
  1705. """Initialize Acosh"""
  1706. def infer_shape(self, x_shape):
  1707. return x_shape
  1708. def infer_dtype(self, x_dtype):
  1709. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
  1710. return x_dtype
  1711. class Cosh(PrimitiveWithInfer):
  1712. """
  1713. Computes hyperbolic cosine of input element-wise.
  1714. Inputs:
  1715. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  1716. Outputs:
  1717. Tensor, has the same shape as `input_x`.
  1718. Examples:
  1719. >>> cosh = P.Cosh()
  1720. >>> input_x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
  1721. >>> output = cosh(input_x)
  1722. [1.0289385 1.364684 1.048436 1.4228927]
  1723. """
  1724. @prim_attr_register
  1725. def __init__(self):
  1726. """Initialize Cosh"""
  1727. def infer_shape(self, x_shape):
  1728. return x_shape
  1729. def infer_dtype(self, x_dtype):
  1730. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
  1731. return x_dtype
  1732. class Asinh(PrimitiveWithInfer):
  1733. """
  1734. Compute inverse hyperbolic sine of the input element-wise.
  1735. Inputs:
  1736. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  1737. Outputs:
  1738. Tensor, has the same shape as `input_x`.
  1739. Examples:
  1740. >>> asinh = P.Asinh()
  1741. >>> input_x = Tensor(np.array([-5.0, 1.5, 3.0, 100.0]), mindspore.float32)
  1742. >>> output = asinh(input_x)
  1743. [-2.3212, 1.1976, 1.8184, 5.2983]
  1744. """
  1745. @prim_attr_register
  1746. def __init__(self):
  1747. """Initialize Asinh"""
  1748. def infer_shape(self, x_shape):
  1749. return x_shape
  1750. def infer_dtype(self, x_dtype):
  1751. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
  1752. return x_dtype
  1753. class Sinh(PrimitiveWithInfer):
  1754. """
  1755. Computes hyperbolic sine of input element-wise.
  1756. Inputs:
  1757. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  1758. Outputs:
  1759. Tensor, has the same shape as `input_x`.
  1760. Examples:
  1761. >>> sinh = P.Sinh()
  1762. >>> input_x = Tensor(np.array([0.62, 0.28, 0.43, 0.62]), mindspore.float32)
  1763. >>> output = sinh(input_x)
  1764. [0.6604918 0.28367308 0.44337422 0.6604918]
  1765. """
  1766. @prim_attr_register
  1767. def __init__(self):
  1768. """Initialize Sinh"""
  1769. def infer_shape(self, x_shape):
  1770. return x_shape
  1771. def infer_dtype(self, x_dtype):
  1772. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
  1773. return x_dtype
  1774. class _LogicBinaryOp(_BinaryOp):
  1775. """
  1776. Define logic binary operators.
  1777. """
  1778. @staticmethod
  1779. def do_infer_dtype(x_dtype, y_dtype, valid_type=mstype.number_type, prim_name=None):
  1780. args_dtype = {"x": x_dtype, "y": y_dtype}
  1781. validator.check_tensor_type_same(args_dtype, valid_type, prim_name)
  1782. return mstype.tensor_type(mstype.bool_)
  1783. def infer_dtype(self, x_dtype, y_dtype):
  1784. return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, prim_name=self.name)
  1785. class Equal(_LogicBinaryOp):
  1786. """
  1787. Computes the equivalence between two tensors element-wise.
  1788. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1789. The inputs must be two tensors or one tensor and one scalar.
  1790. When the inputs are two tensors, the shapes of them could be broadcast.
  1791. When the inputs are one tensor and one scalar, the scalar could only be a constant.
  1792. Inputs:
  1793. - **input_x** (Union[Tensor, Number]) - The first input is a number or
  1794. a tensor whose data type is number.
  1795. - **input_y** (Union[Tensor, Number]) - The second input is a number
  1796. when the first input is a tensor or a tensor whose data type is number.
  1797. Outputs:
  1798. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  1799. Examples:
  1800. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  1801. >>> equal = P.Equal()
  1802. >>> equal(input_x, 2.0)
  1803. [False, True, False]
  1804. >>>
  1805. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  1806. >>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
  1807. >>> equal = P.Equal()
  1808. >>> equal(input_x, input_y)
  1809. [True, True, False]
  1810. """
  1811. def infer_dtype(self, x_dtype, y_dtype):
  1812. return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, mstype.number_type + (mstype.bool_,), self.name)
  1813. class ApproximateEqual(_LogicBinaryOp):
  1814. """
  1815. Returns true if abs(x1-x2) is smaller than tolerance element-wise, otherwise false.
  1816. Inputs of `x1` and `x2` comply with the implicit type conversion rules to make the data types consistent.
  1817. If they have different data types, lower priority data type will be converted to
  1818. relatively highest priority data type.
  1819. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  1820. Args:
  1821. tolerance (float): The maximum deviation that two elements can be considered equal. Default: 1e-05.
  1822. Inputs:
  1823. - **x1** (Tensor) - A tensor. Must be one of the following types: float32, float16.
  1824. - **x2** (Tensor) - A tensor of the same type and shape as 'x1'.
  1825. Outputs:
  1826. Tensor, the shape is the same as the shape of 'x1', and the data type is bool.
  1827. Examples:
  1828. >>> x1 = Tensor(np.array([1, 2, 3]), mindspore.float32)
  1829. >>> x2 = Tensor(np.array([2, 4, 6]), mindspore.float32)
  1830. >>> approximate_equal = P.ApproximateEqual(2.)
  1831. >>> result = approximate_equal(x1, x2)
  1832. [True True False]
  1833. """
  1834. @prim_attr_register
  1835. def __init__(self, tolerance=1e-05):
  1836. """Initialize ApproximateEqual"""
  1837. validator.check_value_type("tolerance", tolerance, [float], self.name)
  1838. def infer_shape(self, x_shape, y_shape):
  1839. validator.check("x_shape", x_shape, "y_shape", y_shape, Rel.EQ, self.name)
  1840. return x_shape
  1841. def infer_dtype(self, x_dtype, y_dtype):
  1842. args_dtype = {"x": x_dtype, "y": y_dtype}
  1843. valid_type = [mstype.float32, mstype.float16]
  1844. validator.check_tensor_type_same(args_dtype, valid_type, prim_name=self.name)
  1845. return mstype.tensor_type(mstype.bool_)
  1846. class EqualCount(PrimitiveWithInfer):
  1847. """
  1848. Computes the number of the same elements of two tensors.
  1849. The two input tensors must have the same data type and shape.
  1850. Inputs:
  1851. - **input_x** (Tensor) - The first input tensor.
  1852. - **input_y** (Tensor) - The second input tensor.
  1853. Outputs:
  1854. Tensor, with the type same as input tensor and size as (1,).
  1855. Examples:
  1856. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  1857. >>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
  1858. >>> equal_count = P.EqualCount()
  1859. >>> equal_count(input_x, input_y)
  1860. [2]
  1861. """
  1862. @prim_attr_register
  1863. def __init__(self):
  1864. """Initialize EqualCount"""
  1865. self.init_prim_io_names(inputs=['x', 'y'], outputs=['output'])
  1866. def infer_shape(self, x_shape, y_shape):
  1867. validator.check("x_shape", x_shape, "y_shape", y_shape, Rel.EQ, self.name)
  1868. output_shape = (1,)
  1869. return output_shape
  1870. def infer_dtype(self, x_dtype, y_dtype):
  1871. args = {'x': x_dtype, 'y': y_dtype}
  1872. validator.check_tensor_type_same(args, mstype.number_type + (mstype.bool_,), self.name)
  1873. return x_dtype
  1874. class NotEqual(_LogicBinaryOp):
  1875. """
  1876. Computes the non-equivalence of two tensors element-wise.
  1877. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1878. The inputs must be two tensors or one tensor and one scalar.
  1879. When the inputs are two tensors, the shapes of them could be broadcast.
  1880. When the inputs are one tensor and one scalar, the scalar could only be a constant.
  1881. Inputs:
  1882. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1883. a bool or a tensor whose data type is number or bool.
  1884. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1885. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1886. Outputs:
  1887. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  1888. Examples:
  1889. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  1890. >>> not_equal = P.NotEqual()
  1891. >>> not_equal(input_x, 2.0)
  1892. [True, False, True]
  1893. >>>
  1894. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  1895. >>> input_y = Tensor(np.array([1, 2, 4]), mindspore.int32)
  1896. >>> not_equal = P.NotEqual()
  1897. >>> not_equal(input_x, input_y)
  1898. [False, False, True]
  1899. """
  1900. def infer_dtype(self, x_dtype, y_dtype):
  1901. return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, mstype.number_type + (mstype.bool_,), self.name)
  1902. class Greater(_LogicBinaryOp):
  1903. """
  1904. Computes the boolean value of :math:`x > y` element-wise.
  1905. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1906. The inputs must be two tensors or one tensor and one scalar.
  1907. When the inputs are two tensors,
  1908. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1909. When the inputs are one tensor and one scalar,
  1910. the scalar could only be a constant.
  1911. Inputs:
  1912. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1913. a bool or a tensor whose data type is number or bool.
  1914. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1915. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1916. Outputs:
  1917. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  1918. Examples:
  1919. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  1920. >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  1921. >>> greater = P.Greater()
  1922. >>> greater(input_x, input_y)
  1923. [False, True, False]
  1924. """
  1925. def infer_value(self, x, y):
  1926. if x is not None and y is not None:
  1927. x = x.asnumpy()
  1928. y = y.asnumpy()
  1929. out = np.array(np.greater(x, y))
  1930. return Tensor(out)
  1931. return None
  1932. class GreaterEqual(_LogicBinaryOp):
  1933. """
  1934. Computes the boolean value of :math:`x >= y` element-wise.
  1935. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1936. The inputs must be two tensors or one tensor and one scalar.
  1937. When the inputs are two tensors,
  1938. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1939. When the inputs are one tensor and one scalar,
  1940. the scalar could only be a constant.
  1941. Inputs:
  1942. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1943. a bool or a tensor whose data type is number or bool.
  1944. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1945. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1946. Outputs:
  1947. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  1948. Examples:
  1949. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  1950. >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  1951. >>> greater_equal = P.GreaterEqual()
  1952. >>> greater_equal(input_x, input_y)
  1953. [True, True, False]
  1954. """
  1955. def infer_value(self, x, y):
  1956. if x is not None and y is not None:
  1957. x = x.asnumpy()
  1958. y = y.asnumpy()
  1959. out = np.array(np.greater_equal(x, y))
  1960. return Tensor(out)
  1961. return None
  1962. class Less(_LogicBinaryOp):
  1963. """
  1964. Computes the boolean value of :math:`x < y` element-wise.
  1965. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1966. The inputs must be two tensors or one tensor and one scalar.
  1967. When the inputs are two tensors,
  1968. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1969. When the inputs are one tensor and one scalar,
  1970. the scalar could only be a constant.
  1971. Inputs:
  1972. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  1973. a bool or a tensor whose data type is number or bool.
  1974. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  1975. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1976. Outputs:
  1977. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  1978. Examples:
  1979. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  1980. >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  1981. >>> less = P.Less()
  1982. >>> less(input_x, input_y)
  1983. [False, False, True]
  1984. """
  1985. def infer_value(self, x, y):
  1986. if x is not None and y is not None:
  1987. x = x.asnumpy()
  1988. y = y.asnumpy()
  1989. out = np.array(np.less(x, y))
  1990. return Tensor(out)
  1991. return None
  1992. class LessEqual(_LogicBinaryOp):
  1993. """
  1994. Computes the boolean value of :math:`x <= y` element-wise.
  1995. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  1996. The inputs must be two tensors or one tensor and one scalar.
  1997. When the inputs are two tensors,
  1998. dtypes of them cannot be both bool , and the shapes of them could be broadcast.
  1999. When the inputs are one tensor and one scalar,
  2000. the scalar could only be a constant.
  2001. Inputs:
  2002. - **input_x** (Union[Tensor, Number, bool]) - The first input is a number or
  2003. a bool or a tensor whose data type is number or bool.
  2004. - **input_y** (Union[Tensor, Number, bool]) - The second input is a number or
  2005. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  2006. Outputs:
  2007. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  2008. Examples:
  2009. >>> input_x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2010. >>> input_y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  2011. >>> less_equal = P.LessEqual()
  2012. >>> less_equal(input_x, input_y)
  2013. [True, False, True]
  2014. """
  2015. def infer_value(self, x, y):
  2016. if x is not None and y is not None:
  2017. x = x.asnumpy()
  2018. y = y.asnumpy()
  2019. out = np.array(np.less_equal(x, y))
  2020. return Tensor(out)
  2021. return None
  2022. class LogicalNot(PrimitiveWithInfer):
  2023. """
  2024. Computes the "logical NOT" of a tensor element-wise.
  2025. Inputs:
  2026. - **input_x** (Tensor) - The input tensor whose dtype is bool.
  2027. Outputs:
  2028. Tensor, the shape is the same as the `input_x`, and the dtype is bool.
  2029. Examples:
  2030. >>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
  2031. >>> logical_not = P.LogicalNot()
  2032. >>> logical_not(input_x)
  2033. [False, True, False]
  2034. """
  2035. @prim_attr_register
  2036. def __init__(self):
  2037. """Initialize LogicalNot"""
  2038. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  2039. def infer_shape(self, x_shape):
  2040. return x_shape
  2041. def infer_dtype(self, x_dtype):
  2042. validator.check_tensor_type_same({"x": x_dtype}, [mstype.bool_], self.name)
  2043. return mstype.tensor_type(mstype.bool_)
  2044. class LogicalAnd(_LogicBinaryOp):
  2045. """
  2046. Computes the "logical AND" of two tensors element-wise.
  2047. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  2048. The inputs must be two tensors or one tensor and one bool.
  2049. When the inputs are two tensors, the shapes of them could be broadcast,
  2050. and the data types of them must be bool.
  2051. When the inputs are one tensor and one bool, the bool object could only be a constant,
  2052. and the data type of the tensor must be bool.
  2053. Inputs:
  2054. - **input_x** (Union[Tensor, bool]) - The first input is a bool or a tensor whose data type is bool.
  2055. - **input_y** (Union[Tensor, bool]) - The second input is a bool when the first input is a tensor or
  2056. a tensor whose data type is bool.
  2057. Outputs:
  2058. Tensor, the shape is the same as the one after broadcasting, and the data type is bool.
  2059. Examples:
  2060. >>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
  2061. >>> input_y = Tensor(np.array([True, True, False]), mindspore.bool_)
  2062. >>> logical_and = P.LogicalAnd()
  2063. >>> logical_and(input_x, input_y)
  2064. [True, False, False]
  2065. """
  2066. def infer_dtype(self, x_dtype, y_dtype):
  2067. return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, (mstype.bool_,), self.name)
  2068. class LogicalOr(_LogicBinaryOp):
  2069. """
  2070. Computes the "logical OR" of two tensors element-wise.
  2071. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  2072. The inputs must be two tensors or one tensor and one bool.
  2073. When the inputs are two tensors, the shapes of them could be broadcast,
  2074. and the data types of them must be bool.
  2075. When the inputs are one tensor and one bool, the bool object could only be a constant,
  2076. and the data type of the tensor must be bool.
  2077. Inputs:
  2078. - **input_x** (Union[Tensor, bool]) - The first input is a bool or a tensor whose data type is bool.
  2079. - **input_y** (Union[Tensor, bool]) - The second input is a bool when the first input is a tensor or
  2080. a tensor whose data type is bool.
  2081. Outputs:
  2082. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  2083. Examples:
  2084. >>> input_x = Tensor(np.array([True, False, True]), mindspore.bool_)
  2085. >>> input_y = Tensor(np.array([True, True, False]), mindspore.bool_)
  2086. >>> logical_or = P.LogicalOr()
  2087. >>> logical_or(input_x, input_y)
  2088. [True, True, True]
  2089. """
  2090. def infer_dtype(self, x_dtype, y_dtype):
  2091. return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, (mstype.bool_,), self.name)
  2092. class IsNan(PrimitiveWithInfer):
  2093. """
  2094. Judge which elements are nan for each position.
  2095. Inputs:
  2096. - **input_x** (Tensor) - The input tensor.
  2097. Outputs:
  2098. Tensor, has the same shape of input, and the dtype is bool.
  2099. Examples:
  2100. >>> is_nan = P.IsNan()
  2101. >>> input_x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
  2102. >>> result = is_nan(input_x)
  2103. """
  2104. @prim_attr_register
  2105. def __init__(self):
  2106. """Initialize IsNan"""
  2107. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  2108. def infer_shape(self, x_shape):
  2109. return x_shape
  2110. def infer_dtype(self, x_dtype):
  2111. return mstype.bool_
  2112. class IsInf(PrimitiveWithInfer):
  2113. """
  2114. Judging which elements are inf or -inf for each position
  2115. Inputs:
  2116. - **input_x** (Tensor) - The input tensor.
  2117. Outputs:
  2118. Tensor, has the same shape of input, and the dtype is bool.
  2119. Examples:
  2120. >>> is_inf = P.IsInf()
  2121. >>> input_x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
  2122. >>> result = is_inf(input_x)
  2123. """
  2124. @prim_attr_register
  2125. def __init__(self):
  2126. """Initialize IsInf"""
  2127. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  2128. def infer_shape(self, x_shape):
  2129. return x_shape
  2130. def infer_dtype(self, x_dtype):
  2131. return mstype.bool_
  2132. class IsFinite(PrimitiveWithInfer):
  2133. """
  2134. Judge which elements are finite for each position.
  2135. Inputs:
  2136. - **input_x** (Tensor) - The input tensor.
  2137. Outputs:
  2138. Tensor, has the same shape of input, and the dtype is bool.
  2139. Examples:
  2140. >>> is_finite = P.IsFinite()
  2141. >>> input_x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
  2142. >>> result = is_finite(input_x)
  2143. [False True False]
  2144. """
  2145. @prim_attr_register
  2146. def __init__(self):
  2147. """Initialize IsFinite"""
  2148. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  2149. def infer_shape(self, x_shape):
  2150. return x_shape
  2151. def infer_dtype(self, x_dtype):
  2152. validator.check_subclass("x", x_dtype, mstype.tensor, self.name)
  2153. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type + (mstype.bool_,), self.name)
  2154. return mstype.bool_
  2155. class FloatStatus(PrimitiveWithInfer):
  2156. """
  2157. Determine if the elements contain Not a Number(NaN), infinite or negative infinite. 0 for normal, 1 for overflow.
  2158. Inputs:
  2159. - **input_x** (Tensor) - The input tensor. The data type must be float16 or float32.
  2160. Outputs:
  2161. Tensor, has the shape of `(1,)`, and has the same dtype of input `mindspore.dtype.float32` or
  2162. `mindspore.dtype.float16`.
  2163. Examples:
  2164. >>> float_status = P.FloatStatus()
  2165. >>> input_x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
  2166. >>> result = float_status(input_x)
  2167. """
  2168. @prim_attr_register
  2169. def __init__(self):
  2170. """Initialize FloatStatus"""
  2171. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  2172. def infer_shape(self, x_shape):
  2173. return [1]
  2174. def infer_dtype(self, x_dtype):
  2175. validator.check_tensor_type_same({'x': x_dtype}, [mstype.float32, mstype.float16], self.name)
  2176. return x_dtype
  2177. class NPUAllocFloatStatus(PrimitiveWithInfer):
  2178. """
  2179. Allocates a flag to store the overflow status.
  2180. The flag is a tensor whose shape is `(8,)` and data type is `mindspore.dtype.float32`.
  2181. Note:
  2182. Examples: see `NPUGetFloatStatus`.
  2183. Outputs:
  2184. Tensor, has the shape of `(8,)`.
  2185. Examples:
  2186. >>> alloc_status = P.NPUAllocFloatStatus()
  2187. >>> init = alloc_status()
  2188. Tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], shape=(8,), dtype=mindspore.float32)
  2189. """
  2190. @prim_attr_register
  2191. def __init__(self):
  2192. """Initialize NPUAllocFloatStatus"""
  2193. self.add_prim_attr("_side_effect_flag", True)
  2194. def infer_shape(self):
  2195. return [8]
  2196. def infer_dtype(self):
  2197. return mstype.float32
  2198. class NPUGetFloatStatus(PrimitiveWithInfer):
  2199. """
  2200. Updates the flag which is the output tensor of `NPUAllocFloatStatus` with latest overflow status.
  2201. The flag is a tensor whose shape is `(8,)` and data type is `mindspore.dtype.float32`.
  2202. If the sum of the flag equals to 0, there is no overflow happened. If the sum of the flag is bigger than 0, there
  2203. is overflow happened.
  2204. Inputs:
  2205. - **input_x** (Tensor) - The output tensor of `NPUAllocFloatStatus`.
  2206. The data type must be float16 or float32.
  2207. Outputs:
  2208. Tensor, has the same shape as `input_x`. All the elements in the tensor will be zero.
  2209. Examples:
  2210. >>> alloc_status = P.NPUAllocFloatStatus()
  2211. >>> get_status = P.NPUGetFloatStatus()
  2212. >>> init = alloc_status()
  2213. >>> flag = get_status(init)
  2214. Tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], shape=(8,), dtype=mindspore.float32)
  2215. """
  2216. @prim_attr_register
  2217. def __init__(self):
  2218. """Initialize NPUGetFloatStatus"""
  2219. self.add_prim_attr("_side_effect_flag", True)
  2220. def infer_shape(self, x_shape):
  2221. cls_name = self.name
  2222. validator.check_equal_int(len(x_shape), 1, "len(x_shape)", cls_name)
  2223. validator.check_equal_int(x_shape[0], 8, "x_shape[0]", cls_name)
  2224. return [8]
  2225. def infer_dtype(self, x_dtype):
  2226. validator.check_tensor_type_same({'x': x_dtype}, [mstype.float16, mstype.float32], self.name)
  2227. return mstype.float32
  2228. class NPUClearFloatStatus(PrimitiveWithInfer):
  2229. """
  2230. Clear the flag which stores the overflow status.
  2231. Note:
  2232. The flag is in the register on the `Ascend` device. It will be reset and can not be reused again after the
  2233. `NPUClearFloatStatus` is called.
  2234. Examples: see `NPUGetFloatStatus`.
  2235. Inputs:
  2236. - **input_x** (Tensor) - The output tensor of `NPUAllocFloatStatus`.
  2237. The data type must be float16 or float32.
  2238. Outputs:
  2239. Tensor, has the same shape as `input_x`. All the elements in the tensor will be zero.
  2240. Examples:
  2241. >>> alloc_status = P.NPUAllocFloatStatus()
  2242. >>> get_status = P.NPUGetFloatStatus()
  2243. >>> clear_status = P.NPUClearFloatStatus()
  2244. >>> init = alloc_status()
  2245. >>> flag = get_status(init)
  2246. >>> clear = clear_status(init)
  2247. Tensor([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], shape=(8,), dtype=mindspore.float32)
  2248. """
  2249. @prim_attr_register
  2250. def __init__(self):
  2251. """Initialize NPUClearFloatStatus"""
  2252. self.add_prim_attr("_side_effect_flag", True)
  2253. def infer_shape(self, x_shape):
  2254. cls_name = self.name
  2255. validator.check_equal_int(len(x_shape), 1, "len(x_shape)", cls_name)
  2256. validator.check_equal_int(x_shape[0], 8, "x_shape[0]", cls_name)
  2257. return [8]
  2258. def infer_dtype(self, x_dtype):
  2259. validator.check_tensor_type_same({'x': x_dtype}, [mstype.float16, mstype.float32], self.name)
  2260. return mstype.float32
  2261. class Cos(PrimitiveWithInfer):
  2262. """
  2263. Computes cosine of input element-wise.
  2264. Inputs:
  2265. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  2266. Outputs:
  2267. Tensor, has the same shape as `input_x`.
  2268. Examples:
  2269. >>> cos = P.Cos()
  2270. >>> input_x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
  2271. >>> output = cos(input_x)
  2272. """
  2273. @prim_attr_register
  2274. def __init__(self):
  2275. """Initialize Cos"""
  2276. def infer_shape(self, x_shape):
  2277. return x_shape
  2278. def infer_dtype(self, x_dtype):
  2279. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
  2280. return x_dtype
  2281. class ACos(PrimitiveWithInfer):
  2282. """
  2283. Computes arccosine of input element-wise.
  2284. Inputs:
  2285. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  2286. Outputs:
  2287. Tensor, has the same shape as `input_x`.
  2288. Examples:
  2289. >>> acos = P.ACos()
  2290. >>> input_x = Tensor(np.array([0.74, 0.04, 0.30, 0.56]), mindspore.float32)
  2291. >>> output = acos(input_x)
  2292. """
  2293. @prim_attr_register
  2294. def __init__(self):
  2295. """Initialize ACos"""
  2296. def infer_shape(self, x_shape):
  2297. return x_shape
  2298. def infer_dtype(self, x_dtype):
  2299. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
  2300. return x_dtype
  2301. class Sin(PrimitiveWithInfer):
  2302. """
  2303. Computes sine of input element-wise.
  2304. Inputs:
  2305. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  2306. Outputs:
  2307. Tensor, has the same shape as `input_x`.
  2308. Examples:
  2309. >>> sin = P.Sin()
  2310. >>> input_x = Tensor(np.array([0.62, 0.28, 0.43, 0.62]), mindspore.float32)
  2311. >>> output = sin(input_x)
  2312. [0.5810352 0.27635565 0.41687083 0.5810352]
  2313. """
  2314. @prim_attr_register
  2315. def __init__(self):
  2316. """Initialize Sin."""
  2317. def infer_shape(self, x_shape):
  2318. return x_shape
  2319. def infer_dtype(self, x_dtype):
  2320. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
  2321. return x_dtype
  2322. class Asin(PrimitiveWithInfer):
  2323. """
  2324. Computes arcsine of input element-wise.
  2325. Inputs:
  2326. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  2327. Outputs:
  2328. Tensor, has the same shape as `input_x`.
  2329. Examples:
  2330. >>> asin = P.Asin()
  2331. >>> input_x = Tensor(np.array([0.74, 0.04, 0.30, 0.56]), mindspore.float32)
  2332. >>> output = asin(input_x)
  2333. [0.8331, 0.0400, 0.3047, 0.5944]
  2334. """
  2335. @prim_attr_register
  2336. def __init__(self):
  2337. """Initialize Asin"""
  2338. def infer_shape(self, x_shape):
  2339. return x_shape
  2340. def infer_dtype(self, x_dtype):
  2341. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
  2342. return x_dtype
  2343. class NMSWithMask(PrimitiveWithInfer):
  2344. """
  2345. Select some bounding boxes in descending order of score.
  2346. Args:
  2347. iou_threshold (float): Specifies the threshold of overlap boxes with respect to
  2348. IOU. Default: 0.5.
  2349. Raises:
  2350. ValueError: If the iou_threshold is not a float number, or if the first dimension
  2351. of input Tensor is less than or equal to 0, or if the data type of the input
  2352. Tensor is not float16 or float32.
  2353. Inputs:
  2354. - **bboxes** (Tensor) - The shape of tensor is :math:`(N, 5)`. Input bounding boxes.
  2355. `N` is the number of input bounding boxes. Every bounding box
  2356. contains 5 values, the first 4 values are the coordinates of bounding
  2357. box, and the last value is the score of this bounding box.
  2358. The data type must be float16 or float32.
  2359. Outputs:
  2360. tuple[Tensor], tuple of three tensors, they are selected_boxes, selected_idx and selected_mask.
  2361. - **selected_boxes** (Tensor) - The shape of tensor is :math:`(N, 5)`. The list of bounding boxes
  2362. after non-max suppression calculation.
  2363. - **selected_idx** (Tensor) - The shape of tensor is :math:`(N,)`. The indexes list of
  2364. valid input bounding boxes.
  2365. - **selected_mask** (Tensor) - The shape of tensor is :math:`(N,)`. A mask list of
  2366. valid output bounding boxes.
  2367. Examples:
  2368. >>> bbox = np.random.rand(128, 5)
  2369. >>> bbox[:, 2] += bbox[:, 0]
  2370. >>> bbox[:, 3] += bbox[:, 1]
  2371. >>> inputs = Tensor(bbox, mindspore.float32)
  2372. >>> nms = P.NMSWithMask(0.5)
  2373. >>> output_boxes, indices, mask = nms(inputs)
  2374. """
  2375. @prim_attr_register
  2376. def __init__(self, iou_threshold=0.5):
  2377. """Initialize NMSWithMask"""
  2378. validator.check_value_type("iou_threshold", iou_threshold, [float], self.name)
  2379. self.init_prim_io_names(inputs=['bboxes'], outputs=['selected_boxes', 'selected_idx', 'selected_mask'])
  2380. self.is_ge = context.get_context("enable_ge")
  2381. def infer_shape(self, bboxes_shape):
  2382. cls_name = self.name
  2383. validator.check_equal_int(len(bboxes_shape), 2, "bboxes rank", cls_name)
  2384. validator.check_positive_int(bboxes_shape[0], "bboxes.shape[0]", cls_name)
  2385. validator.check_equal_int(bboxes_shape[1], 5, "bboxes.shape[1]", cls_name)
  2386. num = bboxes_shape[0]
  2387. return (bboxes_shape, (num,), (num,))
  2388. def infer_dtype(self, bboxes_dtype):
  2389. validator.check_tensor_type_same({"bboxes": bboxes_dtype}, [mstype.float16, mstype.float32], self.name)
  2390. return (bboxes_dtype, mstype.int32, mstype.bool_)
  2391. class Abs(PrimitiveWithInfer):
  2392. """
  2393. Returns absolute value of a tensor element-wise.
  2394. Inputs:
  2395. - **input_x** (Tensor) - The input tensor. The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  2396. Outputs:
  2397. Tensor, has the same shape as the `input_x`.
  2398. Examples:
  2399. >>> input_x = Tensor(np.array([-1.0, 1.0, 0.0]), mindspore.float32)
  2400. >>> abs = P.Abs()
  2401. >>> abs(input_x)
  2402. [1.0, 1.0, 0.0]
  2403. """
  2404. @prim_attr_register
  2405. def __init__(self):
  2406. """Initialize Abs"""
  2407. self.init_prim_io_names(inputs=['input_x'], outputs=['output'])
  2408. def infer_shape(self, x_shape):
  2409. return x_shape
  2410. def infer_dtype(self, x_type):
  2411. validator.check_tensor_type_same({'x': x_type}, mstype.number_type, self.name)
  2412. return x_type
  2413. def infer_value(self, x):
  2414. if x is not None:
  2415. x = x.asnumpy()
  2416. out = np.array(np.abs(x, dtype=x.dtype))
  2417. return Tensor(out)
  2418. return None
  2419. class Sign(PrimitiveWithInfer):
  2420. r"""
  2421. Perform :math:`sign` on tensor element-wise.
  2422. Note:
  2423. .. math::
  2424. sign(x) = \begin{cases} -1, &if\ x < 0 \cr
  2425. 0, &if\ x = 0 \cr
  2426. 1, &if\ x > 0\end{cases}
  2427. Inputs:
  2428. - **input_x** (Tensor) - The input tensor.
  2429. Outputs:
  2430. Tensor, has the same shape and type as the `input_x`.
  2431. Examples:
  2432. >>> input_x = Tensor(np.array([[2.0, 0.0, -1.0]]), mindspore.float32)
  2433. >>> sign = P.Sign()
  2434. >>> output = sign(input_x)
  2435. [[1.0, 0.0, -1.0]]
  2436. """
  2437. @prim_attr_register
  2438. def __init__(self):
  2439. pass
  2440. def infer_shape(self, x_shape):
  2441. return x_shape
  2442. def infer_dtype(self, x_dtype):
  2443. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type, self.name)
  2444. return x_dtype
  2445. class Round(PrimitiveWithInfer):
  2446. """
  2447. Returns half to even of a tensor element-wise.
  2448. Inputs:
  2449. - **input_x** (Tensor) - The input tensor.
  2450. Outputs:
  2451. Tensor, has the same shape and type as the `input_x`.
  2452. Examples:
  2453. >>> input_x = Tensor(np.array([0.8, 1.5, 2.3, 2.5, -4.5]), mindspore.float32)
  2454. >>> round = P.Round()
  2455. >>> round(input_x)
  2456. [1.0, 2.0, 2.0, 2.0, -4.0]
  2457. """
  2458. @prim_attr_register
  2459. def __init__(self):
  2460. """Initialize Round"""
  2461. self.init_prim_io_names(inputs=['input_x'], outputs=['output'])
  2462. def infer_shape(self, x_shape):
  2463. return x_shape
  2464. def infer_dtype(self, x_type):
  2465. validator.check_tensor_type_same({'x': x_type}, mstype.number_type, self.name)
  2466. return x_type
  2467. class Tan(PrimitiveWithInfer):
  2468. """
  2469. Computes tangent of `input_x` element-wise.
  2470. Inputs:
  2471. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. Data type must be
  2472. float16, float32 or int32.
  2473. Outputs:
  2474. Tensor, has the same shape as `input_x`.
  2475. Examples:
  2476. >>> tan = P.Tan()
  2477. >>> input_x = Tensor(np.array([-1.0, 0.0, 1.0]), mindspore.float32)
  2478. >>> output = tan(input_x)
  2479. """
  2480. @prim_attr_register
  2481. def __init__(self):
  2482. """Initialize Tan"""
  2483. def infer_shape(self, x_shape):
  2484. return x_shape
  2485. def infer_dtype(self, x_type):
  2486. valid_types = [mstype.float16, mstype.float32, mstype.int32]
  2487. validator.check_tensor_type_same({'x': x_type}, valid_types, self.name)
  2488. return x_type
  2489. class Atan(PrimitiveWithInfer):
  2490. """
  2491. Computes the trigonometric inverse tangent of the input element-wise.
  2492. Inputs:
  2493. - **input_x** (Tensor): The input tensor.
  2494. Outputs:
  2495. A Tensor, has the same type as the input.
  2496. Examples:
  2497. >>> input_x = Tensor(np.array([1.047, 0.785]), mindspore.float32)
  2498. >>> tan = P.Tan()
  2499. >>> output_y = tan(input_x)
  2500. >>> atan = P.Atan()
  2501. >>> atan(output_y)
  2502. [[1.047, 07850001]]
  2503. """
  2504. @prim_attr_register
  2505. def __init__(self):
  2506. pass
  2507. def infer_shape(self, x_shape):
  2508. return x_shape
  2509. def infer_dtype(self, x_type):
  2510. validator.check_tensor_type_same({'x': x_type}, mstype.number_type, self.name)
  2511. return x_type
  2512. class Atanh(PrimitiveWithInfer):
  2513. """
  2514. Computes inverse hyperbolic tangent of the input element-wise.
  2515. Inputs:
  2516. - **input_x** (Tensor): The input tensor.
  2517. Outputs:
  2518. A Tensor, has the same type as the input.
  2519. Examples:
  2520. >>> input_x = Tensor(np.array([1.047, 0.785]), mindspore.float32)
  2521. >>> atanh = P.Atanh()
  2522. >>> atanh(input_x)
  2523. [[1.8869909 1.058268]]
  2524. """
  2525. @prim_attr_register
  2526. def __init__(self):
  2527. pass
  2528. def infer_shape(self, x_shape):
  2529. return x_shape
  2530. def infer_dtype(self, x_type):
  2531. validator.check_tensor_type_same({'x': x_type}, mstype.number_type, self.name)
  2532. return x_type
  2533. class Atan2(_MathBinaryOp):
  2534. r"""
  2535. Returns arctangent of input_x/input_y element-wise.
  2536. It returns :math:`\theta\ \in\ [-\pi, \pi]`
  2537. such that :math:`x = r*\sin(\theta), y = r*\cos(\theta)`, where :math:`r = \sqrt{x^2 + y^2}`.
  2538. Inputs of `input_x` and `input_y` comply with the implicit type conversion rules to make the data types consistent.
  2539. If they have different data types, lower priority data type will be converted to
  2540. relatively highest priority data type.
  2541. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2542. Inputs:
  2543. - **input_x** (Tensor) - The input tensor.
  2544. - **input_y** (Tensor) - The input tensor.
  2545. Outputs:
  2546. Tensor, the shape is the same as the one after broadcasting,and the data type is same as `input_x`.
  2547. Examples:
  2548. >>> input_x = Tensor(np.array([[0, 1]]), mindspore.float32)
  2549. >>> input_y = Tensor(np.array([[1, 1]]), mindspore.float32)
  2550. >>> atan2 = P.Atan2()
  2551. >>> atan2(input_x, input_y)
  2552. [[0. 0.7853982]]
  2553. """
  2554. class SquareSumAll(PrimitiveWithInfer):
  2555. """
  2556. Returns square sum all of a tensor element-wise
  2557. Inputs:
  2558. - **input_x1** (Tensor) - The input tensor. The data type must be float16 or float32.
  2559. - **input_x2** (Tensor) - The input tensor has the same type and shape as the `input_x1`.
  2560. Note:
  2561. SquareSumAll only supports float16 and float32 data type.
  2562. Outputs:
  2563. - **output_y1** (Tensor) - The same type as the `input_x1`.
  2564. - **output_y2** (Tensor) - The same type as the `input_x1`.
  2565. Examples:
  2566. >>> input_x1 = Tensor(np.array([0, 0, 2, 0]), mindspore.float32)
  2567. >>> input_x2 = Tensor(np.array([0, 0, 2, 4]), mindspore.float32)
  2568. >>> square_sum_all = P.SquareSumAll()
  2569. >>> square_sum_all(input_x1, input_x2)
  2570. (4, 20)
  2571. """
  2572. @prim_attr_register
  2573. def __init__(self):
  2574. """Initialize SquareSumAll"""
  2575. def infer_shape(self, x_shape, y_shape):
  2576. validator.check("x1_shape", x_shape, "x2_shape", y_shape, Rel.EQ, self.name)
  2577. return [], []
  2578. def infer_dtype(self, x_type, y_type):
  2579. validator.check_tensor_type_same({'x1_type': x_type}, [mstype.float16, mstype.float32], self.name)
  2580. validator.check_tensor_type_same({'x2_type': y_type}, [mstype.float16, mstype.float32], self.name)
  2581. return x_type, y_type
  2582. class BitwiseAnd(_BitwiseBinaryOp):
  2583. """
  2584. Returns bitwise `and` of two tensors element-wise.
  2585. Inputs of `input_x1` and `input_x2` comply with the implicit type conversion rules to
  2586. make the data types consistent.
  2587. If they have different data types, lower priority data type will be converted to
  2588. relatively highest priority data type.
  2589. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2590. Inputs:
  2591. - **input_x1** (Tensor) - The input tensor with int16, int32 or uint16 data type.
  2592. - **input_x2** (Tensor) - The input tensor with same type as the `input_x1`.
  2593. Outputs:
  2594. - **y** (Tensor) - The same type as the `input_x1`.
  2595. Examples:
  2596. >>> input_x1 = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mstype.int16)
  2597. >>> input_x2 = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mstype.int16)
  2598. >>> bitwise_and = P.BitwiseAnd()
  2599. >>> bitwise_and(input_x1, input_x2)
  2600. [0, 0, 1, -1, 1, 0, 1]
  2601. """
  2602. class BitwiseOr(_BitwiseBinaryOp):
  2603. """
  2604. Returns bitwise `or` of two tensors element-wise.
  2605. Inputs of `input_x1` and `input_x2` comply with the implicit type conversion rules to
  2606. make the data types consistent.
  2607. If they have different data types, lower priority data type will be converted to
  2608. relatively highest priority data type.
  2609. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2610. Inputs:
  2611. - **input_x1** (Tensor) - The input tensor with int16, int32 or uint16 data type.
  2612. - **input_x2** (Tensor) - The input tensor with same type as the `input_x1`.
  2613. Outputs:
  2614. - **y** (Tensor) - The same type as the `input_x1`.
  2615. Examples:
  2616. >>> input_x1 = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mstype.int16)
  2617. >>> input_x2 = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mstype.int16)
  2618. >>> bitwise_or = P.BitwiseOr()
  2619. >>> bitwise_or(input_x1, input_x2)
  2620. [0, 1, 1, -1, -1, 3, 3]
  2621. """
  2622. class BitwiseXor(_BitwiseBinaryOp):
  2623. """
  2624. Returns bitwise `xor` of two tensors element-wise.
  2625. Inputs of `input_x1` and `input_x2` comply with the implicit type conversion rules to
  2626. make the data types consistent.
  2627. If they have different data types, lower priority data type will be converted to
  2628. relatively highest priority data type.
  2629. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2630. Inputs:
  2631. - **input_x1** (Tensor) - The input tensor with int16, int32 or uint16 data type.
  2632. - **input_x2** (Tensor) - The input tensor with same type as the `input_x1`.
  2633. Outputs:
  2634. - **y** (Tensor) - The same type as the `input_x1`.
  2635. Examples:
  2636. >>> input_x1 = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mstype.int16)
  2637. >>> input_x2 = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mstype.int16)
  2638. >>> bitwise_xor = P.BitwiseXor()
  2639. >>> bitwise_xor(input_x1, input_x2)
  2640. [0, 1, 0, 0, -2, 3, 2]
  2641. """
  2642. class BesselI0e(PrimitiveWithInfer):
  2643. """
  2644. Computes BesselI0e of input element-wise.
  2645. Inputs:
  2646. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  2647. Outputs:
  2648. Tensor, has the same shape as `input_x`. Data type must be float16 or float32.
  2649. Examples:
  2650. >>> bessel_i0e = P.BesselI0e()
  2651. >>> input_x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
  2652. >>> output = bessel_i0e(input_x)
  2653. [0.7979961, 0.5144438, 0.75117415, 0.9157829]
  2654. """
  2655. @prim_attr_register
  2656. def __init__(self):
  2657. """Initialize BesselI0e"""
  2658. def infer_shape(self, x):
  2659. return x
  2660. def infer_dtype(self, x):
  2661. validator.check_tensor_type_same({'x': x}, mstype.number_type, self.name)
  2662. return x
  2663. class BesselI1e(PrimitiveWithInfer):
  2664. """
  2665. Computes BesselI1e of input element-wise.
  2666. Inputs:
  2667. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  2668. Outputs:
  2669. Tensor, has the same shape as `input_x`. Data type must be float16 or float32.
  2670. Examples:
  2671. >>> bessel_i1e = P.BesselI1e()
  2672. >>> input_x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
  2673. >>> output = bessel_i1e(input_x)
  2674. [0.09507662, 0.19699717, 0.11505538, 0.04116856]
  2675. """
  2676. @prim_attr_register
  2677. def __init__(self):
  2678. """Initialize BesselI1e"""
  2679. def infer_shape(self, x):
  2680. return x
  2681. def infer_dtype(self, x):
  2682. validator.check_tensor_type_same({'x': x}, mstype.number_type, self.name)
  2683. return x
  2684. class Inv(PrimitiveWithInfer):
  2685. """
  2686. Computes Inv(Reciprocal) of input tensor element-wise.
  2687. Inputs:
  2688. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  2689. Must be one of the following types: float16, float32, int32.
  2690. Outputs:
  2691. Tensor, has the same shape and data type as `input_x`.
  2692. Examples:
  2693. >>> inv = P.Inv()
  2694. >>> input_x = Tensor(np.array([0.25, 0.4, 0.31, 0.52]), mindspore.float32)
  2695. >>> output = inv(input_x)
  2696. [4., 2.5, 3.2258065, 1.923077]
  2697. """
  2698. @prim_attr_register
  2699. def __init__(self):
  2700. pass
  2701. def infer_shape(self, x_shape):
  2702. return x_shape
  2703. def infer_dtype(self, x_dtype):
  2704. validator.check_tensor_type_same({'x_dtype': x_dtype}, [mstype.float16, mstype.float32,
  2705. mstype.int32], self.name)
  2706. return x_dtype
  2707. class Invert(PrimitiveWithInfer):
  2708. """
  2709. Flips all bits of input tensor element-wise.
  2710. Inputs:
  2711. - **input_x** (Tensor[int16], Tensor[uint16]) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  2712. Outputs:
  2713. Tensor, has the same shape as `input_x`.
  2714. Examples:
  2715. >>> invert = P.Invert()
  2716. >>> input_x = Tensor(np.array([25, 4, 13, 9]), mindspore.int16)
  2717. >>> output = invert(input_x)
  2718. [-26, -5, -14, -10]
  2719. """
  2720. @prim_attr_register
  2721. def __init__(self):
  2722. pass
  2723. def infer_shape(self, x_shape):
  2724. return x_shape
  2725. def infer_dtype(self, x_dtype):
  2726. validator.check_tensor_type_same({'x_dtype': x_dtype}, [mstype.int16, mstype.uint16], self.name)
  2727. return x_dtype
  2728. class Eps(PrimitiveWithInfer):
  2729. """
  2730. Creates a tensor filled with `input_x` dtype minimum val.
  2731. Inputs:
  2732. - **input_x** (Tensor) - Input tensor. The data type must be float16 or float32.
  2733. Outputs:
  2734. Tensor, has the same type and shape as `input_x`, but filled with `input_x` dtype minimum val.
  2735. Examples:
  2736. >>> input_x = Tensor([4, 1, 2, 3], mindspore.float32)
  2737. >>> out = P.Eps()(input_x)
  2738. [1.52587891e-05, 1.52587891e-05, 1.52587891e-05, 1.52587891e-05]
  2739. """
  2740. @prim_attr_register
  2741. def __init__(self):
  2742. """Initialize Eps"""
  2743. self.init_prim_io_names(inputs=['input_x'], outputs=['y'])
  2744. def __infer__(self, input_x):
  2745. valid_types = [mstype.float16, mstype.float32]
  2746. validator.check_tensor_type_same({'input_x': input_x['dtype']}, valid_types, self.name)
  2747. x_nptype = mstype.dtype_to_nptype(input_x['dtype'].element_type())
  2748. if x_nptype == np.float16:
  2749. min_val = 2 ** (-14)
  2750. else:
  2751. min_val = 2 ** (-16)
  2752. res = np.full(input_x['shape'], min_val, x_nptype)
  2753. out = {
  2754. 'value': Tensor(res),
  2755. 'shape': input_x['shape'],
  2756. 'dtype': input_x['dtype'],
  2757. }
  2758. return out
  2759. class IFMR(PrimitiveWithInfer):
  2760. """
  2761. The TFMR(Input Feature Map Reconstruction).
  2762. Args:
  2763. min_percentile (float): Min init percentile.
  2764. max_percentile (float): Max init percentile.
  2765. search_range Union[list(float), tuple(float)]: Range of searching.
  2766. search_step (float): Step size of searching.
  2767. with_offset (bool): Whether using offset.
  2768. Inputs:
  2769. - **data** (Tensor) - A Tensor of feature map. With float16 or float32 data type.
  2770. - **data_min** (Tensor) - A Tensor of min value of feature map, the shape is :math:`(1)`.
  2771. With float16 or float32 data type.
  2772. - **data_max** (Tensor) - A Tensor of max value of feature map, the shape is :math:`(1)`.
  2773. With float16 or float32 data type.
  2774. - **cumsum** (Tensor) - A `1-D` Tensor of cumsum bin of data. With int32 data type.
  2775. Outputs:
  2776. - **scale** (Tensor) - A tensor of optimal scale, the shape is :math:`(1)`. Data dtype is float32.
  2777. - **offset** (Tensor) - A tensor of optimal offset, the shape is :math:`(1)`. Data dtype is float32.
  2778. Examples:
  2779. >>> data = Tensor(np.random.rand(1, 3, 6, 4).astype(np.float32))
  2780. >>> data_min = Tensor([0.1], mstype.float32)
  2781. >>> data_max = Tensor([0.5], mstype.float32)
  2782. >>> cumsum = Tensor(np.random.rand(4).astype(np.int32))
  2783. >>> ifmr = P.IFMR(min_percentile=0.2, max_percentile=0.9, search_range=(1.0, 2.0),
  2784. search_step=1.0, with_offset=False)
  2785. >>> output = ifmr(data, data_min, data_max, cumsum)
  2786. """
  2787. @prim_attr_register
  2788. def __init__(self, min_percentile, max_percentile, search_range, search_step, with_offset):
  2789. validator.check_value_type("min_percentile", min_percentile, [float], self.name)
  2790. validator.check_value_type("max_percentile", max_percentile, [float], self.name)
  2791. validator.check_value_type("search_range", search_range, [list, tuple], self.name)
  2792. for item in search_range:
  2793. validator.check_positive_float(item, "item of search_range", self.name)
  2794. validator.check('search_range[1]', search_range[1], 'search_range[0]', search_range[0], Rel.GE, self.name)
  2795. validator.check_value_type("search_step", search_step, [float], self.name)
  2796. validator.check_value_type("offset_flag", with_offset, [bool], self.name)
  2797. def infer_shape(self, data_shape, data_min_shape, data_max_shape, cumsum_shape):
  2798. validator.check_equal_int(len(data_min_shape), 1, "dims of data_min", self.name)
  2799. validator.check_equal_int(data_min_shape[0], 1, "data_min[0]", self.name)
  2800. validator.check_equal_int(len(data_max_shape), 1, "dims of data_max", self.name)
  2801. validator.check_equal_int(data_max_shape[0], 1, "data_max[0]", self.name)
  2802. validator.check_equal_int(len(cumsum_shape), 1, "dims of cumsum", self.name)
  2803. return (1,), (1,)
  2804. def infer_dtype(self, data_dtype, data_min_dtype, data_max_dtype, cumsum_dtype):
  2805. valid_types = [mstype.float32, mstype.float16]
  2806. validator.check_tensor_type_same({"input_value": data_dtype}, valid_types, self.name)
  2807. validator.check_tensor_type_same({"input_min": data_min_dtype}, valid_types, self.name)
  2808. validator.check_tensor_type_same({"input_max": data_max_dtype}, valid_types, self.name)
  2809. validator.check_tensor_type_same({"input_bins": cumsum_dtype}, [mstype.int32], self.name)
  2810. return mstype.tensor_type(mstype.float32), mstype.tensor_type(mstype.float32)