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.

array_ops.py 164 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
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
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010
  1. # coding: utf-8
  2. # Copyright 2020 Huawei Technologies Co., Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. # ============================================================================
  16. """Operators for array."""
  17. import copy
  18. import functools
  19. import itertools
  20. import numbers
  21. import numpy as np
  22. from .._utils import get_concat_offset
  23. from ..operations.math_ops import _infer_shape_reduce
  24. from ..primitive import Primitive, PrimitiveWithInfer, PrimitiveWithCheck, prim_attr_register, _run_op
  25. from .. import signature as sig
  26. from ..._checkparam import Rel
  27. from ..._checkparam import Validator as validator
  28. from ...common import dtype as mstype
  29. from ...common.parameter import Parameter
  30. from ...common.tensor import Tensor
  31. class _ScatterOp(PrimitiveWithInfer):
  32. """
  33. Defines Scatter operators
  34. """
  35. __mindspore_signature__ = (
  36. sig.make_sig('x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
  37. sig.make_sig('indices', dtype=sig.sig_dtype.T1),
  38. sig.make_sig('updates', dtype=sig.sig_dtype.T)
  39. )
  40. def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name):
  41. if updates_shape and updates_shape != indices_shape + x_shape[1:]:
  42. raise ValueError(f"For '{prim_name}', "
  43. f"updates_shape = indices_shape + x_shape[1:], but got x_shape: {x_shape}, "
  44. f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.")
  45. @prim_attr_register
  46. def __init__(self, use_locking=False):
  47. """Initialize _ScatterOp"""
  48. validator.check_value_type('use_locking', use_locking, [bool], self.name)
  49. self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y'])
  50. def infer_shape(self, x_shape, indices_shape, updates_shape):
  51. self._check_scatter_shape(x_shape, indices_shape, updates_shape, self.name)
  52. return x_shape
  53. def infer_dtype(self, x_dtype, indices_dtype, updates_dtype):
  54. validator.check_tensor_type_same({'indices': indices_dtype}, [mstype.int32], self.name)
  55. args = {"x": x_dtype, "updates": updates_dtype}
  56. validator.check_tensor_type_same(args, mstype.number_type, self.name)
  57. return x_dtype
  58. class _ScatterNdOp(_ScatterOp):
  59. """
  60. Defines _ScatterNd operators
  61. """
  62. def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name):
  63. validator.check('the dimension of x', len(x_shape),
  64. 'the dimension of indices', indices_shape[-1], Rel.GE)
  65. if indices_shape[:-1] + x_shape[indices_shape[-1]:] != updates_shape:
  66. raise ValueError(f"For '{prim_name}', updates_shape = "
  67. f"indices_shape[:-1] + x_shape[indices_shape[-1]:], but got x_shape: {x_shape}, "
  68. f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.")
  69. def _check_infer_attr_reduce(axis, keep_dims, prim_name):
  70. validator.check_value_type('keep_dims', keep_dims, [bool], prim_name)
  71. validator.check_value_type('axis', axis, [int, tuple], prim_name)
  72. if isinstance(axis, tuple):
  73. for index, value in enumerate(axis):
  74. validator.check_value_type('axis[%d]' % index, value, [int], prim_name)
  75. class ExpandDims(PrimitiveWithInfer):
  76. """
  77. Adds an additional dimension at the given axis.
  78. Note:
  79. If the specified axis is a negative number, the index is counted
  80. backward from the end and starts at 1.
  81. Raises:
  82. ValueError: If axis is not an integer or not in the valid range.
  83. Inputs:
  84. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  85. - **axis** (int) - Specifies the dimension index at which to expand
  86. the shape of `input_x`. The value of axis must be in the range
  87. `[-input_x.dim()-1, input_x.dim()]`. Only constant value is allowed.
  88. Outputs:
  89. Tensor, the shape of tensor is :math:`(1, x_1, x_2, ..., x_R)` if the
  90. value of `axis` is 0.
  91. Examples:
  92. >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  93. >>> expand_dims = P.ExpandDims()
  94. >>> output = expand_dims(input_tensor, 0)
  95. [[[2.0, 2.0],
  96. [2.0, 2.0]]]
  97. """
  98. @prim_attr_register
  99. def __init__(self):
  100. """Initialize ExpandDims"""
  101. self.init_prim_io_names(inputs=['x', 'axis'], outputs=['output'])
  102. def __infer__(self, x, axis):
  103. validator.check_subclass("input_x", x['dtype'], mstype.tensor, self.name)
  104. x_shape = list(x['shape'])
  105. axis_v = axis['value']
  106. rank = len(x_shape)
  107. validator.check_int_range('axis', axis_v, -rank - 1, rank, Rel.INC_BOTH, self.name)
  108. value = None
  109. if x['value'] is not None:
  110. value = x['value'].asnumpy()
  111. value = np.expand_dims(value, axis_v)
  112. value = Tensor(value)
  113. if axis_v < 0:
  114. axis_v = rank + 1 + axis_v
  115. x_shape.insert(axis_v, 1)
  116. out = {'shape': x_shape,
  117. 'dtype': x['dtype'],
  118. 'value': value}
  119. if 'min_shape' in x and 'max_shape' in x:
  120. out['min_shape'] = x['min_shape']
  121. out['min_shape'].insert(axis_v, 1)
  122. out['max_shape'] = x['max_shape']
  123. out['max_shape'].insert(axis_v, 1)
  124. return out
  125. class DType(PrimitiveWithInfer):
  126. """
  127. Returns the data type of input tensor as mindspore.dtype.
  128. Inputs:
  129. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  130. Outputs:
  131. mindspore.dtype, the data type of a tensor.
  132. Examples:
  133. >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  134. >>> type = P.DType()(input_tensor)
  135. """
  136. @prim_attr_register
  137. def __init__(self):
  138. """Initialize DType"""
  139. def __infer__(self, x):
  140. validator.check_subclass("input_x", x['dtype'], mstype.tensor, self.name)
  141. out = {'shape': (),
  142. 'dtype': mstype.type_type,
  143. 'value': x['dtype'].element_type()}
  144. return out
  145. class SameTypeShape(PrimitiveWithInfer):
  146. """
  147. Checks whether data type and shape of two tensors are the same.
  148. Raises:
  149. TypeError: If the data types of two tensors are not the same.
  150. ValueError: If the shapes of two tensors are not the same.
  151. Inputs:
  152. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  153. - **input_y** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_S)`.
  154. Outputs:
  155. Tensor, the shape of tensor is :math:`(x_1, x_2, ..., x_R)`,
  156. if data type and shape of `input_x` and `input_y` are the same.
  157. Examples:
  158. >>> input_x = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  159. >>> input_y = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  160. >>> out = P.SameTypeShape()(input_x, input_y)
  161. """
  162. @prim_attr_register
  163. def __init__(self):
  164. """Initialize Same"""
  165. def __call__(self, x, y):
  166. """run in PyNative mode"""
  167. validator.check_value_type('x', x, Tensor, self.name)
  168. validator.check_value_type('y', y, Tensor, self.name)
  169. validator.check('x dtype', x.dtype, 'y dtype', y.dtype, Rel.EQ, self.name, TypeError)
  170. validator.check('x shape', x.shape, 'y shape', y.shape, Rel.EQ, self.name)
  171. return x
  172. def __infer__(self, x, y):
  173. validator.check_subclass('x', x['dtype'], mstype.tensor, self.name)
  174. validator.check_subclass('y', y['dtype'], mstype.tensor, self.name)
  175. validator.check('x dtype', x['dtype'], 'y dtype', y['dtype'], Rel.EQ, self.name, TypeError)
  176. validator.check('x shape', x['shape'], 'y shape', y['shape'], Rel.EQ, self.name)
  177. return x
  178. class Cast(PrimitiveWithInfer):
  179. """
  180. Returns a tensor with the new specified data type.
  181. Inputs:
  182. - **input_x** (Union[Tensor, Number]) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  183. The tensor to be cast.
  184. - **type** (dtype.Number) - The valid data type of the output tensor. Only constant value is allowed.
  185. Outputs:
  186. Tensor, the shape of tensor is the same as `input_x`, :math:`(x_1, x_2, ..., x_R)`.
  187. Examples:
  188. >>> input_np = np.random.randn(2, 3, 4, 5).astype(np.float32)
  189. >>> input_x = Tensor(input_np)
  190. >>> type_dst = mindspore.float16
  191. >>> cast = P.Cast()
  192. >>> result = cast(input_x, type_dst)
  193. """
  194. @prim_attr_register
  195. def __init__(self):
  196. # if primitive need setattr in __infer__ need add this flag
  197. """Initialize Cast"""
  198. self.init_prim_io_names(inputs=['x', 'dst_type'], outputs=['output'])
  199. def check_elim(self, x, dtype):
  200. if isinstance(x, (Tensor, numbers.Number, Parameter)):
  201. if isinstance(x, Tensor) and x.dtype == dtype:
  202. return (True, x)
  203. if isinstance(x, numbers.Number):
  204. return (True, Tensor(x, dtype=dtype))
  205. if isinstance(x, Parameter):
  206. data = x.data
  207. if data.dtype == dtype:
  208. return (True, x)
  209. return (False, None)
  210. def __infer__(self, x, t):
  211. src_type = x['dtype']
  212. dst_type = t['value']
  213. validator.check_subclass("input_x", src_type, [mstype.tensor, mstype.number], self.name)
  214. validator.check_subclass("type", dst_type, mstype.number, self.name)
  215. if isinstance(src_type, type(mstype.tensor)):
  216. src_type = x['dtype'].element_type()
  217. if isinstance(dst_type, type(mstype.tensor)):
  218. dst_type = dst_type.element_type()
  219. self.add_prim_attr('DstT', dst_type)
  220. self.add_prim_attr('SrcT', src_type)
  221. value = None
  222. if x['value'] is not None:
  223. np_dst_type = mstype.dtype_to_nptype(dst_type)
  224. if isinstance(x['value'], (int, float)):
  225. value = Tensor(np.array(x['value']).astype(np_dst_type))
  226. else:
  227. value = Tensor(x['value'].asnumpy().astype(np_dst_type))
  228. out = {'shape': x['shape'],
  229. 'dtype': mstype.tensor_type(t['value']),
  230. 'value': value}
  231. if 'min_shape' in x and 'max_shape' in x:
  232. out['min_shape'] = x['min_shape']
  233. out['max_shape'] = x['max_shape']
  234. return out
  235. class IsSubClass(PrimitiveWithInfer):
  236. """
  237. Checks whether one type is subtraction class of another type.
  238. Inputs:
  239. - **sub_type** (mindspore.dtype) - The type to be checked. Only constant value is allowed.
  240. - **type_** (mindspore.dtype) - The target type. Only constant value is allowed.
  241. Outputs:
  242. bool, the check result.
  243. Examples:
  244. >>> result = P.IsSubClass()(mindspore.int32, mindspore.intc)
  245. True
  246. """
  247. @prim_attr_register
  248. def __init__(self):
  249. pass
  250. def __infer__(self, sub_type, type_):
  251. sub_type_t = sub_type['value']
  252. type_v = type_['value']
  253. validator.check_value_type("sub_type", sub_type_t, [mstype.Type], self.name)
  254. validator.check_value_type("type_", type_v, [mstype.Type], self.name)
  255. value = mstype.issubclass_(sub_type_t, type_v)
  256. out = {'shape': (),
  257. 'dtype': mstype.type_type,
  258. 'value': value}
  259. return out
  260. class IsInstance(PrimitiveWithInfer):
  261. """
  262. Checks whether an object is an instance of a target type.
  263. Inputs:
  264. - **inst** (Any Object) - The instance to be checked. Only constant value is allowed.
  265. - **type_** (mindspore.dtype) - The target type. Only constant value is allowed.
  266. Outputs:
  267. bool, the check result.
  268. Examples:
  269. >>> a = 1
  270. >>> result = P.IsInstance()(a, mindspore.int32)
  271. True
  272. """
  273. @prim_attr_register
  274. def __init__(self):
  275. pass
  276. def __infer__(self, inst, type_):
  277. sub_type_t = inst['dtype']
  278. type_v = type_['value']
  279. validator.check_value_type("type_", type_v, [mstype.Type], self.name)
  280. if type_v == mstype.list_:
  281. value = isinstance(sub_type_t, list)
  282. elif type_v == mstype.tuple_:
  283. value = isinstance(sub_type_t, tuple)
  284. else:
  285. value = mstype.issubclass_(sub_type_t, type_v)
  286. out = {'shape': (),
  287. 'dtype': mstype.type_type,
  288. 'value': value}
  289. return out
  290. class Reshape(PrimitiveWithInfer):
  291. """
  292. Reshapes input tensor with the same values based on a given shape tuple.
  293. Raises:
  294. ValueError: Given a shape tuple, if it has several -1; or if the product
  295. of its elements is less than or equal to 0 or cannot be divided by the product
  296. of the input tensor shape; or if it does not match the input's array size.
  297. Inputs:
  298. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  299. - **input_shape** (tuple[int]) - The input tuple is constructed by multiple
  300. integers, i.e., :math:`(y_1, y_2, ..., y_S)`. Only constant value is allowed.
  301. Outputs:
  302. Tensor, the shape of tensor is :math:`(y_1, y_2, ..., y_S)`.
  303. Examples:
  304. >>> input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  305. >>> reshape = P.Reshape()
  306. >>> output = reshape(input_tensor, (3, 2))
  307. """
  308. @prim_attr_register
  309. def __init__(self):
  310. """Initialize Reshape"""
  311. self.init_prim_io_names(inputs=['tensor', 'shape'], outputs=['output'])
  312. def __infer__(self, x, shape):
  313. shape_v = shape['value']
  314. x_shp = x['shape']
  315. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  316. validator.check_value_type("shape", shape_v, [tuple], self.name)
  317. shape_v = list(shape_v)
  318. neg_index = -1
  319. dim_prod = 1
  320. for i, shp_i in enumerate(shape_v):
  321. validator.check_value_type("shape[%d]" % i, shp_i, [int], self.name)
  322. if shp_i == -1:
  323. if neg_index != -1:
  324. raise ValueError(f'The shape can only has one -1 at most, but {shape_v}.')
  325. neg_index = i
  326. else:
  327. dim_prod *= shp_i
  328. arr_prod = np.prod(x_shp)
  329. if dim_prod <= 0 or arr_prod % dim_prod != 0:
  330. raise ValueError(f'For \'{self.name}\' input_x\'s shape is {x_shp}, input_shape\'s value is {shape_v}.'
  331. f'The product of input_x\'s shape should > 0, '
  332. f'and can be divided by product of input_shape, '
  333. f'but product of input_x\'s shape is {arr_prod}, product of input_shape is {dim_prod}.')
  334. if neg_index != -1:
  335. shape_v[neg_index] = int(arr_prod / dim_prod)
  336. dim_prod *= shape_v[neg_index]
  337. if dim_prod != arr_prod:
  338. raise ValueError(f'For \'{self.name}\' input_x\'s shape is {x_shp}, input_shape\'s value is {shape_v}.'
  339. f'The product of input_x\'s shape should be equal to product of input_shape, '
  340. f'but product of input_x\'s shape is {arr_prod}, product of input_shape is {dim_prod}.')
  341. value = None
  342. if x['value'] is not None:
  343. value = Tensor(x['value'].asnumpy().reshape(shape_v))
  344. out = {'shape': tuple(shape_v),
  345. 'dtype': x['dtype'],
  346. 'value': value}
  347. return out
  348. class Shape(PrimitiveWithInfer):
  349. """
  350. Returns the shape of input tensor.
  351. Inputs:
  352. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  353. Outputs:
  354. tuple[int], the output tuple is constructed by multiple integers,
  355. :math:`(x_1, x_2, ..., x_R)`.
  356. Examples:
  357. >>> input_tensor = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32)
  358. >>> shape = P.Shape()
  359. >>> output = shape(input_tensor)
  360. (3, 2, 1)
  361. """
  362. @prim_attr_register
  363. def __init__(self):
  364. """Initialize Shape"""
  365. def __infer__(self, x):
  366. validator.check_subclass("input_x", x['dtype'], mstype.tensor, self.name)
  367. out = {'shape': (),
  368. 'dtype': mstype.tuple_,
  369. 'value': tuple(x['shape'])}
  370. return out
  371. class DynamicShape(Primitive):
  372. """
  373. Returns the shape of input tensor.
  374. Inputs:
  375. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  376. Outputs:
  377. Tensor[int], 1-dim Tensor of type int32
  378. Examples:
  379. >>> input_tensor = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32)
  380. >>> shape = P.DynamicShape()
  381. >>> output = shape(input_tensor)
  382. """
  383. @prim_attr_register
  384. def __init__(self):
  385. """init Shape"""
  386. self.init_prim_io_names(inputs=['tensor'], outputs=['output'])
  387. self.add_prim_attr('is_dynamic_shape', True)
  388. self.add_prim_attr("dynamic_shape_depends", [0])
  389. class Squeeze(PrimitiveWithInfer):
  390. """
  391. Returns a tensor with the same type but dimensions of 1 are removed based on `axis`.
  392. Note:
  393. The dimension index starts at 0 and must be in the range `[-input.dim(), input.dim())`.
  394. Raises:
  395. ValueError: If the corresponding dimension of the specified axis does not equal to 1.
  396. Args:
  397. axis (Union[int, tuple(int)]): Specifies the dimension indexes of shape to be removed, which will remove
  398. all the dimensions that are equal to 1. If specified, it must be int32 or int64.
  399. Default: (), an empty tuple.
  400. Inputs:
  401. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  402. Outputs:
  403. Tensor, the shape of tensor is :math:`(x_1, x_2, ..., x_S)`.
  404. Examples:
  405. >>> input_tensor = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32)
  406. >>> squeeze = P.Squeeze(2)
  407. >>> output = squeeze(input_tensor)
  408. [[1. 1.]
  409. [1. 1.]
  410. [1. 1.]]
  411. """
  412. @prim_attr_register
  413. def __init__(self, axis=()):
  414. """Initialize Squeeze"""
  415. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  416. validator.check_value_type('axis', axis, [int, tuple], self.name)
  417. if isinstance(axis, tuple):
  418. for idx, item in enumerate(axis):
  419. validator.check_value_type("axis[%d]" % idx, item, [int], self.name)
  420. else:
  421. self.axis = (axis,)
  422. self.add_prim_attr("axis", (axis,))
  423. def infer_shape(self, x_shape):
  424. axis = self.axis
  425. x_shape = list(x_shape)
  426. ndim = len(x_shape)
  427. if not axis:
  428. ret = [d for d in x_shape if d != 1]
  429. else:
  430. for a in axis:
  431. validator.check_int_range('axis or its elements', a, -ndim, ndim - 1, Rel.INC_BOTH, self.name)
  432. if x_shape[a] != 1:
  433. raise ValueError('Cannot select an axis to squeeze out which has size not equal to one.')
  434. ret = [x_shape[i] for i in range(ndim) if not (i in axis or (i - ndim) in axis)]
  435. return ret
  436. def infer_dtype(self, x_dtype):
  437. validator.check_subclass("x", x_dtype, mstype.tensor, self.name)
  438. return x_dtype
  439. class Transpose(PrimitiveWithInfer):
  440. """
  441. Permutes the dimensions of input tensor according to input permutation.
  442. Inputs:
  443. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  444. - **input_perm** (tuple[int]) - The permutation to be converted. The input tuple is constructed by multiple
  445. indexes. The length of `input_perm` and the shape of `input_x` must be the same. Only constant value is
  446. allowed.
  447. Outputs:
  448. Tensor, the type of output tensor is the same as `input_x` and the shape of output tensor is decided by the
  449. shape of `input_x` and the value of `input_perm`.
  450. Examples:
  451. >>> input_tensor = Tensor(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]), mindspore.float32)
  452. >>> perm = (0, 2, 1)
  453. >>> transpose = P.Transpose()
  454. >>> output = transpose(input_tensor, perm)
  455. """
  456. @prim_attr_register
  457. def __init__(self):
  458. """Initialize Transpose"""
  459. self.init_prim_io_names(inputs=['x', 'perm'], outputs=['output'])
  460. def __infer__(self, x, perm):
  461. x_shape = x['shape']
  462. p_value = perm['value']
  463. x_type = x['dtype']
  464. validator.check_value_type("p_value", p_value, [tuple], self.name)
  465. validator.check_subclass("x_type", x_type, mstype.tensor, self.name)
  466. if len(x_shape) != len(p_value):
  467. raise ValueError('The dimension of x and perm must be equal.')
  468. tmp = list(p_value)
  469. for i, dim in enumerate(p_value):
  470. validator.check_integer("perm[%d]" % i, dim, 0, Rel.GE, self.name)
  471. validator.check_integer("perm[%d]" % i, dim, len(p_value), Rel.LT, self.name)
  472. tmp.remove(dim)
  473. if dim in tmp:
  474. raise ValueError('The value of perm is wrong.')
  475. out_shapes = []
  476. for i in p_value:
  477. out_shapes.append(x_shape[i])
  478. out = {'shape': tuple(out_shapes),
  479. 'dtype': x['dtype'],
  480. 'value': None}
  481. return out
  482. class Unique(Primitive):
  483. """
  484. Returns the unique elements of input tensor and also return a tensor containing the index of each value of input
  485. tensor corresponding to the output unique tensor.
  486. Inputs:
  487. - **x** (Tensor) - The input tensor.
  488. Outputs:
  489. Tuple, containing Tensor objects `(y, idx)`, `y` is a tensor has the same type as `x`, `idx` is a tensor
  490. containing indices of elements in the input coressponding to the output tensor.
  491. Examples:
  492. >>> x = Tensor(np.array([1, 2, 5, 2]), mindspore.int32)
  493. >>> out = P.Unique()(x)
  494. (Tensor([1, 2, 5], mindspore.int32), Tensor([0, 1, 2, 1], mindspore.int32))
  495. """
  496. @prim_attr_register
  497. def __init__(self):
  498. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  499. class GatherV2(PrimitiveWithCheck):
  500. """
  501. Returns a slice of input tensor based on the specified indices and axis.
  502. Inputs:
  503. - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  504. The original Tensor.
  505. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`.
  506. Specifies the indices of elements of the original Tensor. Must be in the range
  507. `[0, input_param.shape[axis])`.
  508. - **axis** (int) - Specifies the dimension index to gather indices.
  509. Outputs:
  510. Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`.
  511. Examples:
  512. >>> input_params = Tensor(np.array([[1, 2, 7, 42], [3, 4, 54, 22], [2, 2, 55, 3]]), mindspore.float32)
  513. >>> input_indices = Tensor(np.array([1, 2]), mindspore.int32)
  514. >>> axis = 1
  515. >>> out = P.GatherV2()(input_params, input_indices, axis)
  516. [[2.0, 7.0],
  517. [4.0, 54.0],
  518. [2.0, 55.0]]
  519. """
  520. @prim_attr_register
  521. def __init__(self):
  522. """Initialize index_select"""
  523. self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output'])
  524. self.add_prim_attr("dynamic_shape_depends", [2,])
  525. def __check__(self, params, indices, axis):
  526. validator.check_subclass("params", params['dtype'], mstype.tensor, self.name)
  527. validator.check_tensor_type_same({"indices": indices['dtype']}, mstype.int_type, self.name)
  528. validator.check_subclass("axis", axis['dtype'], mstype.int_, self.name)
  529. axis_v = axis['value']
  530. params_shp = params['shape']
  531. rank = len(params_shp)
  532. validator.check_int_range("axis", axis_v, -rank, rank, Rel.INC_LEFT, self.name)
  533. if axis_v < 0:
  534. axis_v += rank
  535. out_shape = params_shp[:axis_v] + indices['shape'] + params_shp[axis_v + 1:]
  536. out = {'shape': out_shape,
  537. 'dtype': params['dtype'],
  538. 'value': None}
  539. if 'min_shape' in indices and 'max_shape' in indices:
  540. out['min_shape'] = params_shp[:axis_v] + indices['min_shape'] + params_shp[axis_v + 1:]
  541. out['max_shape'] = params_shp[:axis_v] + indices['max_shape'] + params_shp[axis_v + 1:]
  542. return out
  543. class SparseGatherV2(GatherV2):
  544. """
  545. Returns a slice of input tensor based on the specified indices and axis.
  546. Inputs:
  547. - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  548. The original Tensor.
  549. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`.
  550. Specifies the indices of elements of the original Tensor, must be in the range
  551. `[0, input_param.shape[axis])`.
  552. - **axis** (int) - Specifies the dimension index to gather indices.
  553. Outputs:
  554. Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`.
  555. Examples:
  556. >>> input_params = Tensor(np.array([[1, 2, 7, 42], [3, 4, 54, 22], [2, 2, 55, 3]]), mindspore.float32)
  557. >>> input_indices = Tensor(np.array([1, 2]), mindspore.int32)
  558. >>> axis = 1
  559. >>> out = P.SparseGatherV2()(input_params, input_indices, axis)
  560. """
  561. class Padding(PrimitiveWithInfer):
  562. """
  563. Extends the last dimension of input tensor from 1 to pad_dim_size, by filling with 0.
  564. Args:
  565. pad_dim_size (int): The value of the last dimension of x to be extended, which must be positive.
  566. Inputs:
  567. - **x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The rank of x must be at least 2.
  568. The last dimension of x must be 1.
  569. Outputs:
  570. Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`.
  571. Examples:
  572. >>> x = Tensor(np.array([[8], [10]]), mindspore.float32)
  573. >>> pad_dim_size = 4
  574. >>> out = P.Padding(pad_dim_size)(x)
  575. [[8, 0, 0, 0], [10, 0, 0, 0]]
  576. """
  577. @prim_attr_register
  578. def __init__(self, pad_dim_size=8):
  579. """Initialize padding"""
  580. validator.check_value_type("pad_dim_size", pad_dim_size, [int], self.name)
  581. validator.check_positive_int(pad_dim_size, "pad_dim_size", self.name)
  582. self.pad_dim_size = pad_dim_size
  583. def __infer__(self, x):
  584. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  585. x_shape = list(x['shape'])
  586. validator.check_integer("rank of x", len(x_shape), 1, Rel.GT, self.name)
  587. validator.check_integer("last dim of x", x_shape[-1], 1, Rel.EQ, self.name)
  588. out_shape = x_shape
  589. out_shape[-1] = self.pad_dim_size
  590. out = {'shape': out_shape,
  591. 'dtype': x['dtype'],
  592. 'value': None}
  593. return out
  594. class Split(PrimitiveWithInfer):
  595. """
  596. Splits input tensor into output_num of tensors along the given axis and output numbers.
  597. Args:
  598. axis (int): Index of the split position. Default: 0.
  599. output_num (int): The number of output tensors. Default: 1.
  600. Raises:
  601. ValueError: If `axis` is out of the range [-len(`input_x.shape`), len(`input_x.shape`)),
  602. or if the `output_num` is less than or equal to 0, or if the
  603. dimension which to split cannot be evenly divided by `output_num`.
  604. Inputs:
  605. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  606. Outputs:
  607. tuple[Tensor], the shape of each output tensor is the same, which is
  608. :math:`(y_1, y_2, ..., y_S)`.
  609. Examples:
  610. >>> split = P.Split(1, 2)
  611. >>> x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]]))
  612. >>> output = split(x)
  613. ([[1, 1],
  614. [2, 2]],
  615. [[1, 1],
  616. [2, 2]])
  617. """
  618. @prim_attr_register
  619. def __init__(self, axis=0, output_num=1):
  620. """Initialize Split"""
  621. validator.check_value_type("axis", axis, [int], self.name)
  622. validator.check_value_type("output_num", output_num, [int], self.name)
  623. self.axis = axis
  624. self.output_num = output_num
  625. def __infer__(self, x):
  626. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  627. x_shape = list(x['shape'])
  628. dim = len(x_shape)
  629. validator.check_int_range('axis value', self.axis, -dim, dim, Rel.INC_LEFT, self.name)
  630. validator.check_positive_int(self.output_num, "output_num", self.name)
  631. output_valid_check = x_shape[self.axis] % self.output_num
  632. if output_valid_check != 0:
  633. raise ValueError(f"x_shape[{self.axis}] {x_shape[self.axis]} must be divide exactly by"
  634. f" output_num {self.output_num}")
  635. x_shape[self.axis] = int(x_shape[self.axis] / self.output_num)
  636. out_shapes = []
  637. out_dtypes = []
  638. for _ in range(self.output_num):
  639. out_shapes.append(tuple(x_shape))
  640. out_dtypes.append(x['dtype'])
  641. out_shapes = tuple(out_shapes)
  642. out_dtypes = tuple(out_dtypes)
  643. out = {'shape': out_shapes,
  644. 'dtype': out_dtypes,
  645. 'value': None}
  646. return out
  647. class Rank(PrimitiveWithInfer):
  648. """
  649. Returns the rank of a tensor.
  650. Returns a 0-D int32 Tensor representing the rank of input; the rank of a tensor
  651. is the number of indices required to uniquely select each element of the tensor.
  652. Inputs:
  653. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  654. Outputs:
  655. Tensor. 0-D int32 Tensor representing the rank of input, i.e., :math:`R`.
  656. Examples:
  657. >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  658. >>> rank = P.Rank()
  659. >>> rank(input_tensor)
  660. """
  661. @prim_attr_register
  662. def __init__(self):
  663. """Initialize Rank"""
  664. def __infer__(self, x):
  665. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  666. out = {'shape': None,
  667. 'dtype': None,
  668. 'value': len(x['shape'])}
  669. return out
  670. class TruncatedNormal(PrimitiveWithInfer):
  671. """
  672. Returns a tensor of the specified shape filled with truncated normal values.
  673. The generated values follow a normal distribution.
  674. Args:
  675. seed (int): A integer number used to create random seed. Default: 0.
  676. dtype (:class:`mindspore.dtype`): Data type. Default: mindspore.float32.
  677. Inputs:
  678. - **shape** (tuple[int]) - The shape of the output tensor, is a tuple of positive integer.
  679. Outputs:
  680. Tensor, the data type of output tensor is the same as attribute `dtype`.
  681. Examples:
  682. >>> shape = (1, 2, 3)
  683. >>> truncated_normal = P.TruncatedNormal()
  684. >>> output = truncated_normal(shape)
  685. """
  686. @prim_attr_register
  687. def __init__(self, seed=0, dtype=mstype.float32):
  688. """Initialize TruncatedNormal"""
  689. validator.check_value_type('seed', seed, [int], self.name)
  690. validator.check_type_same({'dtype': dtype}, mstype.number_type, self.name)
  691. def __infer__(self, shape):
  692. shape_value = shape['value']
  693. validator.check_value_type("shape", shape_value, [tuple], self.name)
  694. for i, value in enumerate(shape_value):
  695. validator.check_positive_int(value, f'{i}th value of shape', self.name)
  696. out = {'shape': shape_value,
  697. 'dtype': mstype.tensor_type(self.dtype),
  698. 'value': None}
  699. return out
  700. class Size(PrimitiveWithInfer):
  701. r"""
  702. Returns the elements count size of a tensor.
  703. Returns an int scalar representing the elements size of input, the total number of elements in the tensor.
  704. Inputs:
  705. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  706. Outputs:
  707. int, a scalar representing the elements size of `input_x`, tensor is the number of elements
  708. in a tensor, :math:`size=x_1*x_2*...x_R`.
  709. Examples:
  710. >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  711. >>> size = P.Size()
  712. >>> output = size(input_tensor)
  713. """
  714. @prim_attr_register
  715. def __init__(self):
  716. """Initialize Size"""
  717. def __infer__(self, x):
  718. size = 1
  719. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  720. shp = x['shape']
  721. if not shp:
  722. size = 0
  723. else:
  724. size = functools.reduce(lambda x, y: x * y, x['shape'])
  725. out = {'shape': None,
  726. 'dtype': mstype.int32,
  727. 'value': size}
  728. return out
  729. class Fill(PrimitiveWithInfer):
  730. """
  731. Creates a tensor filled with a scalar value.
  732. Creates a tensor with shape described by the first argument and fills it with values in the second argument.
  733. Inputs:
  734. - **type** (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed.
  735. - **shape** (tuple) - The specified shape of output tensor. Only constant value is allowed.
  736. - **value** (scalar) - Value to fill the returned tensor. Only constant value is allowed.
  737. Outputs:
  738. Tensor, has the same type and shape as input value.
  739. Examples:
  740. >>> fill = P.Fill()
  741. >>> fill(mindspore.float32, (2, 2), 1)
  742. [[1.0, 1.0],
  743. [1.0, 1.0]]
  744. """
  745. @prim_attr_register
  746. def __init__(self):
  747. """Initialize Fill"""
  748. def __infer__(self, dtype, dims, x):
  749. validator.check_value_type("shape", dims['value'], [tuple], self.name)
  750. validator.check_value_type("value", x['value'], [numbers.Number, bool], self.name)
  751. for i, item in enumerate(dims['value']):
  752. validator.check_positive_int(item, f'dims[{i}]', self.name)
  753. valid_types = [mstype.bool_, mstype.int8, mstype.int16, mstype.int32, mstype.int64,
  754. mstype.uint8, mstype.uint32, mstype.uint64,
  755. mstype.float16, mstype.float32, mstype.float64]
  756. validator.check_type_same({"value": dtype['value']}, valid_types, self.name)
  757. x_nptype = mstype.dtype_to_nptype(dtype['value'])
  758. ret = np.full(dims['value'], x['value'], x_nptype)
  759. out = {
  760. 'value': Tensor(ret),
  761. 'shape': dims['value'],
  762. 'dtype': x['dtype'],
  763. }
  764. return out
  765. class OnesLike(PrimitiveWithInfer):
  766. """
  767. Creates a new tensor. The values of all elements are 1.
  768. Returns a tensor of ones with the same shape and type as the input.
  769. Inputs:
  770. - **input_x** (Tensor) - Input tensor.
  771. Outputs:
  772. Tensor, has the same shape and type as `input_x` but filled with ones.
  773. Examples:
  774. >>> oneslike = P.OnesLike()
  775. >>> x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
  776. >>> output = oneslike(x)
  777. [[1, 1],
  778. [1, 1]]
  779. """
  780. @prim_attr_register
  781. def __init__(self):
  782. """Initialize OnesLike"""
  783. def infer_shape(self, x_shape):
  784. return x_shape
  785. def infer_dtype(self, x_dtype):
  786. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type + (mstype.bool_,), self.name)
  787. return x_dtype
  788. class ZerosLike(PrimitiveWithInfer):
  789. """
  790. Creates a new tensor. All elements value are 0.
  791. Returns a tensor of zeros with the same shape and data type as the input tensor.
  792. Inputs:
  793. - **input_x** (Tensor) - Input tensor.
  794. Outputs:
  795. Tensor, has the same shape and data type as `input_x` but filled with zeros.
  796. Examples:
  797. >>> zeroslike = P.ZerosLike()
  798. >>> x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.float32))
  799. >>> output = zeroslike(x)
  800. [[0.0, 0.0],
  801. [0.0, 0.0]]
  802. """
  803. @prim_attr_register
  804. def __init__(self):
  805. """Initialize ZerosLike"""
  806. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  807. def infer_shape(self, x_shape):
  808. return x_shape
  809. def infer_dtype(self, x_dtype):
  810. validator.check_tensor_type_same({'x': x_dtype}, mstype.number_type + (mstype.bool_,), self.name)
  811. return x_dtype
  812. class TupleToArray(PrimitiveWithInfer):
  813. """
  814. Converts a tuple to a tensor.
  815. If the type of the first number in the tuple is integer, the data type of the output tensor is int.
  816. Otherwise, the data type of the output tensor is float.
  817. Inputs:
  818. - **input_x** (tuple) - A tuple of numbers. These numbers have the same type. Only constant value is allowed.
  819. Outputs:
  820. Tensor, if the input tuple contains `N` numbers, then the shape of the output tensor is (N,).
  821. Examples:
  822. >>> type = P.TupleToArray()((1,2,3))
  823. """
  824. @prim_attr_register
  825. def __init__(self):
  826. """Initialize TupleToArray"""
  827. def infer_value(self, x):
  828. validator.check_value_type("x", x, [tuple], self.name)
  829. validator.check("size of x", len(x), '', 0, Rel.GT, self.name)
  830. dtype = type(x[0])
  831. for i, item in enumerate(x):
  832. validator.check_value_type(f"x[{i}]", item, [numbers.Number], self.name)
  833. if not all(isinstance(item, dtype) for item in x):
  834. raise TypeError("For \'{self.name}\' all elements of input x must be have same type.")
  835. if isinstance(x[0], int):
  836. ret = np.array(x, np.int32)
  837. else:
  838. ret = np.array(x, np.float32)
  839. return Tensor(ret)
  840. def __call__(self, x):
  841. args = list()
  842. if isinstance(x, range):
  843. args.append(tuple(x))
  844. else:
  845. args.append(x)
  846. return _run_op(self, self.name, args)
  847. class ScalarToArray(PrimitiveWithInfer):
  848. """
  849. Converts a scalar to a `Tensor`.
  850. Inputs:
  851. - **input_x** (Union[int, float]) - The input is a scalar. Only constant value is allowed.
  852. Outputs:
  853. Tensor. 0-D Tensor and the content is the input.
  854. Examples:
  855. >>> op = P.ScalarToArray()
  856. >>> data = 1.0
  857. >>> output = op(data)
  858. """
  859. @prim_attr_register
  860. def __init__(self):
  861. pass
  862. def infer_value(self, x):
  863. validator.check_value_type("x", x, [int, float], self.name)
  864. if isinstance(x, int):
  865. ret = np.array(x, np.int32)
  866. else:
  867. ret = np.array(x, np.float32)
  868. return Tensor(ret)
  869. class ScalarToTensor(PrimitiveWithInfer):
  870. """
  871. Converts a scalar to a `Tensor`, and convert data type to specified type.
  872. Inputs:
  873. - **input_x** (Union[int, float]) - The input is a scalar. Only constant value is allowed.
  874. - **dtype** (mindspore.dtype) - The target data type. Default: mindspore.float32. Only
  875. constant value is allowed.
  876. Outputs:
  877. Tensor. 0-D Tensor and the content is the input.
  878. Examples:
  879. >>> op = P.ScalarToTensor()
  880. >>> data = 1
  881. >>> output = op(data, mindspore.float32)
  882. """
  883. @prim_attr_register
  884. def __init__(self):
  885. pass
  886. def infer_value(self, x, dtype=mstype.float32):
  887. validator.check_value_type("x", x, [int, float], self.name)
  888. validator.check_subclass("dtype", dtype, mstype.number, self.name)
  889. data_type = mstype.dtype_to_nptype(dtype)
  890. return Tensor(np.array(x, data_type))
  891. class InvertPermutation(PrimitiveWithInfer):
  892. r"""
  893. Computes the inverse of an index permutation.
  894. Given a tuple input, this operation inserts a dimension of 1 at the dimension
  895. This operation calculates the inverse of the index replacement. It requires a
  896. 1-dimensional tuple x, which represents the array starting at zero,
  897. and swaps each value with its index position. In other words, for the output
  898. tuple y and the input tuple x, this operation calculates the following:
  899. :math:`y[x[i]] = i, \quad i \in [0, 1, \ldots, \text{len}(x)-1]`.
  900. Note:
  901. These values must include 0. There must be no duplicate values and the
  902. values can not be negative.
  903. Inputs:
  904. - **input_x** (Union(tuple[int], list[int]) - The input is constructed by multiple
  905. integers, i.e., :math:`(y_1, y_2, ..., y_S)` representing the indices.
  906. The values must include 0. There can be no duplicate values or negative values.
  907. Only constant value is allowed. The maximum value msut be equal to length of input_x.
  908. Outputs:
  909. tuple[int]. It has the same length as the input.
  910. Examples:
  911. >>> invert = P.InvertPermutation()
  912. >>> input_data = (3, 4, 0, 2, 1)
  913. >>> output = invert(input_data)
  914. >>> output == (2, 4, 3, 0, 1)
  915. """
  916. @prim_attr_register
  917. def __init__(self):
  918. """Initialize InvertPermutation"""
  919. self.set_const_prim(True)
  920. def __infer__(self, x):
  921. x_shp = x['shape']
  922. x_value = x['value']
  923. if x_value is None:
  924. raise ValueError(f'For \'{self.name}\' the input value must be const.')
  925. validator.check_value_type("shape", x_shp, [tuple, list], self.name)
  926. if mstype.issubclass_(x['dtype'], mstype.tensor):
  927. raise ValueError(f'For \'{self.name}\' the input value must be non-Tensor.')
  928. for shp in x_shp:
  929. if shp != []:
  930. x_rank = len(np.array(x_value, np.int64).shape)
  931. raise ValueError(f'For \'{self.name}\' the rank of input must be 1, but got {x_rank}.')
  932. for i, value in enumerate(x_value):
  933. validator.check_value_type("input[%d]" % i, value, [int], self.name)
  934. z = [x_value[i] for i in range(len(x_value))]
  935. z.sort()
  936. for i in range(1, len(z)):
  937. if z[i - 1] == z[i]:
  938. raise ValueError(f"For {self.name}, {z[i]} is duplicated in the input.")
  939. validator.check(f'value min', min(x_value), '', 0, Rel.EQ, self.name)
  940. validator.check(f'value max', max(x_value), '', len(x_value) - 1, Rel.EQ, self.name)
  941. y = [None] * len(x_value)
  942. for i, value in enumerate(x_value):
  943. validator.check_value_type("input[%d]" % i, value, [int], self.name)
  944. validator.check(f'value', z[i], f'index', i, Rel.EQ, self.name)
  945. y[value] = i
  946. z.append(value)
  947. return {'shape': x_shp,
  948. 'dtype': x['dtype'],
  949. 'value': tuple(y)}
  950. class Argmax(PrimitiveWithInfer):
  951. """
  952. Returns the indices of the max value of a tensor across the axis.
  953. If the shape of input tensor is :math:`(x_1, ..., x_N)`, the shape of the output tensor will be
  954. :math:`(x_1, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`.
  955. Args:
  956. axis (int): Axis where the Argmax operation applies to. Default: -1.
  957. output_type (:class:`mindspore.dtype`): An optional data type of `mindspore.dtype.int32`.
  958. Default: `mindspore.dtype.int32`.
  959. Inputs:
  960. - **input_x** (Tensor) - Input tensor.
  961. Outputs:
  962. Tensor, indices of the max value of input tensor across the axis.
  963. Examples:
  964. >>> input_x = Tensor(np.array([2.0, 3.1, 1.2]), mindspore.float32)
  965. >>> index = P.Argmax(output_type=mindspore.int32)(input_x)
  966. 1
  967. """
  968. @prim_attr_register
  969. def __init__(self, axis=-1, output_type=mstype.int32):
  970. """Initialize Argmax"""
  971. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  972. validator.check_value_type("axis", axis, [int], self.name)
  973. validator.check_type_same({'output': output_type}, [mstype.int32], self.name)
  974. self.axis = axis
  975. self.add_prim_attr('output_type', output_type)
  976. def infer_shape(self, x_shape):
  977. axis = self.axis
  978. if axis is None:
  979. axis = 0
  980. x_rank = len(x_shape)
  981. validator.check_int_range("axis", axis, -x_rank, x_rank, Rel.INC_LEFT, self.name)
  982. axis = axis + x_rank if axis < 0 else axis
  983. ouput_shape = [x_shape[i] for i in range(x_rank) if i != axis]
  984. return ouput_shape
  985. def infer_dtype(self, x_dtype):
  986. validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name)
  987. return mstype.tensor_type(self.output_type)
  988. class Argmin(PrimitiveWithInfer):
  989. """
  990. Returns the indices of the min value of a tensor across the axis.
  991. If the shape of input tensor is :math:`(x_1, ..., x_N)`, the shape of the output tensor is
  992. :math:`(x_1, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`.
  993. Args:
  994. axis (int): Axis where the Argmin operation applies to. Default: -1.
  995. output_type (:class:`mindspore.dtype`): An optional data type of `mindspore.dtype.int32`.
  996. Default: `mindspore.dtype.int32`.
  997. Inputs:
  998. - **input_x** (Tensor) - Input tensor.
  999. Outputs:
  1000. Tensor, indices of the min value of input tensor across the axis.
  1001. Examples:
  1002. >>> input_x = Tensor(np.array([2.0, 3.1, 1.2]), mindspore.float32)
  1003. >>> index = P.Argmin()(input_x)
  1004. >>> assert index == Tensor(2, mindspore.int64)
  1005. """
  1006. @prim_attr_register
  1007. def __init__(self, axis=-1, output_type=mstype.int32):
  1008. """Initialize Argmin"""
  1009. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  1010. validator.check_value_type("axis", axis, [int], self.name)
  1011. validator.check_type_name("output_type", output_type, [mstype.int32, mstype.int64], self.name)
  1012. self.axis = axis
  1013. self.add_prim_attr('output_type', output_type)
  1014. def infer_shape(self, x_shape):
  1015. axis = self.axis
  1016. if axis is None:
  1017. axis = 0
  1018. x_rank = len(x_shape)
  1019. validator.check_int_range("axis", axis, -x_rank, x_rank, Rel.INC_LEFT, self.name)
  1020. axis = axis + x_rank if axis < 0 else axis
  1021. ouput_shape = [x_shape[i] for i in range(x_rank) if i != axis]
  1022. return ouput_shape
  1023. def infer_dtype(self, x_dtype):
  1024. validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name)
  1025. return mstype.tensor_type(self.output_type)
  1026. class ArgMaxWithValue(PrimitiveWithInfer):
  1027. """
  1028. Calculates the maximum value with the corresponding index.
  1029. Calculates the maximum value along with the given axis for the input tensor. It returns the maximum values and
  1030. indices.
  1031. Note:
  1032. In auto_parallel and semi_auto_parallel mode, the first output index can not be used.
  1033. Args:
  1034. axis (int): The dimension to reduce. Default: 0.
  1035. keep_dims (bool): Whether to reduce dimension, if true, the output will keep same dimension with the input,
  1036. the output will reduce dimension if false. Default: False.
  1037. Inputs:
  1038. - **input_x** (Tensor) - The input tensor, can be any dimension. Set the shape of input tensor as
  1039. :math:`(x_1, x_2, ..., x_N)`.
  1040. Outputs:
  1041. tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the maximum value of the input
  1042. tensor.
  1043. - index (Tensor) - The index for the maximum value of the input tensor. If `keep_dims` is true, the shape of
  1044. output tensors is :math:`(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)`. Otherwise, the shape is
  1045. :math:`(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`.
  1046. - output_x (Tensor) - The maximum value of input tensor, with the same shape as index.
  1047. Examples:
  1048. >>> input_x = Tensor(np.random.rand(5), mindspore.float32)
  1049. >>> index, output = P.ArgMaxWithValue()(input_x)
  1050. """
  1051. @prim_attr_register
  1052. def __init__(self, axis=0, keep_dims=False):
  1053. """Initialize ArgMaxWithValue"""
  1054. self.axis = axis
  1055. self.keep_dims = keep_dims
  1056. validator.check_value_type('keep_dims', keep_dims, [bool], self.name)
  1057. validator.check_value_type('axis', axis, [int], self.name)
  1058. def infer_shape(self, x_shape):
  1059. axis = self.axis
  1060. x_rank = len(x_shape)
  1061. validator.check_int_range("axis", axis, -x_rank, x_rank, Rel.INC_LEFT, self.name)
  1062. ouput_shape = _infer_shape_reduce(x_shape, self.axis, self.keep_dims, self.name)
  1063. return ouput_shape, ouput_shape
  1064. def infer_dtype(self, x_dtype):
  1065. validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name)
  1066. return mstype.tensor_type(mstype.int32), x_dtype
  1067. class ArgMinWithValue(PrimitiveWithInfer):
  1068. """
  1069. Calculates the minimum value with corresponding index, return indices and values.
  1070. Calculates the minimum value along with the given axis for the input tensor. It returns the minimum values and
  1071. indices.
  1072. Note:
  1073. In auto_parallel and semi_auto_parallel mode, the first output index can not be used.
  1074. Args:
  1075. axis (int): The dimension to reduce. Default: 0.
  1076. keep_dims (bool): Whether to reduce dimension, if true the output will keep the same dimension as the input,
  1077. the output will reduce dimension if false. Default: False.
  1078. Inputs:
  1079. - **input_x** (Tensor) - The input tensor, can be any dimension. Set the shape of input tensor as
  1080. :math:`(x_1, x_2, ..., x_N)`.
  1081. Outputs:
  1082. tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the minimum value of the input
  1083. tensor.
  1084. - index (Tensor) - The index for the maximum value of the input tensor. If `keep_dims` is true, the shape of
  1085. output tensors is :math:`(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)`. Otherwise, the shape is
  1086. :math:`(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`.
  1087. - output_x (Tensor) - The minimum value of input tensor, with the same shape as index.
  1088. Examples:
  1089. >>> input_x = Tensor(np.random.rand(5))
  1090. >>> index, output = P.ArgMinWithValue()(input_x)
  1091. """
  1092. @prim_attr_register
  1093. def __init__(self, axis=0, keep_dims=False):
  1094. """Initialize ArgMinWithValue"""
  1095. self.axis = axis
  1096. self.keep_dims = keep_dims
  1097. validator.check_value_type('keep_dims', keep_dims, [bool], self.name)
  1098. validator.check_value_type('axis', axis, [int], self.name)
  1099. def infer_shape(self, x_shape):
  1100. axis = self.axis
  1101. x_rank = len(x_shape)
  1102. validator.check_int_range("axis", axis, -x_rank, x_rank, Rel.INC_LEFT, self.name)
  1103. ouput_shape = _infer_shape_reduce(x_shape, self.axis, self.keep_dims, self.name)
  1104. return ouput_shape, ouput_shape
  1105. def infer_dtype(self, x_dtype):
  1106. validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name)
  1107. return mstype.tensor_type(mstype.int32), x_dtype
  1108. class Tile(PrimitiveWithInfer):
  1109. r"""
  1110. Replicates a tensor with given multiples times.
  1111. Creates a new tensor by replicating input multiples times. The dimension of
  1112. output tensor is the larger of the input tensor dimension and the length of `multiples`.
  1113. Inputs:
  1114. - **input_x** (Tensor) - 1-D or higher Tensor. Set the shape of input tensor as
  1115. :math:`(x_1, x_2, ..., x_S)`.
  1116. - **multiples** (tuple[int]) - The input tuple is constructed by multiple
  1117. integers, i.e., :math:`(y_1, y_2, ..., y_S)`. The length of `multiples`
  1118. cannot be smaller than the length of the shape of `input_x`.
  1119. Only constant value is allowed.
  1120. Outputs:
  1121. Tensor, has the same data type as the `input_x`.
  1122. - If the length of `multiples` is the same as the length of shape of `input_x`,
  1123. then the shape of their corresponding positions can be multiplied, and
  1124. the shape of Outputs is :math:`(x_1*y_1, x_2*y_2, ..., x_S*y_R)`.
  1125. - If the length of `multiples` is larger than the length of shape of `input_x`,
  1126. fill in multiple 1 in the length of the shape of `input_x` until their lengths are consistent.
  1127. Such as set the shape of `input_x` as :math:`(1, ..., x_1, x_2, ..., x_S)`,
  1128. then the shape of their corresponding positions can be multiplied, and
  1129. the shape of Outputs is :math:`(1*y_1, ..., x_S*y_R)`.
  1130. Examples:
  1131. >>> tile = P.Tile()
  1132. >>> input_x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.float32)
  1133. >>> multiples = (2, 3)
  1134. >>> result = tile(input_x, multiples)
  1135. [[1. 2. 1. 2. 1. 2.]
  1136. [3. 4. 3. 4. 3. 4.]
  1137. [1. 2. 1. 2. 1. 2.]
  1138. [3. 4. 3. 4. 3. 4.]]
  1139. """
  1140. @prim_attr_register
  1141. def __init__(self):
  1142. """Initialize Tile"""
  1143. self.init_prim_io_names(inputs=['x', 'multiples'], outputs=['output'])
  1144. def check_elim(self, base_tensor, multiplier):
  1145. if (not isinstance(base_tensor, Tensor)) or (not isinstance(multiplier, tuple)):
  1146. raise TypeError("Expecting (Tensor, tuple), got: ({}, {})".format(base_tensor, multiplier))
  1147. if all(v == 1 for v in multiplier):
  1148. return (True, base_tensor)
  1149. return (False, None)
  1150. def __infer__(self, x, multiples):
  1151. multiples_v = multiples['value']
  1152. x_shp = x['shape']
  1153. validator.check_value_type("multiples", multiples_v, [tuple], self.name)
  1154. for i, multiple in enumerate(multiples_v):
  1155. validator.check_value_type("multiples[%d]" % i, multiple, [int], self.name)
  1156. validator.check_value_type("x[\'dtype\']", x["dtype"], mstype.tensor_type, self.name)
  1157. len_sub = len(multiples_v) - len(x_shp)
  1158. multiples_w = None
  1159. if len_sub == 0:
  1160. multiples_w = multiples_v
  1161. if len_sub > 0:
  1162. for i in range(0, len_sub):
  1163. x_shp.insert(0, 1)
  1164. multiples_w = multiples_v
  1165. elif len_sub < 0:
  1166. raise ValueError(f'For \'{self.name}\' the length of multiples can not be smaller than '
  1167. f'the length of dimension in input_x.')
  1168. for i, a in enumerate(multiples_w):
  1169. x_shp[i] *= a
  1170. value = None
  1171. if x['value'] is not None:
  1172. value = Tensor(np.tile(x['value'].asnumpy(), multiples_w))
  1173. return {'shape': x_shp,
  1174. 'dtype': x['dtype'],
  1175. 'value': value}
  1176. class UnsortedSegmentSum(PrimitiveWithInfer):
  1177. r"""
  1178. Computes the sum along segments of a tensor.
  1179. Calculates a tensor such that :math:`\text{output}[i] = \sum_{segment\_ids[j] == i} \text{data}[j, \ldots]`, where
  1180. :math:`j` is a tuple describing the index of element in data. `segment_ids` selects which elements in data to sum
  1181. up. Segment_ids does not need to be sorted, and it does not need to cover all values in the entire valid value
  1182. range.
  1183. If the sum of the given segment_ids :math:`i` is empty, then :math:`\text{output}[i] = 0`. If the given segment_ids
  1184. is negative, the value will be ignored. 'num_segments' must be equal to the number of different segment_ids.
  1185. Inputs:
  1186. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`.
  1187. - **segment_ids** (Tensor) - Set the shape as :math:`(x_1, x_2, ..., x_N)`, where 0 < N <= R. Type must be int.
  1188. - **num_segments** (int) - Set :math:`z` as num_segments.
  1189. Outputs:
  1190. Tensor, the shape is :math:`(z, x_{N+1}, ..., x_R)`.
  1191. Examples:
  1192. >>> input_x = Tensor([1, 2, 3, 4], mindspore.float32)
  1193. >>> segment_ids = Tensor([0, 0, 1, 2], mindspore.int32)
  1194. >>> num_segments = 4
  1195. >>> P.UnsortedSegmentSum()(input_x, segment_ids, num_segments)
  1196. [3, 3, 4, 0]
  1197. """
  1198. @prim_attr_register
  1199. def __init__(self):
  1200. """Initialize UnsortedSegmentSum"""
  1201. self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y'])
  1202. self.add_prim_attr("dynamic_shape_depends", [2,])
  1203. def __infer__(self, x, segment_ids, num_segments):
  1204. x_type = x['dtype']
  1205. x_shp = x['shape']
  1206. validator.check_subclass("input_x", x_type, mstype.tensor, self.name)
  1207. validator.check_value_type("x_shape", x_shp, [list], self.name)
  1208. x_shp_len = len(x_shp)
  1209. validator.check_positive_int(x_shp_len, "rank of input_x", self.name)
  1210. segment_ids_shp = segment_ids['shape']
  1211. segment_ids_type = segment_ids['dtype']
  1212. validator.check_subclass("segment_ids", segment_ids_type, mstype.tensor, self.name)
  1213. validator.check_value_type("segment_ids", segment_ids_shp, [list], self.name)
  1214. segment_ids_shp_len = len(segment_ids_shp)
  1215. validator.check_positive_int(segment_ids_shp_len, "rank of segment_ids", self.name)
  1216. validator.check(f'rank of input_x', len(x_shp),
  1217. 'rank of segments_id', len(segment_ids_shp), Rel.GE, self.name)
  1218. for i, value in enumerate(segment_ids_shp):
  1219. validator.check("ids[%d]" % i, value, 'input[%d]' % i, x_shp[i], Rel.EQ, self.name)
  1220. num_segments_v = num_segments['value']
  1221. num_segments_type = num_segments['dtype']
  1222. validator.check_subclass("num_segments", num_segments_type, [mstype.tensor, mstype.number], self.name)
  1223. if isinstance(num_segments_type, type(mstype.tensor)):
  1224. validator.check_tensor_type_same({"num_segments": num_segments_type}, [mstype.int32], self.name)
  1225. shp = [-1]
  1226. else:
  1227. validator.check_value_type('num_segments', num_segments_v, [int], self.name)
  1228. validator.check_positive_int(num_segments_v, "num_segments", self.name)
  1229. shp = [num_segments_v]
  1230. shp += x_shp[segment_ids_shp_len:]
  1231. if 'max_shape' in x:
  1232. output_max_shape = x['max_shape']
  1233. else:
  1234. output_max_shape = x_shp
  1235. out = {'shape': shp,
  1236. 'max_shape': output_max_shape,
  1237. 'min_shape': [1] * segment_ids_shp_len + x_shp[segment_ids_shp_len:],
  1238. 'dtype': mstype.tensor_type(x_type.element_type()),
  1239. 'value': None}
  1240. return out
  1241. class UnsortedSegmentMin(PrimitiveWithInfer):
  1242. """
  1243. Computes the minimum along segments of a tensor.
  1244. Inputs:
  1245. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`.
  1246. The data type must be float16, float32 or int32.
  1247. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be >= 0.
  1248. The data type must be int32.
  1249. - **num_segments** (int) - The value spcifies the number of distinct `segment_ids`.
  1250. Outputs:
  1251. Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`.
  1252. Examples:
  1253. >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32))
  1254. >>> segment_ids = Tensor(np.array([0, 1, 1]).astype(np.int32))
  1255. >>> num_segments = 2
  1256. >>> unsorted_segment_min = P.UnsortedSegmentMin()
  1257. >>> unsorted_segment_min(input_x, segment_ids, num_segments)
  1258. [[1., 2., 3.], [4., 2., 1.]]
  1259. """
  1260. @prim_attr_register
  1261. def __init__(self):
  1262. """Initialize UnsortedSegmentMin"""
  1263. self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y'])
  1264. def __infer__(self, x, segment_ids, num_segments):
  1265. x_type = x['dtype']
  1266. x_shape = x['shape']
  1267. segment_ids_shape = segment_ids['shape']
  1268. valid_type = [mstype.float16, mstype.float32, mstype.int32]
  1269. validator.check_tensor_type_same({"x": x['dtype']}, valid_type, self.name)
  1270. validator.check_tensor_type_same({"segment_ids": segment_ids['dtype']}, [mstype.int32], self.name)
  1271. validator.check_integer("rank of segment_ids_shape", len(segment_ids_shape), 1, Rel.EQ, self.name)
  1272. validator.check(f'first shape of input_x', x_shape[0],
  1273. 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name)
  1274. num_segments_v = num_segments['value']
  1275. validator.check_value_type('num_segments', num_segments_v, [int], self.name)
  1276. validator.check_positive_int(num_segments_v, "num_segments", self.name)
  1277. segment_ids_shape_len = len(segment_ids_shape)
  1278. out_shape = [num_segments_v]
  1279. out_shape += x_shape[segment_ids_shape_len:]
  1280. out = {'shape': out_shape,
  1281. 'dtype': x_type,
  1282. 'value': None}
  1283. return out
  1284. class UnsortedSegmentProd(PrimitiveWithInfer):
  1285. """
  1286. Computes the product along segments of a tensor.
  1287. Inputs:
  1288. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`.
  1289. With float16, float32 or int32 data type.
  1290. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be >= 0.
  1291. Data type must be int32.
  1292. - **num_segments** (int) - The value spcifies the number of distinct `segment_ids`,
  1293. must be greater than 0.
  1294. Outputs:
  1295. Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`.
  1296. Examples:
  1297. >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32))
  1298. >>> segment_ids = Tensor(np.array([0, 1, 0]).astype(np.int32))
  1299. >>> num_segments = 2
  1300. >>> unsorted_segment_prod = P.UnsortedSegmentProd()
  1301. >>> unsorted_segment_prod(input_x, segment_ids, num_segments)
  1302. [[4., 4., 3.], [4., 5., 6.]]
  1303. """
  1304. @prim_attr_register
  1305. def __init__(self):
  1306. """Initialize UnsortedSegmentProd"""
  1307. self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y'])
  1308. def __infer__(self, x, segment_ids, num_segments):
  1309. x_type = x['dtype']
  1310. x_shape = x['shape']
  1311. segment_ids_shape = segment_ids['shape']
  1312. validator.check_subclass("input_x", x_type, mstype.tensor, self.name)
  1313. validator.check_value_type("x_shape", x_shape, [list], self.name)
  1314. valid_type = [mstype.float16, mstype.float32, mstype.int32]
  1315. validator.check_tensor_type_same({"x": x['dtype']}, valid_type, self.name)
  1316. validator.check_tensor_type_same({"segment_ids": segment_ids['dtype']}, [mstype.int32], self.name)
  1317. validator.check_integer("rank of segment_ids_shape", len(segment_ids_shape), 1, Rel.EQ, self.name)
  1318. validator.check(f'first shape of input_x', x_shape[0],
  1319. 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name)
  1320. num_segments_v = num_segments['value']
  1321. validator.check_value_type('num_segments', num_segments_v, [int], self.name)
  1322. validator.check_positive_int(num_segments_v, "num_segments", self.name)
  1323. segment_ids_shape_len = len(segment_ids_shape)
  1324. out_shape = [num_segments_v]
  1325. out_shape += x_shape[segment_ids_shape_len:]
  1326. out = {'shape': out_shape,
  1327. 'dtype': mstype.tensor_type(x_type.element_type()),
  1328. 'value': None}
  1329. return out
  1330. class Concat(PrimitiveWithInfer):
  1331. r"""
  1332. Concats tensor in specified axis.
  1333. Concats input tensors along with the given axis.
  1334. Note:
  1335. The input data is a tuple of tensors. These tensors have the same rank `R`. Set the given axis as `m`, and
  1336. :math:`0 \le m < R`. Set the number of input tensors as `N`. For the :math:`i`-th tensor :math:`t_i`, it has
  1337. the shape of :math:`(x_1, x_2, ..., x_{mi}, ..., x_R)`. :math:`x_{mi}` is the :math:`m`-th dimension of the
  1338. :math:`i`-th tensor. Then, the shape of the output tensor is
  1339. .. math::
  1340. (x_1, x_2, ..., \sum_{i=1}^Nx_{mi}, ..., x_R)
  1341. Args:
  1342. axis (int): The specified axis. Default: 0.
  1343. Inputs:
  1344. - **input_x** (tuple, list) - A tuple or a list of input tensors.
  1345. Outputs:
  1346. Tensor, the shape is :math:`(x_1, x_2, ..., \sum_{i=1}^Nx_{mi}, ..., x_R)`.
  1347. Examples:
  1348. >>> data1 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
  1349. >>> data2 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
  1350. >>> op = P.Concat()
  1351. >>> output = op((data1, data2))
  1352. [[0, 1],
  1353. [2, 1],
  1354. [0, 1],
  1355. [2, 1]]
  1356. """
  1357. @prim_attr_register
  1358. def __init__(self, axis=0):
  1359. """Initialize Tile"""
  1360. validator.check_value_type("axis", axis, [int], self.name)
  1361. def __infer__(self, input_x):
  1362. axis = self.axis
  1363. x_shp = input_x['shape']
  1364. x_type = input_x['dtype']
  1365. _, all_shp, _ = get_concat_offset(x_shp, x_type, axis, self.name)
  1366. self.add_prim_attr('T', x_type[0].element_type())
  1367. self.add_prim_attr('inputNums', len(x_shp))
  1368. ret_shp = x_shp[0].copy()
  1369. ret_shp[axis] = all_shp
  1370. out = {'shape': ret_shp,
  1371. 'dtype': x_type[0],
  1372. 'value': None}
  1373. return out
  1374. class ParallelConcat(PrimitiveWithInfer):
  1375. r"""
  1376. Concats tensor in the first dimension.
  1377. Concats input tensors along with the first dimension.
  1378. Note:
  1379. The input tensors are all required to have size 1 in the first dimension.
  1380. Inputs:
  1381. - **values** (tuple, list) - A tuple or a list of input tensors. The data type and shape of these
  1382. tensors must be the same.
  1383. Outputs:
  1384. Tensor, data type is the same as `values`.
  1385. Examples:
  1386. >>> data1 = Tensor(np.array([[0, 1]]).astype(np.int32))
  1387. >>> data2 = Tensor(np.array([[2, 1]]).astype(np.int32))
  1388. >>> op = P.ParallelConcat()
  1389. >>> output = op((data1, data2))
  1390. [[0, 1], [2, 1]]
  1391. """
  1392. @prim_attr_register
  1393. def __init__(self):
  1394. """Initialize ParallelConcat"""
  1395. def __infer__(self, values):
  1396. x_shp = values['shape']
  1397. x_type = values['dtype']
  1398. validator.check_integer(f'x_shp length', len(x_shp), 1, Rel.GE, self.name)
  1399. args = {f"x_type[{i}]": elem for i, elem in enumerate(x_type)}
  1400. validator.check_tensor_type_same(args, mstype.number_type + (mstype.bool_,), self.name)
  1401. first_elem = x_shp[0]
  1402. for i, elem in enumerate(x_shp[1:]):
  1403. j = i + 1
  1404. validator.check_integer(f'x_shp[{j}][0]', elem[0], 1, Rel.EQ, self.name)
  1405. validator.check(f"x_shp[0] shape", first_elem, f"x_shp[{j}] shape", elem, Rel.EQ, self.name)
  1406. ret_shp = x_shp[0].copy()
  1407. ret_shp[0] = len(x_shp)
  1408. self.add_prim_attr('shape', ret_shp)
  1409. self.add_prim_attr('N', len(x_shp))
  1410. out = {'shape': ret_shp,
  1411. 'dtype': x_type[0],
  1412. 'value': None}
  1413. return out
  1414. def _get_pack_shape(x_shape, x_type, axis, prim_name):
  1415. """for pack output shape"""
  1416. validator.check_value_type("shape", x_shape, [tuple, list], prim_name)
  1417. validator.check_integer("len of input_x", len(x_shape), 1, Rel.GE, prim_name)
  1418. validator.check_subclass("input_x[0]", x_type[0], mstype.tensor, prim_name)
  1419. rank_base = len(x_shape[0])
  1420. N = len(x_shape)
  1421. out_shape = x_shape[0]
  1422. validator.check_int_range('axis', axis, -rank_base - 1, rank_base, Rel.INC_BOTH, prim_name)
  1423. if axis < 0:
  1424. axis = axis + rank_base + 1
  1425. for i in range(1, N):
  1426. validator.check('x_type[%d]' % i, x_type[i], 'base', x_type[0], Rel.EQ, prim_name, TypeError)
  1427. if x_shape[i] != x_shape[0]:
  1428. raise ValueError(f"For \'{prim_name}\' element {i} shape in input can not pack with first element")
  1429. out_shape.insert(axis, N)
  1430. return out_shape
  1431. class Pack(PrimitiveWithInfer):
  1432. r"""
  1433. Packs a list of tensors in specified axis.
  1434. Packs the list of input tensors with the same rank `R`, output is a tensor of rank `(R+1)`.
  1435. Given input tensors of shape :math:`(x_1, x_2, ..., x_R)`. Set the number of input tensors as `N`.
  1436. If :math:`0 \le axis`, the shape of the output tensor is :math:`(x_1, x_2, ..., x_{axis}, N, x_{axis+1}, ..., x_R)`.
  1437. Args:
  1438. axis (int): Dimension to pack. Default: 0.
  1439. Negative values wrap around. The range is [-(R+1), R+1).
  1440. Inputs:
  1441. - **input_x** (Union[tuple, list]) - A Tuple or list of Tensor objects with the same shape and type.
  1442. Outputs:
  1443. Tensor. A packed Tensor with the same type as `input_x`.
  1444. Raises:
  1445. TypeError: If the data types of elements in `input_x` are not the same.
  1446. ValueError: If the length of `input_x` is not greater than 1;
  1447. or if axis is out of the range [-(R+1), R+1);
  1448. or if the shapes of elements in input_x are not the same.
  1449. Examples:
  1450. >>> data1 = Tensor(np.array([0, 1]).astype(np.float32))
  1451. >>> data2 = Tensor(np.array([2, 3]).astype(np.float32))
  1452. >>> pack = P.Pack()
  1453. >>> output = pack([data1, data2])
  1454. [[0, 1], [2, 3]]
  1455. """
  1456. @prim_attr_register
  1457. def __init__(self, axis=0):
  1458. """Initialize Pack"""
  1459. validator.check_value_type("axis", axis, [int], self.name)
  1460. self.axis = axis
  1461. def __infer__(self, value):
  1462. x_shape = value['shape']
  1463. x_type = value['dtype']
  1464. self.add_prim_attr('num', len(x_shape))
  1465. all_shape = _get_pack_shape(x_shape, x_type, self.axis, self.name)
  1466. out = {'shape': all_shape,
  1467. 'dtype': x_type[0],
  1468. 'value': None}
  1469. return out
  1470. class Unpack(PrimitiveWithInfer):
  1471. r"""
  1472. Unpacks tensor in specified axis.
  1473. Unpacks a tensor of rank `R` along axis dimension, output tensors will have rank `(R-1)`.
  1474. Given a tensor of shape :math:`(x_1, x_2, ..., x_R)`. If :math:`0 \le axis`,
  1475. the shape of tensor in output is :math:`(x_1, x_2, ..., x_{axis}, x_{axis+2}, ..., x_R)`.
  1476. This is the opposite of pack.
  1477. Args:
  1478. axis (int): Dimension along which to pack. Default: 0.
  1479. Negative values wrap around. The range is [-R, R).
  1480. Inputs:
  1481. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`.
  1482. A tensor to be unpacked and the rank of the tensor must be greater than 0.
  1483. Outputs:
  1484. A tuple of tensors, the shape of each objects is the same.
  1485. Raises:
  1486. ValueError: If axis is out of the range [-len(input_x.shape), len(input_x.shape)).
  1487. Examples:
  1488. >>> unpack = P.Unpack()
  1489. >>> input_x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]]))
  1490. >>> output = unpack(input_x)
  1491. ([1, 1, 1, 1], [2, 2, 2, 2])
  1492. """
  1493. @prim_attr_register
  1494. def __init__(self, axis=0):
  1495. """Initialize Unpack"""
  1496. validator.check_value_type("axis", axis, [int], self.name)
  1497. self.axis = axis
  1498. def __infer__(self, x):
  1499. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  1500. x_shape = list(x['shape'])
  1501. dim = len(x_shape)
  1502. validator.check_int_range('axis value', self.axis, -dim, dim, Rel.INC_LEFT, self.name)
  1503. if self.axis < 0:
  1504. self.axis = self.axis + dim
  1505. output_num = x_shape[self.axis]
  1506. validator.check_value_type("num", output_num, [int], self.name)
  1507. validator.check_positive_int(output_num, "output_num", self.name)
  1508. self.add_prim_attr('num', output_num)
  1509. output_valid_check = x_shape[self.axis] - output_num
  1510. validator.check_integer("The dimension which to unpack divides output_num", output_valid_check, 0, Rel.EQ,
  1511. self.name)
  1512. out_shapes = []
  1513. out_dtypes = []
  1514. out_shape = x_shape[:self.axis] + x_shape[self.axis + 1:]
  1515. for _ in range(output_num):
  1516. out_shapes.append(tuple(out_shape))
  1517. out_dtypes.append(x['dtype'])
  1518. out_shapes = tuple(out_shapes)
  1519. out_dtypes = tuple(out_dtypes)
  1520. out = {'shape': out_shapes,
  1521. 'dtype': out_dtypes,
  1522. 'value': None}
  1523. return out
  1524. class Slice(PrimitiveWithInfer):
  1525. """
  1526. Slices a tensor in the specified shape.
  1527. Args:
  1528. x (Tensor): The target tensor.
  1529. begin (tuple): The beginning of the slice. Only constant value is allowed.
  1530. size (tuple): The size of the slice. Only constant value is allowed.
  1531. Returns:
  1532. Tensor.
  1533. Examples:
  1534. >>> data = Tensor(np.array([[[1, 1, 1], [2, 2, 2]],
  1535. >>> [[3, 3, 3], [4, 4, 4]],
  1536. >>> [[5, 5, 5], [6, 6, 6]]]).astype(np.int32))
  1537. >>> type = P.Slice()(data, (1, 0, 0), (1, 1, 3))
  1538. """
  1539. @prim_attr_register
  1540. def __init__(self):
  1541. """Initialize slice"""
  1542. self.init_prim_io_names(inputs=['x', 'begin', 'size'], outputs=['output'])
  1543. def __infer__(self, x, begin, size):
  1544. x_shape = x['shape']
  1545. x_shp_len = len(x_shape)
  1546. validator.check_const_input('begin', begin['value'], self.name)
  1547. validator.check_const_input('size', size['value'], self.name)
  1548. begin_v, size_v = begin['value'], size['value']
  1549. if begin_v is None or size_v is None:
  1550. return {'shape': None,
  1551. 'dtype': x['dtype'],
  1552. 'value': None}
  1553. for key, value in zip(('begin', 'size'), (begin_v, size_v)):
  1554. validator.check(f'len of {key}', len(value),
  1555. 'len x\'s dim', x_shp_len)
  1556. for i in range(x_shp_len):
  1557. if x_shape[i] < begin_v[i] + size_v[i]:
  1558. y = begin_v[i] + size_v[i]
  1559. raise ValueError("For '%s' slice shape can not bigger than orign shape %d, %d." %
  1560. (self.name, x_shape[i], y))
  1561. return {'shape': size_v,
  1562. 'dtype': x['dtype'],
  1563. 'value': None}
  1564. class ReverseV2(PrimitiveWithInfer):
  1565. """
  1566. Reverses specific dimensions of a tensor.
  1567. Args:
  1568. axis (Union[tuple(int), list(int)): The indices of the dimensions to reverse.
  1569. Inputs:
  1570. - **input_x** (Tensor) - The target tensor.
  1571. Outputs:
  1572. Tensor, has the same shape and type as `input_x`.
  1573. Examples:
  1574. >>> input_x = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), mindspore.int32)
  1575. >>> op = P.ReverseV2(axis=[1])
  1576. >>> output = op(input_x)
  1577. [[4, 3, 2, 1], [8, 7, 6, 5]]
  1578. """
  1579. @prim_attr_register
  1580. def __init__(self, axis):
  1581. validator.check_value_type('axis', axis, [list, tuple], self.name)
  1582. for i, each in enumerate(axis):
  1583. validator.check_value_type(f'axis[{i}]', each, [int], self.name)
  1584. self.axis = axis
  1585. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  1586. def infer_shape(self, x_shape):
  1587. dim = len(x_shape)
  1588. for i, each in enumerate(self.axis):
  1589. validator.check_int_range(f'axis[{i}]', each, -dim, dim, Rel.INC_LEFT, self.name)
  1590. return x_shape
  1591. def infer_dtype(self, x_dtype):
  1592. validator.check_tensor_type_same({'x': x_dtype}, (mstype.bool_,) + mstype.number_type, self.name)
  1593. return x_dtype
  1594. class Rint(PrimitiveWithInfer):
  1595. """
  1596. Returns element-wise integer closest to x.
  1597. Inputs:
  1598. - **input_x** (Tensor) - The target tensor, which must be one of the following types:
  1599. float16, float32.
  1600. Outputs:
  1601. Tensor, has the same shape and type as `input_x`.
  1602. Examples:
  1603. >>> input_x = Tensor(np.array([-1.6, -0.1, 1.5, 2.0]), mindspore.float32)
  1604. >>> op = P.Rint()
  1605. >>> output = op(input_x)
  1606. [-2., 0., 2., 2.]
  1607. """
  1608. @prim_attr_register
  1609. def __init__(self):
  1610. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  1611. def infer_shape(self, x_shape):
  1612. return x_shape
  1613. def infer_dtype(self, x_dtype):
  1614. validator.check_tensor_type_same({'x': x_dtype}, [mstype.float16, mstype.float32], self.name)
  1615. return x_dtype
  1616. class Select(PrimitiveWithInfer):
  1617. r"""
  1618. Returns the selected elements, either from input :math:`x` or input :math:`y`, depending on the `condition`.
  1619. Given a tensor as input, this operation inserts a dimension of 1 at the dimension,
  1620. if both :math:`x` and :math:`y` are none, the operation returns the coordinates of the true
  1621. element in the `condition`, the coordinates are returned as a two-dimensional
  1622. tensor, where the first dimension (row) represents the number of true elements
  1623. and the second dimension (columns) represents the coordinates of the true
  1624. elements. Keep in mind that the shape of the output tensor can vary depending
  1625. on how many true values are in the input. Indexes are output in row-first
  1626. order.
  1627. If neither is None, :math:`x` and :math:`y` must have the same shape. If :math:`x` and :math:`y` are
  1628. scalars, the conditional tensor must be a scalar. If :math:`x` and :math:`y` are
  1629. higher-demensional vectors, the `condition` must be a vector whose size matches the
  1630. first dimension of :math:`x`, or must have the same shape as :math:`y`.
  1631. The conditional tensor acts as an optional compensation (mask), which
  1632. determines whether the corresponding element / row in the output must be
  1633. selected from :math:`x` (if true) or :math:`y` (if false) based on the value of each
  1634. element.
  1635. If condition is a vector, then :math:`x` and :math:`y` are higher-demensional matrices, then it
  1636. chooses to copy that row (external dimensions) from :math:`x` and :math:`y`. If condition has
  1637. the same shape as :math:`x` and :math:`y`, you can choose to copy these elements from :math:`x`
  1638. and :math:`y`.
  1639. Inputs:
  1640. - **input_x** (Tensor[bool]) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`.
  1641. The condition tensor, decides which element is chosen.
  1642. - **input_y** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`.
  1643. The first input tensor.
  1644. - **input_z** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`.
  1645. The second input tensor.
  1646. Outputs:
  1647. Tensor, has the same shape as `input_y`. The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`.
  1648. Examples:
  1649. >>> select = P.Select()
  1650. >>> input_x = Tensor([True, False])
  1651. >>> input_y = Tensor([2,3], mindspore.float32)
  1652. >>> input_z = Tensor([1,2], mindspore.float32)
  1653. >>> select(input_x, input_y, input_z)
  1654. """
  1655. @prim_attr_register
  1656. def __init__(self):
  1657. """init"""
  1658. self.init_prim_io_names(inputs=['condition', 'x', 'y'], outputs=['output'])
  1659. def infer_shape(self, cond_shape, x_shape, y_shape):
  1660. if cond_shape != x_shape or x_shape != y_shape:
  1661. raise ValueError('The x_shape and y_shape must be the same as cond_shape.')
  1662. return x_shape
  1663. def infer_dtype(self, cond_type, x_type, y_type):
  1664. self.add_prim_attr('T', x_type)
  1665. validator.check_subclass("x_type", x_type, mstype.tensor, self.name)
  1666. validator.check_subclass("y_type", y_type, mstype.tensor, self.name)
  1667. validator.check_tensor_type_same({"cond": cond_type}, [mstype.bool_], self.name)
  1668. if x_type != y_type:
  1669. raise TypeError('\'%s\' the x_type %s must be the same as y_type %s.' % (self.name, x_type, y_type))
  1670. return x_type
  1671. def infer_value(self, cond, x, y):
  1672. if cond is not None and x is not None and y is not None:
  1673. cond = cond.asnumpy()
  1674. x = x.asnumpy()
  1675. y = y.asnumpy()
  1676. out = np.where(cond, x, y)
  1677. return Tensor(out)
  1678. return None
  1679. def _compute_slicing_length(begin, end, stride, x_shape, i):
  1680. """Computes the length of the slicing."""
  1681. if i >= len(x_shape):
  1682. raise ValueError(f"For 'StridedSlice', When their is no new axis, the index length must be less or "
  1683. f"equal than the dim of x.")
  1684. x_dim = x_shape[i]
  1685. if stride > 0:
  1686. # When slicing forward, convert begin and end to positive numbers.
  1687. if begin >= x_dim or end < -x_dim:
  1688. # When slicing forward, if begin >= x_dim or end < -x_dim, the length of the slicing is 0.
  1689. slicing_length = 0
  1690. else:
  1691. if -x_dim <= begin < 0:
  1692. begin += x_dim
  1693. if begin < -x_dim:
  1694. # When slicing forward, if begin < -x_dim, set begin = 0, which means start from the 0th element.
  1695. begin = 0
  1696. if -x_dim <= end < 0:
  1697. end += x_dim
  1698. if end > x_dim:
  1699. # When slicing forward, if end > x_dim, set end = x_dims, which means slice to the last element.
  1700. end = x_dim
  1701. if begin >= end:
  1702. # When slicing forward, if begin >= end, the length of the slicing is 0.
  1703. slicing_length = 0
  1704. else:
  1705. slicing_length = 1 + (end - 1 - begin) // stride
  1706. else:
  1707. # When slicing backward, convert begin and end to negative numbers.
  1708. if begin < -x_dim or end >= x_dim:
  1709. # When slicing backward, if begin < -x_dim or end >= x_dim, the length of the slicing is 0.
  1710. slicing_length = 0
  1711. else:
  1712. if 0 <= begin < x_dim:
  1713. begin += -x_dim
  1714. if begin >= x_dim:
  1715. begin = -1
  1716. if 0 <= end < x_dim:
  1717. end += -x_dim
  1718. if end < -x_dim - 1:
  1719. # When slicing backward, if end < -x_dim - 1, set end = -x_dim - 1, which means
  1720. # slicing to the 0th element.
  1721. end = -x_dim - 1
  1722. if begin <= end:
  1723. # When slicing backward, if begin <= end, the length of the slicing is 0.
  1724. slicing_length = 0
  1725. else:
  1726. slicing_length = 1 + (end + 1 - begin) // stride
  1727. return slicing_length
  1728. class StridedSlice(PrimitiveWithInfer):
  1729. r"""
  1730. Extracts a strided slice of a tensor.
  1731. Given an input tensor, this operation inserts a dimension of length 1 at the dimension.
  1732. This operation extracts a fragment of size (end-begin)/stride from the given 'input_tensor'.
  1733. Starting from the begining position, the fragment continues adding stride to the index until
  1734. all dimensions are not less than the ending position.
  1735. Note:
  1736. The stride may be negative value, which causes reverse slicing.
  1737. The shape of `begin`, `end` and `strides` must be the same.
  1738. Args:
  1739. begin_mask (int): Starting index of the slice. Default: 0.
  1740. end_mask (int): Ending index of the slice. Default: 0.
  1741. ellipsis_mask (int): An int mask. Default: 0.
  1742. new_axis_mask (int): An int mask. Default: 0.
  1743. shrink_axis_mask (int): An int mask. Default: 0.
  1744. Inputs:
  1745. - **input_x** (Tensor) - The input Tensor.
  1746. - **begin** (tuple[int]) - A tuple which represents the location where to start. Only
  1747. constant value is allowed.
  1748. - **end** (tuple[int]) - A tuple or which represents the maximum location where to end.
  1749. Only constant value is allowed.
  1750. - **strides** (tuple[int]) - A tuple which represents the stride is continuously added
  1751. before reaching the maximum location. Only constant value is allowed.
  1752. Outputs:
  1753. Tensor.
  1754. The output is explained by following example.
  1755. - In the 0th dimension, begin is 1, end is 2, and strides is 1,
  1756. because :math:`1+1=2\geq2`, the interval is :math:`[1,2)`.
  1757. Thus, return the element with :math:`index = 1` in 0th dimension, i.e., [[3, 3, 3], [4, 4, 4]].
  1758. - In the 1st dimension, similarly, the interval is :math:`[0,1)`.
  1759. Based on the return value of the 0th dimension, return the element with :math:`index = 0`,
  1760. i.e., [3, 3, 3].
  1761. - In the 2nd dimension, similarly, the interval is :math:`[0,3)`.
  1762. Based on the return value of the 1st dimension, return the element with :math:`index = 0,1,2`,
  1763. i.e., [3, 3, 3].
  1764. - Finally, the output is [3, 3, 3].
  1765. Examples
  1766. >>> input_x = Tensor([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]],
  1767. >>> [[5, 5, 5], [6, 6, 6]]], mindspore.float32)
  1768. >>> slice = P.StridedSlice()
  1769. >>> output = slice(input_x, (1, 0, 0), (2, 1, 3), (1, 1, 1))
  1770. >>> output.shape
  1771. (1, 1, 3)
  1772. >>> output
  1773. [[[3, 3, 3]]]
  1774. """
  1775. @prim_attr_register
  1776. def __init__(self,
  1777. begin_mask=0,
  1778. end_mask=0,
  1779. ellipsis_mask=0,
  1780. new_axis_mask=0,
  1781. shrink_axis_mask=0):
  1782. """Initialize StrideSlice"""
  1783. self.init_prim_io_names(inputs=['x', 'begin', 'end', 'strides'], outputs=['output'])
  1784. validator.check_non_negative_int(begin_mask, 'begin_mask', self.name)
  1785. validator.check_non_negative_int(end_mask, 'end_mask', self.name)
  1786. validator.check_non_negative_int(ellipsis_mask, 'ellipsis_mask', self.name)
  1787. if len(tuple(filter(lambda x: x == '1', bin(ellipsis_mask)[-1:1:-1]))) > 1:
  1788. raise ValueError(f"For '{self.name}', only support one ellipsis in the index, but got {end_mask}.")
  1789. validator.check_non_negative_int(new_axis_mask, 'new_axis_mask', self.name)
  1790. validator.check_non_negative_int(shrink_axis_mask, 'shrink_axis_mask', self.name)
  1791. def __infer__(self, x, begin, end, strides):
  1792. begin_v, end_v, strides_v = begin['value'], end['value'], strides['value']
  1793. validator.check_value_type("begin", begin_v, [tuple], self.name)
  1794. validator.check_value_type("end", end_v, [tuple], self.name)
  1795. validator.check_value_type("strides", strides_v, [tuple], self.name)
  1796. if tuple(filter(lambda x: not isinstance(x, int), begin_v + end_v + strides_v)):
  1797. raise ValueError(f"For {self.name}, both the begins, ends, and strides must be a tuple of int, "
  1798. f"but got begins: {begin_v}, ends: {end_v}, strides: {strides_v}.")
  1799. if tuple(filter(lambda x: x == 0, strides_v)):
  1800. raise ValueError(f"For '{self.name}', the strides cannot contain 0, but got strides: {strides_v}.")
  1801. if len(end_v) != len(begin_v) or len(strides_v) != len(begin_v):
  1802. raise ValueError(f"For '{self.name}' the length of begin index: {begin_v}, end index: {end_v} and "
  1803. f"strides: {strides_v} must be equal.")
  1804. ret_shape = self._compute_slicing_shape(x['shape'], begin_v, end_v, strides_v)
  1805. value = None if all(ret_shape) else Tensor(np.array([]).reshape(ret_shape), x['dtype'].element_type())
  1806. return {'shape': ret_shape,
  1807. 'dtype': x['dtype'],
  1808. 'value': value}
  1809. def _compute_slicing_shape(self, x_shape, begin_v, end_v, strides_v):
  1810. """Computes the shape of the slicing."""
  1811. x_rank = len(x_shape)
  1812. slice_len = len(begin_v)
  1813. # After the integer is converted to binary, it is a str and the first two chars are the flag char '0b'.
  1814. begin_pos = bin(self.begin_mask)[-1:1:-1]
  1815. end_pos = bin(self.end_mask)[-1:1:-1]
  1816. ellipsis_pos = bin(self.ellipsis_mask)[-1:1:-1]
  1817. new_axis_pos = bin(self.new_axis_mask)[-1:1:-1]
  1818. shrink_axis_pos = bin(self.shrink_axis_mask)[-1:1:-1]
  1819. ret_shape = []
  1820. i, j = 0, 0
  1821. has_ellipsis = False
  1822. while i < x_rank or j < slice_len:
  1823. if j < slice_len:
  1824. begin, end, stride = begin_v[j], end_v[j], strides_v[j]
  1825. if j < len(ellipsis_pos) and ellipsis_pos[j] == '1':
  1826. # When there is ellipsis, the latter part of the ellipsis will be processed separately.
  1827. has_ellipsis = True
  1828. break
  1829. if j < len(begin_pos) and begin_pos[j] == '1':
  1830. begin = -1 if strides_v[j] < 0 else 0
  1831. if j < len(end_pos) and end_pos[j] == '1':
  1832. end = -(x_shape[i] + 1) if strides_v[j] < 0 else x_shape[i]
  1833. if j < len(new_axis_pos) and new_axis_pos[j] == '1':
  1834. ret_shape.append(1)
  1835. j += 1
  1836. continue
  1837. if j < len(shrink_axis_pos) and shrink_axis_pos[j] == '1':
  1838. if (not -x_shape[i] <= begin < x_shape[i]) or stride < 0:
  1839. raise ValueError(f"For {self.name}, when shrink axis, the stride cannot be negative number, "
  1840. f"and begin should be in [-{x_shape[i]}, {x_shape[i]}), "
  1841. f"but got stride: {stride}, begin: {begin}.")
  1842. j += 1
  1843. i += 1
  1844. continue
  1845. else:
  1846. begin, end, stride = 0, x_shape[i], 1
  1847. slicing_length = _compute_slicing_length(begin, end, stride, x_shape, i)
  1848. ret_shape.append(slicing_length)
  1849. i += 1
  1850. j += 1
  1851. if has_ellipsis:
  1852. # When there is ellipsis, handle the second half of the ellipsis split.
  1853. ellipsis_occupied_dims = x_rank - i - (slice_len - (j + 1)) + \
  1854. len(tuple(filter(lambda x: x == '1', new_axis_pos[j + 1:slice_len])))
  1855. ret_shape.extend(x_shape[i:i + ellipsis_occupied_dims])
  1856. j += 1
  1857. i += ellipsis_occupied_dims
  1858. while i < x_rank or j < slice_len:
  1859. begin, end, stride = begin_v[j], end_v[j], strides_v[j]
  1860. if j < len(begin_pos) and begin_pos[j] == '1':
  1861. begin = -1 if strides_v[j] < 0 else 0
  1862. if j < len(end_pos) and end_pos[j] == '1':
  1863. end = -(x_shape[i] + 1) if strides_v[j] < 0 else x_shape[i]
  1864. if j < len(new_axis_pos) and new_axis_pos[j] == '1':
  1865. ret_shape.append(1)
  1866. j += 1
  1867. continue
  1868. if j < len(shrink_axis_pos) and shrink_axis_pos[j] == '1':
  1869. if (not -x_shape[i] <= begin < x_shape[i]) or stride < 0:
  1870. raise ValueError(f"For {self.name}, when shrink axis, the stride cannot be negative number, "
  1871. f"and begin should be in [-{x_shape[i]}, {x_shape[i]}), "
  1872. f"but got stride: {stride}, begin: {begin}.")
  1873. j += 1
  1874. i += 1
  1875. continue
  1876. slicing_length = _compute_slicing_length(begin, end, stride, x_shape, i)
  1877. ret_shape.append(slicing_length)
  1878. i += 1
  1879. j += 1
  1880. return ret_shape
  1881. class Diag(PrimitiveWithInfer):
  1882. r"""
  1883. Constructs a diagonal tensor with a given diagonal values.
  1884. Assume `input_x` has dimensions :math:`[D_1,... D_k]`, the output is a tensor of
  1885. rank 2k with dimensions :math:`[D_1,..., D_k, D_1,..., D_k]` where:
  1886. :math:`output[i_1,..., i_k, i_1,..., i_k] = input_x[i_1,..., i_k]` and 0 everywhere else.
  1887. Inputs:
  1888. - **input_x** (Tensor) - The input tensor. The input shape must be less than 5d.
  1889. Outputs:
  1890. Tensor, has the same dtype as the `input_x`.
  1891. Examples:
  1892. >>> input_x = Tensor([1, 2, 3, 4])
  1893. >>> diag = P.Diag()
  1894. >>> diag(input_x)
  1895. [[1, 0, 0, 0],
  1896. [0, 2, 0, 0],
  1897. [0, 0, 3, 0],
  1898. [0, 0, 0, 4]]
  1899. """
  1900. @prim_attr_register
  1901. def __init__(self):
  1902. """Initialize Diag"""
  1903. def infer_dtype(self, x_type):
  1904. validator.check_subclass('input_x', x_type, mstype.tensor, self.name)
  1905. return x_type
  1906. def infer_shape(self, x_shape):
  1907. validator.check("x rank", len(x_shape), "", 1, Rel.GE)
  1908. ret_shape = copy.deepcopy(x_shape)
  1909. ret_shape = ret_shape + ret_shape
  1910. return ret_shape
  1911. def infer_value(self, x):
  1912. if x is None:
  1913. return None
  1914. # do constant-folding only when x rank is 1
  1915. if len(x.shape) != 1:
  1916. return None
  1917. ret = np.diag(x.asnumpy())
  1918. return Tensor(ret)
  1919. class DiagPart(PrimitiveWithInfer):
  1920. r"""
  1921. Extracts the diagonal part from given tensor.
  1922. Assume input has dimensions :math:`[D_1,..., D_k, D_1,..., D_k]`, the output is a tensor
  1923. of rank k with dimensions :math:`[D_1,..., D_k]` where:
  1924. :math:`output[i_1,..., i_k] = input[i_1,..., i_k, i_1,..., i_k]`.
  1925. Inputs:
  1926. - **input_x** (Tensor) - The input Tensor.
  1927. Outputs:
  1928. Tensor.
  1929. Examples
  1930. >>> input_x = Tensor([[1, 0, 0, 0],
  1931. >>> [0, 2, 0, 0],
  1932. >>> [0, 0, 3, 0],
  1933. >>> [0, 0, 0, 4]])
  1934. >>> diag_part = P.DiagPart()
  1935. >>> diag_part(input_x)
  1936. [1, 2, 3, 4]
  1937. """
  1938. @prim_attr_register
  1939. def __init__(self):
  1940. """Initialize DiagPart"""
  1941. def infer_dtype(self, x_type):
  1942. validator.check_subclass('input_x', x_type, mstype.tensor, self.name)
  1943. return x_type
  1944. def infer_shape(self, x_shape):
  1945. if len(x_shape) % 2 != 0 or \
  1946. not x_shape:
  1947. raise ValueError(f"For \'{self.name}\' input rank must be non-zero and even, but got rank {len(x_shape)}, "
  1948. f"with shapes {x_shape}")
  1949. length = len(x_shape) // 2
  1950. for i in range(length):
  1951. validator.check('input_shape[i + len(input_shape)/2]', x_shape[i + length],
  1952. 'input_shape[i]', x_shape[i], Rel.EQ, self.name)
  1953. ret_shape = x_shape[0:length]
  1954. return ret_shape
  1955. def infer_value(self, x):
  1956. if x is None:
  1957. return None
  1958. # do constant-folding only when x rank is 2
  1959. if len(x.shape) != 2:
  1960. return None
  1961. ret = np.diag(x.asnumpy())
  1962. return Tensor(ret)
  1963. class Eye(PrimitiveWithInfer):
  1964. """
  1965. Creates a tensor with ones on the diagonal and zeros the rest.
  1966. Inputs:
  1967. - **n** (int) - The number of rows of returned tensor
  1968. - **m** (int) - The number of columns of returned tensor
  1969. - **t** (mindspore.dtype) - MindSpore's dtype, The data type of the returned tensor.
  1970. Outputs:
  1971. Tensor, a tensor with ones on the diagonal and the rest of elements are zero.
  1972. Examples:
  1973. >>> eye = P.Eye()
  1974. >>> out_tensor = eye(2, 2, mindspore.int32)
  1975. [[1, 0],
  1976. [0, 1]]
  1977. """
  1978. @prim_attr_register
  1979. def __init__(self):
  1980. """Initialize Eye"""
  1981. def infer_value(self, n, m, t):
  1982. validator.check_positive_int(n, "n", self.name)
  1983. validator.check_positive_int(m, "m", self.name)
  1984. args = {"dtype": t}
  1985. validator.check_type_same(args, mstype.number_type + (mstype.bool_,), self.name)
  1986. np_type = mstype.dtype_to_nptype(t)
  1987. ret = np.eye(n, m, dtype=np_type)
  1988. return Tensor(ret)
  1989. class ScatterNd(PrimitiveWithInfer):
  1990. """
  1991. Scatters a tensor into a new tensor depending on the specified indices.
  1992. Creates an empty tensor, and set values by scattering the update tensor depending on indices.
  1993. Inputs:
  1994. - **indices** (Tensor) - The index of scattering in the new tensor with int32 data type.
  1995. - **update** (Tensor) - The source Tensor to be scattered.
  1996. - **shape** (tuple[int]) - Define the shape of the output tensor, has the same type as indices.
  1997. Outputs:
  1998. Tensor, the new tensor, has the same type as `update` and the same shape as `shape`.
  1999. Examples:
  2000. >>> op = P.ScatterNd()
  2001. >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32)
  2002. >>> update = Tensor(np.array([3.2, 1.1]), mindspore.float32)
  2003. >>> shape = (3, 3)
  2004. >>> output = op(indices, update, shape)
  2005. [[0. 3.2 0.]
  2006. [0. 1.1 0.]
  2007. [0. 0. 0. ]]
  2008. """
  2009. @prim_attr_register
  2010. def __init__(self):
  2011. """Initialize ScatterNd"""
  2012. self.init_prim_io_names(inputs=['indices', 'update', 'shape'], outputs=['output'])
  2013. def __infer__(self, indices, update, shape):
  2014. shp = shape['value']
  2015. validator.check_subclass("update_dtype", update['dtype'], mstype.tensor, self.name)
  2016. validator.check_tensor_type_same({"indices": indices['dtype']}, [mstype.int32], self.name)
  2017. validator.check_value_type("shape", shp, [tuple], self.name)
  2018. for i, x in enumerate(shp):
  2019. validator.check_positive_int(x, f'shape[{i}]', self.name)
  2020. indices_shape, update_shape = indices["shape"], update["shape"]
  2021. if indices_shape[0] != update_shape[0]:
  2022. raise ValueError(f'For \'{self.name}\' The indices_shape[0] and update_shape[0] must be equal.')
  2023. return {'shape': shp,
  2024. 'dtype': update['dtype'],
  2025. 'value': None}
  2026. class ResizeNearestNeighbor(PrimitiveWithInfer):
  2027. r"""
  2028. Resizes the input tensor by using nearest neighbor algorithm.
  2029. Resizes the input tensor to a given size by using the nearest neighbor algorithm. The nearest
  2030. neighbor algorithm selects the value of the nearest point and does not consider the
  2031. values of neighboring points at all, yielding a piecewise-constant interpolant.
  2032. Args:
  2033. size (Union[tuple, list]): The target size. The dimension of size must be 2.
  2034. align_corners (bool): Whether the centers of the 4 corner pixels of the input
  2035. and output tensors are aligned. Default: False.
  2036. Inputs:
  2037. - **input_x** (Tensor) - The input tensor. The shape of the tensor is :math:`(N, C, H, W)`.
  2038. Outputs:
  2039. Tensor, the shape of the output tensor is :math:`(N, C, NEW\_H, NEW\_W)`.
  2040. Examples:
  2041. >>> input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  2042. >>> resize = P.ResizeNearestNeighbor((2, 2))
  2043. >>> output = resize(input_tensor)
  2044. """
  2045. @prim_attr_register
  2046. def __init__(self, size, align_corners=False):
  2047. """Initialize ResizeNearestNeighbor"""
  2048. validator.check_value_type("size", size, [tuple, list], self.name)
  2049. validator.check_value_type("align_corners", align_corners, [bool], self.name)
  2050. validator.check_integer("length of size", len(size), 2, Rel.EQ, self.name)
  2051. for i, value in enumerate(size):
  2052. validator.check_non_negative_int(value, f'{i}th value of size', self.name)
  2053. self.init_prim_io_names(inputs=['image_in'], outputs=['image_out'])
  2054. def infer_shape(self, x):
  2055. validator.check('the dimension of input_x', len(x), '', 4, Rel.EQ, self.name)
  2056. return tuple(x)[:-2] + tuple(self.size)
  2057. def infer_dtype(self, x):
  2058. validator.check_subclass("x", x, mstype.tensor, self.name)
  2059. validator.check_tensor_type_same({"x": x}, mstype.number_type, self.name)
  2060. return x
  2061. class GatherNd(PrimitiveWithInfer):
  2062. """
  2063. Gathers slices from a tensor by indices.
  2064. Using given indices to gather slices from a tensor with a specified shape.
  2065. Inputs:
  2066. - **input_x** (Tensor) - The target tensor to gather values.
  2067. - **indices** (Tensor) - The index tensor, with int data type.
  2068. Outputs:
  2069. Tensor, has the same type as `input_x` and the shape is indices_shape[:-1] + x_shape[indices_shape[-1]:].
  2070. Examples:
  2071. >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  2072. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2073. >>> op = P.GatherNd()
  2074. >>> output = op(input_x, indices)
  2075. [-0.1, 0.5]
  2076. """
  2077. @prim_attr_register
  2078. def __init__(self):
  2079. """Initialize GatherNd"""
  2080. self.init_prim_io_names(inputs=['input_x', 'indices'], outputs=['y'])
  2081. def infer_shape(self, x_shape, indices_shape):
  2082. validator.check('the dimension of x', len(x_shape),
  2083. 'the dimension of indices', indices_shape[-1], Rel.GE, self.name)
  2084. return indices_shape[:-1] + x_shape[indices_shape[-1]:]
  2085. def infer_dtype(self, x_dtype, indices_dtype):
  2086. validator.check_subclass("x_dtype", x_dtype, mstype.tensor, self.name)
  2087. validator.check_tensor_type_same({"indices": indices_dtype}, mstype.int_type, self.name)
  2088. return x_dtype
  2089. class TensorScatterUpdate(PrimitiveWithInfer):
  2090. """
  2091. Updates tensor value using given values, along with the input indices.
  2092. Inputs:
  2093. - **input_x** (Tensor) - The target tensor. The dimension of input_x must be equal to indices.shape[-1].
  2094. - **indices** (Tensor) - The index of input tensor whose data type is int32.
  2095. - **update** (Tensor) - The tensor to update the input tensor, has the same type as input,
  2096. and update.shape = indices.shape[:-1] + input_x.shape[indices.shape[-1]:].
  2097. Outputs:
  2098. Tensor, has the same shape and type as `input_x`.
  2099. Examples:
  2100. >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  2101. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2102. >>> update = Tensor(np.array([1.0, 2.2]), mindspore.float32)
  2103. >>> op = P.TensorScatterUpdate()
  2104. >>> output = op(input_x, indices, update)
  2105. [[1.0, 0.3, 3.6],
  2106. [0.4, 2.2, -3.2]]
  2107. """
  2108. @prim_attr_register
  2109. def __init__(self):
  2110. """Initialize TensorScatterUpdate"""
  2111. self.init_prim_io_names(inputs=['x', 'indices', 'value'], outputs=['y'])
  2112. def infer_shape(self, x_shape, indices_shape, value_shape):
  2113. validator.check('the dimension of x', len(x_shape),
  2114. 'the dimension of indices', indices_shape[-1], Rel.GE)
  2115. if indices_shape[:-1] + x_shape[indices_shape[-1]:] != value_shape:
  2116. raise ValueError("For 'TensorScatterUpdate', input value are not match with input indices.")
  2117. return x_shape
  2118. def infer_dtype(self, x_dtype, indices_dtype, value_dtype):
  2119. validator.check_tensor_type_same({'indices': indices_dtype}, [mstype.int32], self.name)
  2120. args = {"x": x_dtype, "value": value_dtype}
  2121. validator.check_tensor_type_same(args, (mstype.bool_,) + mstype.number_type, self.name)
  2122. return x_dtype
  2123. class ScatterUpdate(_ScatterOp):
  2124. """
  2125. Updates tensor value by using input indices and value.
  2126. Using given values to update tensor value, along with the input indices.
  2127. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2128. If they have different data types, lower priority data type will be converted to
  2129. relatively highest priority data type.
  2130. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2131. Args:
  2132. use_locking (bool): Whether protect the assignment by a lock. Default: True.
  2133. Inputs:
  2134. - **input_x** (Parameter) - The target tensor, with data type of Parameter.
  2135. - **indices** (Tensor) - The index of input tensor. With int32 data type.
  2136. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input,
  2137. and updates.shape = indices.shape + input_x.shape[1:].
  2138. Outputs:
  2139. Tensor, has the same shape and type as `input_x`.
  2140. Examples:
  2141. >>> np_x = np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]])
  2142. >>> input_x = mindspore.Parameter(Tensor(np_x, mindspore.float32), name="x")
  2143. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2144. >>> np_updates = np.array([[[1.0, 2.2, 1.0], [2.0, 1.2, 1.0]], [[2.0, 2.2, 1.0], [3.0, 1.2, 1.0]]])
  2145. >>> updates = Tensor(np_updates, mindspore.float32)
  2146. >>> op = P.ScatterUpdate()
  2147. >>> output = op(input_x, indices, updates)
  2148. [[2.0, 1.2, 1.0],
  2149. [3.0, 1.2, 1.0]]
  2150. """
  2151. @prim_attr_register
  2152. def __init__(self, use_locking=True):
  2153. """Initialize ScatterUpdate"""
  2154. validator.check_value_type('use_locking', use_locking, [bool], self.name)
  2155. self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y'])
  2156. def infer_dtype(self, x_dtype, indices_dtype, value_dtype):
  2157. validator.check_tensor_type_same({'indices': indices_dtype}, [mstype.int32], self.name)
  2158. args = {"x": x_dtype, "value": value_dtype}
  2159. validator.check_tensor_type_same(args, (mstype.bool_,) + mstype.number_type, self.name)
  2160. return x_dtype
  2161. class ScatterNdUpdate(_ScatterNdOp):
  2162. """
  2163. Updates tensor value by using input indices and value.
  2164. Using given values to update tensor value, along with the input indices.
  2165. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2166. If they have different data types, lower priority data type will be converted to
  2167. relatively highest priority data type.
  2168. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2169. Args:
  2170. use_locking (bool): Whether protect the assignment by a lock. Default: True.
  2171. Inputs:
  2172. - **input_x** (Parameter) - The target tensor, with data type of Parameter.
  2173. - **indices** (Tensor) - The index of input tensor, with int32 data type.
  2174. - **update** (Tensor) - The tensor to be updated to the input tensor, has the same type as input.
  2175. Outputs:
  2176. Tensor, has the same shape and type as `input_x`.
  2177. Examples:
  2178. >>> np_x = np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]])
  2179. >>> input_x = mindspore.Parameter(Tensor(np_x, mindspore.float32), name="x")
  2180. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2181. >>> update = Tensor(np.array([1.0, 2.2]), mindspore.float32)
  2182. >>> op = P.ScatterNdUpdate()
  2183. >>> output = op(input_x, indices, update)
  2184. [[1. 0.3 3.6]
  2185. [0.4 2.2 -3.2]]
  2186. """
  2187. @prim_attr_register
  2188. def __init__(self, use_locking=True):
  2189. """Initialize ScatterNdUpdate"""
  2190. validator.check_value_type('use_locking', use_locking, [bool], self.name)
  2191. self.init_prim_io_names(inputs=['x', 'indices', 'value'], outputs=['y'])
  2192. def infer_dtype(self, x_dtype, indices_dtype, value_dtype):
  2193. validator.check_tensor_type_same({'indices': indices_dtype}, [mstype.int32], self.name)
  2194. args = {"x": x_dtype, "value": value_dtype}
  2195. validator.check_tensor_type_same(args, (mstype.bool_,) + mstype.number_type, self.name)
  2196. return x_dtype
  2197. class ScatterMax(_ScatterOp):
  2198. """
  2199. Updates the value of the input tensor through the max operation.
  2200. Using given values to update tensor value through the max operation, along with the input indices.
  2201. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2202. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2203. If they have different data types, lower priority data type will be converted to
  2204. relatively highest priority data type.
  2205. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2206. Args:
  2207. use_locking (bool): Whether protect the assignment by a lock. Default: True.
  2208. Inputs:
  2209. - **input_x** (Parameter) - The target parameter.
  2210. - **indices** (Tensor) - The index to do max operation whose data type must be mindspore.int32.
  2211. - **updates** (Tensor) - The tensor that performs the maximum operation with `input_x`,
  2212. the data type is the same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  2213. Outputs:
  2214. Parameter, the updated `input_x`.
  2215. Examples:
  2216. >>> input_x = Parameter(Tensor(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), mindspore.float32), name="input_x")
  2217. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2218. >>> update = Tensor(np.ones([2, 2, 3]) * 88, mindspore.float32)
  2219. >>> scatter_max = P.ScatterMax()
  2220. >>> output = scatter_max(input_x, indices, update)
  2221. [[88.0, 88.0, 88.0], [88.0, 88.0, 88.0]]
  2222. """
  2223. @prim_attr_register
  2224. def __init__(self, use_locking=True):
  2225. """Initialize ScatterMax"""
  2226. self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y'])
  2227. validator.check_value_type('use_locking', use_locking, (bool,), self.name)
  2228. class ScatterMin(_ScatterOp):
  2229. """
  2230. Updates the value of the input tensor through the min operation.
  2231. Using given values to update tensor value through the min operation, along with the input indices.
  2232. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2233. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2234. If they have different data types, lower priority data type will be converted to
  2235. relatively highest priority data type.
  2236. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2237. Args:
  2238. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  2239. Inputs:
  2240. - **input_x** (Parameter) - The target parameter.
  2241. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32.
  2242. - **updates** (Tensor) - The tensor doing the min operation with `input_x`,
  2243. the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  2244. Outputs:
  2245. Parameter, the updated `input_x`.
  2246. Examples:
  2247. >>> input_x = Parameter(Tensor(np.array([[0.0, 1.0, 2.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="input_x")
  2248. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2249. >>> update = Tensor(np.ones([2, 2, 3]), mindspore.float32)
  2250. >>> scatter_min = P.ScatterMin()
  2251. >>> output = scatter_min(input_x, indices, update)
  2252. [[0.0, 1.0, 1.0], [0.0, 0.0, 0.0]]
  2253. """
  2254. class ScatterAdd(_ScatterOp):
  2255. """
  2256. Updates the value of the input tensor through the add operation.
  2257. Using given values to update tensor value through the add operation, along with the input indices.
  2258. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2259. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2260. If they have different data types, lower priority data type will be converted to
  2261. relatively highest priority data type.
  2262. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2263. Args:
  2264. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  2265. Inputs:
  2266. - **input_x** (Parameter) - The target parameter.
  2267. - **indices** (Tensor) - The index to do add operation whose data type must be mindspore.int32.
  2268. - **updates** (Tensor) - The tensor that performs the add operation with `input_x`,
  2269. the data type is the same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  2270. Outputs:
  2271. Parameter, the updated `input_x`.
  2272. Examples:
  2273. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x")
  2274. >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32)
  2275. >>> updates = Tensor(np.ones([2, 2, 3]), mindspore.float32)
  2276. >>> scatter_add = P.ScatterAdd()
  2277. >>> output = scatter_add(input_x, indices, updates)
  2278. [[1.0, 1.0, 1.0], [3.0, 3.0, 3.0]]
  2279. """
  2280. class ScatterSub(_ScatterOp):
  2281. """
  2282. Updates the value of the input tensor through the subtraction operation.
  2283. Using given values to update tensor value through the subtraction operation, along with the input indices.
  2284. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2285. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2286. If they have different data types, lower priority data type will be converted to
  2287. relatively highest priority data type.
  2288. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2289. Args:
  2290. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  2291. Inputs:
  2292. - **input_x** (Parameter) - The target parameter.
  2293. - **indices** (Tensor) - The index to perform the subtraction operation
  2294. whose data type must be mindspore.int32.
  2295. - **updates** (Tensor) - The tensor that performs the subtraction operation with `input_x`,
  2296. the data type is the same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  2297. Outputs:
  2298. Parameter, the updated `input_x`.
  2299. Examples:
  2300. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]), mindspore.float32), name="x")
  2301. >>> indices = Tensor(np.array([[0, 1]]), mindspore.int32)
  2302. >>> updates = Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32)
  2303. >>> scatter_sub = P.ScatterSub()
  2304. >>> output = scatter_sub(input_x, indices, updates)
  2305. [[-1.0, -1.0, -1.0], [-1.0, -1.0, -1.0]]
  2306. """
  2307. class ScatterMul(_ScatterOp):
  2308. """
  2309. Updates the value of the input tensor through the mul operation.
  2310. Using given values to update tensor value through the mul operation, along with the input indices.
  2311. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2312. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2313. If they have different data types, lower priority data type will be converted to
  2314. relatively highest priority data type.
  2315. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2316. Args:
  2317. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  2318. Inputs:
  2319. - **input_x** (Parameter) - The target parameter.
  2320. - **indices** (Tensor) - The index to do mul operation whose data type must be mindspore.int32.
  2321. - **updates** (Tensor) - The tensor doing the mul operation with `input_x`,
  2322. the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  2323. Outputs:
  2324. Parameter, the updated `input_x`.
  2325. Examples:
  2326. >>> input_x = Parameter(Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x")
  2327. >>> indices = Tensor(np.array([0, 1]), mindspore.int32)
  2328. >>> updates = Tensor(np.ones([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]), mindspore.float32)
  2329. >>> scatter_mul = P.ScatterMul()
  2330. >>> output = scatter_mul(input_x, indices, updates)
  2331. [[2.0, 2.0, 2.0], [4.0, 4.0, 4.0]]
  2332. """
  2333. class ScatterDiv(_ScatterOp):
  2334. """
  2335. Updates the value of the input tensor through the div operation.
  2336. Using given values to update tensor value through the div operation, along with the input indices.
  2337. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2338. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2339. If they have different data types, lower priority data type will be converted to
  2340. relatively highest priority data type.
  2341. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2342. Args:
  2343. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  2344. Inputs:
  2345. - **input_x** (Parameter) - The target parameter.
  2346. - **indices** (Tensor) - The index to do div operation whose data type must be mindspore.int32.
  2347. - **updates** (Tensor) - The tensor that performs the div operation with `input_x`,
  2348. the data type is the same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  2349. Outputs:
  2350. Parameter, the updated `input_x`.
  2351. Examples:
  2352. >>> input_x = Parameter(Tensor(np.array([[6.0, 6.0, 6.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x")
  2353. >>> indices = Tensor(np.array([0, 1]), mindspore.int32)
  2354. >>> updates = Tensor(np.ones([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]), mindspore.float32)
  2355. >>> scatter_div = P.ScatterDiv()
  2356. >>> output = scatter_div(input_x, indices, updates)
  2357. [[3.0, 3.0, 3.0], [1.0, 1.0, 1.0]]
  2358. """
  2359. class ScatterNdAdd(_ScatterNdOp):
  2360. """
  2361. Applies sparse addition to individual values or slices in a Tensor.
  2362. Using given values to update tensor value through the add operation, along with the input indices.
  2363. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2364. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2365. If they have different data types, lower priority data type will be converted to
  2366. relatively highest priority data type.
  2367. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2368. Args:
  2369. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  2370. Inputs:
  2371. - **input_x** (Parameter) - The target parameter.
  2372. - **indices** (Tensor) - The index to do add operation whose data type must be mindspore.int32.
  2373. - **updates** (Tensor) - The tensor doing the add operation with `input_x`,
  2374. the data type is same as `input_x`, the shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`.
  2375. Outputs:
  2376. Parameter, the updated `input_x`.
  2377. Examples:
  2378. >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x")
  2379. >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32)
  2380. >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32)
  2381. >>> scatter_nd_add = P.ScatterNdAdd()
  2382. >>> output = scatter_nd_add(input_x, indices, updates)
  2383. [1, 10, 9, 4, 12, 6, 7, 17]
  2384. """
  2385. class ScatterNdSub(_ScatterNdOp):
  2386. """
  2387. Applies sparse subtraction to individual values or slices in a Tensor.
  2388. Using given values to update tensor value through the subtraction operation, along with the input indices.
  2389. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2390. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2391. If they have different data types, lower priority data type will be converted to
  2392. relatively highest priority data type.
  2393. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2394. Args:
  2395. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  2396. Inputs:
  2397. - **input_x** (Parameter) - The target parameter.
  2398. - **indices** (Tensor) - The index to do add operation whose data type must be mindspore.int32.
  2399. - **updates** (Tensor) - The tensor that performs the subtraction operation with `input_x`,
  2400. the data type is the same as `input_x`, the shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`.
  2401. Outputs:
  2402. Parameter, the updated `input_x`.
  2403. Examples:
  2404. >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x")
  2405. >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32)
  2406. >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32)
  2407. >>> scatter_nd_sub = P.ScatterNdSub()
  2408. >>> output = scatter_nd_sub(input_x, indices, updates)
  2409. [1, -6, -3, 4, -2, 6, 7, -1]
  2410. """
  2411. class ScatterNonAliasingAdd(_ScatterNdOp):
  2412. """
  2413. Applies sparse addition to input using individual values or slices.
  2414. Using given values to update tensor value through the add operation, along with the input indices.
  2415. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2416. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2417. If they have different data types, lower priority data type will be converted to
  2418. relatively highest priority data type.
  2419. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2420. Inputs:
  2421. - **input_x** (Parameter) - The target parameter. The data type must be float16, float32 or int32.
  2422. - **indices** (Tensor) - The index to perform the addition operation whose data type must be mindspore.int32.
  2423. - **updates** (Tensor) - The tensor that performs the addition operation with `input_x`,
  2424. the data type is the same as `input_x`, the shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`.
  2425. Outputs:
  2426. Parameter, the updated `input_x`.
  2427. Examples:
  2428. >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x")
  2429. >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32)
  2430. >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32)
  2431. >>> scatter_non_aliasing_add = P.ScatterNonAliasingAdd()
  2432. >>> output = scatter_non_aliasing_add(input_x, indices, updates)
  2433. [1, 10, 9, 4, 12, 6, 7, 17]
  2434. """
  2435. @prim_attr_register
  2436. def __init__(self):
  2437. """Initialize ScatterNonAliasingAdd"""
  2438. self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y'])
  2439. def infer_dtype(self, x_dtype, indices_dtype, updates_dtype):
  2440. validator.check_tensor_type_same({'indices': indices_dtype}, [mstype.int32], self.name)
  2441. args = {"x": x_dtype, "updates": updates_dtype}
  2442. validator.check_tensor_type_same(args, [mstype.float16, mstype.float32, mstype.int32], self.name)
  2443. return x_dtype
  2444. class SpaceToDepth(PrimitiveWithInfer):
  2445. r"""
  2446. Rearranges blocks of spatial data into depth.
  2447. The output tensor's `height` dimension is :math:`height / block\_size`.
  2448. The output tensor's `weight` dimension is :math:`weight / block\_size`.
  2449. The depth of output tensor is :math:`block\_size * block\_size * input\_depth`.
  2450. The input tensor's height and width must be divisible by `block_size`.
  2451. The data format is "NCHW".
  2452. Args:
  2453. block_size (int): The block size used to divide spatial data. It must be >= 2.
  2454. Inputs:
  2455. - **x** (Tensor) - The target tensor.
  2456. Outputs:
  2457. Tensor, the same data type as `x`. It must be a 4-D tensor.
  2458. Examples:
  2459. >>> x = Tensor(np.random.rand(1,3,2,2), mindspore.float32)
  2460. >>> block_size = 2
  2461. >>> op = P.SpaceToDepth(block_size)
  2462. >>> output = op(x)
  2463. >>> output.asnumpy().shape == (1,12,1,1)
  2464. """
  2465. @prim_attr_register
  2466. def __init__(self, block_size):
  2467. """Initialize SpaceToDepth"""
  2468. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  2469. validator.check_value_type('block_size', block_size, [int], self.name)
  2470. validator.check('block_size', block_size, '', 2, Rel.GE)
  2471. self.block_size = block_size
  2472. def infer_shape(self, x_shape):
  2473. validator.check('x dimension', len(x_shape), '', 4, Rel.EQ)
  2474. out_shape = copy.deepcopy(x_shape)
  2475. for i in range(2):
  2476. if out_shape[i + 2] % self.block_size != 0:
  2477. raise ValueError(f'For \'{self.name}\' input shape[{i + 2}] {out_shape[i + 2]} should be '
  2478. f'fully divided by block_size {self.block_size}')
  2479. out_shape[i + 2] //= self.block_size
  2480. out_shape[1] *= self.block_size * self.block_size
  2481. return out_shape
  2482. def infer_dtype(self, x_dtype):
  2483. validator.check_subclass("x_dtype", x_dtype, mstype.tensor, self.name)
  2484. return x_dtype
  2485. class DepthToSpace(PrimitiveWithInfer):
  2486. r"""
  2487. Rearranges blocks of depth data into spatial dimensions.
  2488. This is the reverse operation of SpaceToDepth.
  2489. The depth of output tensor is :math:`input\_depth / (block\_size * block\_size)`.
  2490. The output tensor's `height` dimension is :math:`height * block\_size`.
  2491. The output tensor's `weight` dimension is :math:`weight * block\_size`.
  2492. The input tensor's depth must be divisible by `block_size * block_size`.
  2493. The data format is "NCHW".
  2494. Args:
  2495. block_size (int): The block size used to divide depth data. It must be >= 2.
  2496. Inputs:
  2497. - **x** (Tensor) - The target tensor. It must be a 4-D tensor.
  2498. Outputs:
  2499. Tensor, has the same shape and dtype as the 'x'.
  2500. Examples:
  2501. >>> x = Tensor(np.random.rand(1,12,1,1), mindspore.float32)
  2502. >>> block_size = 2
  2503. >>> op = P.DepthToSpace(block_size)
  2504. >>> output = op(x)
  2505. >>> output.asnumpy().shape == (1,3,2,2)
  2506. """
  2507. @prim_attr_register
  2508. def __init__(self, block_size):
  2509. """Initialize DepthToSpace"""
  2510. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  2511. validator.check_value_type('block_size', block_size, [int], self.name)
  2512. validator.check('block_size', block_size, '', 2, Rel.GE, self.name)
  2513. self.block_size = block_size
  2514. def infer_shape(self, x_shape):
  2515. validator.check('x dimension', len(x_shape), '', 4, Rel.EQ)
  2516. out_shape = copy.deepcopy(x_shape)
  2517. for i in range(2):
  2518. out_shape[i + 2] *= self.block_size
  2519. validator.check_integer('x_shape[1] % (block_size*block_size)',
  2520. x_shape[1] % (self.block_size * self.block_size),
  2521. 0, Rel.EQ, self.name)
  2522. out_shape[1] //= self.block_size * self.block_size
  2523. return out_shape
  2524. def infer_dtype(self, x_dtype):
  2525. validator.check_subclass("x_dtype", x_dtype, mstype.tensor, self.name)
  2526. return x_dtype
  2527. class SpaceToBatch(PrimitiveWithInfer):
  2528. r"""
  2529. Divides spatial dimensions into blocks and combine the block size with the original batch.
  2530. This operation will divide spatial dimensions (H, W) into blocks with `block_size`, the output tensor's H and W
  2531. dimension is the corresponding number of blocks after division. The output tensor's batch dimension is the
  2532. product of the original batch and the square of block_size. Before division, the spatial dimensions
  2533. of the input are zero padded according to paddings if necessary.
  2534. Args:
  2535. block_size (int): The block size of dividing blocks with value greater than 2.
  2536. paddings (Union[tuple, list]): The padding values for H and W dimension, containing 2 subtraction lists.
  2537. Each subtraction list contains 2 integer value. All values must be greater than 0.
  2538. paddings[i] specifies the paddings for the spatial dimension i, which corresponds to the
  2539. input dimension i+2. It is required that input_shape[i+2]+paddings[i][0]+paddings[i][1]
  2540. is divisible by block_size.
  2541. Inputs:
  2542. - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor.
  2543. Outputs:
  2544. Tensor, the output tensor with the same data type as input. Assume input shape is :math:`(n, c, h, w)` with
  2545. :math:`block\_size` and :math:`paddings`. The shape of the output tensor will be :math:`(n', c', h', w')`,
  2546. where
  2547. :math:`n' = n*(block\_size*block\_size)`
  2548. :math:`c' = c`
  2549. :math:`h' = (h+paddings[0][0]+paddings[0][1])//block\_size`
  2550. :math:`w' = (w+paddings[1][0]+paddings[1][1])//block\_size`
  2551. Examples:
  2552. >>> block_size = 2
  2553. >>> paddings = [[0, 0], [0, 0]]
  2554. >>> space_to_batch = P.SpaceToBatch(block_size, paddings)
  2555. >>> input_x = Tensor(np.array([[[[1, 2], [3, 4]]]]), mindspore.float32)
  2556. >>> space_to_batch(input_x)
  2557. [[[[1.]]], [[[2.]]], [[[3.]]], [[[4.]]]]
  2558. """
  2559. @prim_attr_register
  2560. def __init__(self, block_size, paddings):
  2561. """Initialize SpaceToBatch"""
  2562. validator.check_value_type('block_size', block_size, [int], self.name)
  2563. validator.check('block_size', block_size, '', 2, Rel.GE, self.name)
  2564. self.block_size = block_size
  2565. validator.check('paddings shape', np.array(paddings).shape, '', (2, 2), Rel.EQ, self.name)
  2566. for elem in itertools.chain(*paddings):
  2567. validator.check_non_negative_int(elem, 'paddings element', self.name)
  2568. validator.check_value_type('paddings element', elem, [int], self.name)
  2569. self.paddings = paddings
  2570. def infer_dtype(self, x_dtype):
  2571. validator.check_tensor_type_same({'input_x': x_dtype}, mstype.number_type, self.name)
  2572. return x_dtype
  2573. def infer_shape(self, x_shape):
  2574. validator.check_integer('rank of input_x', len(x_shape), 4, Rel.EQ, self.name)
  2575. out_shape = copy.deepcopy(x_shape)
  2576. for i in range(2):
  2577. padded = out_shape[i + 2] + self.paddings[i][0] + self.paddings[i][1]
  2578. if padded % self.block_size != 0:
  2579. raise ValueError(f'For \'{self.name}\' padded[{i}] {padded} should be divisible by '
  2580. f'block_size {self.block_size}')
  2581. out_shape[i + 2] = padded // self.block_size
  2582. out_shape[0] *= self.block_size * self.block_size
  2583. return out_shape
  2584. class BatchToSpace(PrimitiveWithInfer):
  2585. r"""
  2586. Divides batch dimension with blocks and interleaves these blocks back into spatial dimensions.
  2587. This operation will divide batch dimension N into blocks with block_size, the output tensor's N dimension
  2588. is the corresponding number of blocks after division. The output tensor's H, W dimension is product of original H, W
  2589. dimension and block_size with given amount to crop from dimension, respectively.
  2590. Args:
  2591. block_size (int): The block size of division, has the value not less than 2.
  2592. crops (Union[list(int), tuple(int)]): The crop value for H and W dimension, containing 2 subtraction lists.
  2593. Each list contains 2 integers.
  2594. All values must be not less than 0. crops[i] specifies the crop values for the spatial dimension i, which
  2595. corresponds to the input dimension i+2. It is required that
  2596. input_shape[i+2]*block_size >= crops[i][0]+crops[i][1].
  2597. Inputs:
  2598. - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor, dimension 0 must be divisible by
  2599. product of `block_shape`.
  2600. Outputs:
  2601. Tensor, the output tensor with the same type as input. Assume input shape is (n, c, h, w) with block_size
  2602. and crops. The output shape will be (n', c', h', w'), where
  2603. :math:`n' = n//(block\_size*block\_size)`
  2604. :math:`c' = c`
  2605. :math:`h' = h*block\_size-crops[0][0]-crops[0][1]`
  2606. :math:`w' = w*block\_size-crops[1][0]-crops[1][1]`
  2607. Examples:
  2608. >>> block_size = 2
  2609. >>> crops = [[0, 0], [0, 0]]
  2610. >>> op = P.BatchToSpace(block_size, crops)
  2611. >>> input_x = Tensor(np.array([[[[1]]], [[[2]]], [[[3]]], [[[4]]]]), mindspore.float32)
  2612. >>> output = op(input_x)
  2613. [[[[1., 2.], [3., 4.]]]]
  2614. """
  2615. @prim_attr_register
  2616. def __init__(self, block_size, crops):
  2617. """Initialize BatchToSpace"""
  2618. validator.check_value_type('block_size', block_size, [int], self.name)
  2619. validator.check('block_size', block_size, '', 2, Rel.GE, self.name)
  2620. self.block_size = block_size
  2621. validator.check_value_type('crops type', crops, [list, tuple], self.name)
  2622. validator.check('crops shape', np.array(crops).shape, '', (2, 2))
  2623. for elem in itertools.chain(*crops):
  2624. validator.check_non_negative_int(elem, 'crops element', self.name)
  2625. validator.check_value_type('crops element', elem, [int], self.name)
  2626. self.crops = crops
  2627. def infer_dtype(self, x_dtype):
  2628. validator.check_tensor_type_same({'input_x': x_dtype}, mstype.number_type, self.name)
  2629. return x_dtype
  2630. def infer_shape(self, x_shape):
  2631. validator.check('rank of input_x', len(x_shape), '', 4)
  2632. out_shape = copy.deepcopy(x_shape)
  2633. for i in range(2):
  2634. x_block_prod = out_shape[i + 2] * self.block_size
  2635. crops_sum = self.crops[i][0] + self.crops[i][1]
  2636. validator.check("x block shape prod", x_block_prod, 'crops sum', crops_sum, Rel.GT, self.name)
  2637. out_shape[i + 2] = x_block_prod - crops_sum
  2638. block_size_prod = self.block_size * self.block_size
  2639. if out_shape[0] % block_size_prod != 0:
  2640. raise ValueError(f'For \'{self.name}\' input_x dimension 0 {out_shape[0]} should be divisible by '
  2641. f'block_size_prod {block_size_prod}')
  2642. out_shape[0] = out_shape[0] // block_size_prod
  2643. return out_shape
  2644. class SpaceToBatchND(PrimitiveWithInfer):
  2645. r"""
  2646. Divides spatial dimensions into blocks and combine the block size with the original batch.
  2647. This operation will divide spatial dimensions (H, W) into blocks with block_shape, the output tensor's H and W
  2648. dimension is the corresponding number of blocks after division. The output tensor's batch dimension is the
  2649. product of the original batch and the product of `block_shape`. Before division,
  2650. the spatial dimensions of the input are zero padded according to paddings if necessary.
  2651. Args:
  2652. block_shape (Union[list(int), tuple(int)]): The block shape of dividing block with all value greater than 1.
  2653. The length of `block_shape` is M correspoding to the number of spatial dimensions. M must be 2.
  2654. paddings (Union[tuple, list]): The padding values for H and W dimension, containing 2 subtraction list.
  2655. Each contains 2 integer value. All values must be greater than 0.
  2656. `paddings[i]` specifies the paddings for the spatial dimension i,
  2657. which corresponds to the input dimension i+2.
  2658. It is required that input_shape[i+2]+paddings[i][0]+paddings[i][1] is divisible by block_shape[i].
  2659. Inputs:
  2660. - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor.
  2661. Outputs:
  2662. Tensor, the output tensor with the same data type as input. Assume input shape is :math:`(n, c, h, w)` with
  2663. :math:`block\_shape` and :math:`padddings`. The shape of the output tensor will be :math:`(n', c', h', w')`,
  2664. where
  2665. :math:`n' = n*(block\_shape[0]*block\_shape[1])`
  2666. :math:`c' = c`
  2667. :math:`h' = (h+paddings[0][0]+paddings[0][1])//block\_shape[0]`
  2668. :math:`w' = (w+paddings[1][0]+paddings[1][1])//block\_shape[1]`
  2669. Examples:
  2670. >>> block_shape = [2, 2]
  2671. >>> paddings = [[0, 0], [0, 0]]
  2672. >>> space_to_batch_nd = P.SpaceToBatchND(block_shape, paddings)
  2673. >>> input_x = Tensor(np.array([[[[1, 2], [3, 4]]]]), mindspore.float32)
  2674. >>> space_to_batch_nd(input_x)
  2675. [[[[1.]]], [[[2.]]], [[[3.]]], [[[4.]]]]
  2676. """
  2677. @prim_attr_register
  2678. def __init__(self, block_shape, paddings):
  2679. """Initialize SpaceToBatchND"""
  2680. self.ori_block_shape = block_shape
  2681. self.ori_paddings = paddings
  2682. validator.check_value_type('block_shape type', block_shape, [list, tuple], self.name)
  2683. validator.check('block_shape shape', len(np.array(block_shape).shape), '', 1, Rel.EQ, self.name)
  2684. block_rank = len(block_shape)
  2685. validator.check('block_shape length', block_rank, '', 2, Rel.EQ, self.name)
  2686. for elem in block_shape:
  2687. validator.check('block_shape element', elem, '', 1, Rel.GE, self.name)
  2688. validator.check_value_type('block_shape element', elem, [int], self.name)
  2689. self.block_shape = block_shape
  2690. validator.check_value_type('paddings type', paddings, [list, tuple], self.name)
  2691. validator.check('paddings length', len(paddings), '', 2, Rel.EQ, self.name)
  2692. validator.check('paddings shape', np.array(paddings).shape, '', (block_rank, 2), Rel.EQ, self.name)
  2693. for elem in itertools.chain(*paddings):
  2694. validator.check_non_negative_int(elem, 'paddings element', self.name)
  2695. validator.check_value_type('paddings element', elem, [int], self.name)
  2696. self.paddings = paddings
  2697. block_shape_append = [1] + list(self.block_shape)
  2698. self.add_prim_attr("block_shape", block_shape_append)
  2699. paddings_append = [[0, 0]] + list(self.paddings)
  2700. self.add_prim_attr("paddings", paddings_append)
  2701. def infer_dtype(self, x_dtype):
  2702. validator.check_tensor_type_same({'input_x': x_dtype}, mstype.number_type, self.name)
  2703. return x_dtype
  2704. def infer_shape(self, x_shape):
  2705. x_rank = len(x_shape)
  2706. validator.check_integer('x_shape rank', x_rank, 4, Rel.EQ, self.name)
  2707. out_shape = copy.deepcopy(x_shape)
  2708. block_shape_prod = 1
  2709. offset = 2
  2710. if x_rank <= 4:
  2711. offset = 1
  2712. for i in range(len(self.block_shape)):
  2713. padded = out_shape[i + offset] + self.paddings[i][0] + \
  2714. self.paddings[i][1]
  2715. if padded % self.block_shape[i] != 0:
  2716. raise ValueError(f'For \'{self.name}\' padded[{i}] {padded} should be divisible by '
  2717. f'block_shape[{i}] {self.block_shape[i]}')
  2718. out_shape[i + offset] = padded // self.block_shape[i]
  2719. block_shape_prod = block_shape_prod * self.block_shape[i]
  2720. out_shape[0] *= block_shape_prod
  2721. return out_shape
  2722. class BatchToSpaceND(PrimitiveWithInfer):
  2723. r"""
  2724. Divides batch dimension with blocks and interleave these blocks back into spatial dimensions.
  2725. This operation will divide batch dimension N into blocks with block_shape, the output tensor's N dimension
  2726. is the corresponding number of blocks after division. The output tensor's H, W dimension is product of original H, W
  2727. dimension and block_shape with given amount to crop from dimension, respectively.B
  2728. Args:
  2729. block_shape (Union[list(int), tuple(int)]): The block shape of dividing block with all value >= 1.
  2730. The length of block_shape is M correspoding to the number of spatial dimensions. M must be 2.
  2731. crops (Union[list(int), tuple(int)]): The crop value for H and W dimension, containing 2 subtraction list,
  2732. each containing 2 int value.
  2733. All values must be >= 0. crops[i] specifies the crop values for spatial dimension i, which corresponds to
  2734. input dimension i+2. It is required that input_shape[i+2]*block_shape[i] > crops[i][0]+crops[i][1].
  2735. Inputs:
  2736. - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor, dimension 0 must be divisible by
  2737. product of `block_shape`.
  2738. Outputs:
  2739. Tensor, the output tensor with the same type as input. Assume input shape is (n, c, h, w) with block_shape
  2740. and crops. The output shape will be (n', c', h', w'), where
  2741. :math:`n' = n//(block\_shape[0]*block\_shape[1])`
  2742. :math:`c' = c`
  2743. :math:`h' = h*block\_shape[0]-crops[0][0]-crops[0][1]`
  2744. :math:`w' = w*block\_shape[1]-crops[1][0]-crops[1][1]`
  2745. Examples:
  2746. >>> block_shape = [2, 2]
  2747. >>> crops = [[0, 0], [0, 0]]
  2748. >>> batch_to_space_nd = P.BatchToSpaceND(block_shape, crops)
  2749. >>> input_x = Tensor(np.array([[[[1]]], [[[2]]], [[[3]]], [[[4]]]]), mindspore.float32)
  2750. >>> output = batch_to_space_nd(input_x)
  2751. [[[[1., 2.], [3., 4.]]]]
  2752. """
  2753. @prim_attr_register
  2754. def __init__(self, block_shape, crops):
  2755. """Initialize BatchToSpaceND"""
  2756. self.ori_block_shape = block_shape
  2757. self.ori_crops = crops
  2758. validator.check_value_type('block_shape type', block_shape, [list, tuple], self.name)
  2759. validator.check('block_shape shape', len(np.array(block_shape).shape), '', 1, Rel.EQ, self.name)
  2760. block_rank = len(block_shape)
  2761. validator.check('block_shape length', block_rank, '', 2, Rel.EQ, self.name)
  2762. for elem in block_shape:
  2763. validator.check('block_shape element', elem, '', 1, Rel.GE, self.name)
  2764. validator.check_value_type('block_shape element', elem, [int], self.name)
  2765. self.block_shape = block_shape
  2766. validator.check_value_type('crops type', crops, [list, tuple], self.name)
  2767. validator.check('crops length', len(crops), '', 2, Rel.EQ, self.name)
  2768. validator.check('crops shape', np.array(crops).shape, '', (block_rank, 2), Rel.EQ, self.name)
  2769. for elem in itertools.chain(*crops):
  2770. validator.check_non_negative_int(elem, 'crops element', self.name)
  2771. validator.check_value_type('crops element', elem, [int], self.name)
  2772. self.crops = crops
  2773. block_shape_append = [1] + list(self.block_shape)
  2774. self.add_prim_attr("block_shape", block_shape_append)
  2775. crops_append = [[0, 0]] + list(self.crops)
  2776. self.add_prim_attr("crops", crops_append)
  2777. def infer_dtype(self, x_dtype):
  2778. validator.check_tensor_type_same({'input_x': x_dtype}, mstype.number_type, self.name)
  2779. return x_dtype
  2780. def infer_shape(self, x_shape):
  2781. x_rank = len(x_shape)
  2782. validator.check_integer('x_shape rank', x_rank, 4, Rel.EQ, self.name)
  2783. out_shape = copy.deepcopy(x_shape)
  2784. block_shape_prod = 1
  2785. offset = 2
  2786. if x_rank <= 4:
  2787. offset = 1
  2788. for i in range(len(self.block_shape)):
  2789. block_shape_prod = block_shape_prod * self.block_shape[i]
  2790. x_block_prod = out_shape[i + offset] * self.block_shape[i]
  2791. crops_sum = self.crops[i][0] + self.crops[i][1]
  2792. validator.check("x block shape prod", x_block_prod, 'crops sum', crops_sum, Rel.GT, self.name)
  2793. out_shape[i + offset] = x_block_prod - crops_sum
  2794. if out_shape[0] % block_shape_prod != 0:
  2795. raise ValueError(f'For \'{self.name}\' input_x dimension 0 {out_shape[0]} should be divisible by '
  2796. f'block_shape_prod {block_shape_prod}')
  2797. out_shape[0] = out_shape[0] // block_shape_prod
  2798. return out_shape
  2799. class BroadcastTo(PrimitiveWithInfer):
  2800. """
  2801. Broadcasts input tensor to a given shape.
  2802. Input shape can be broadcast to target shape if for each dimension pair they are either equal or input is one.
  2803. When input shape is broadcast to target shape, it starts with the trailing dimensions.
  2804. Args:
  2805. shape (tuple): The target shape to broadcast.
  2806. Inputs:
  2807. - **input_x** (Tensor) - The input tensor.
  2808. Outputs:
  2809. Tensor, with the given `shape` and the same data type as `input_x`.
  2810. Examples:
  2811. >>> shape = (2, 3)
  2812. >>> input_x = Tensor(np.array([1, 2, 3]).astype(np.float32))
  2813. >>> broadcast_to = P.BroadcastTo(shape)
  2814. >>> broadcast_to(input_x)
  2815. [[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]
  2816. """
  2817. @prim_attr_register
  2818. def __init__(self, shape):
  2819. """Initialize BroadcastTo"""
  2820. validator.check_value_type("shape", shape, (tuple), self.name)
  2821. validator.check("shape length", len(shape), "", 0, Rel.GT, self.name)
  2822. for i in shape:
  2823. validator.check_positive_int(i, "shape element", self.name)
  2824. self.shape = shape
  2825. def infer_shape(self, x_shape):
  2826. validator.check("input_x shape length", len(x_shape), "target shape", len(self.shape), Rel.LE, self.name)
  2827. reversed_x_shape = tuple(reversed(x_shape))
  2828. reversed_target = tuple(reversed(self.shape))
  2829. for i, v in enumerate(reversed_x_shape):
  2830. if v not in (reversed_target[i], 1):
  2831. raise ValueError(f"Not supported shapes for broadcast, "
  2832. f"x_shape: {tuple(x_shape)}, target shape {self.shape}.")
  2833. return self.shape
  2834. def infer_dtype(self, x_dtype):
  2835. validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name)
  2836. return x_dtype
  2837. class Meshgrid(PrimitiveWithInfer):
  2838. """
  2839. Generates coordinate matrices from given coordinate tensors.
  2840. Given N one-dimensional coordinate tensors, returns a list outputs of N N-D
  2841. coordinate tensors for evaluating expressions on an N-D grid.
  2842. Args:
  2843. indexing (str): Either 'xy' or 'ij'. Default: 'xy'.
  2844. When the indexing argument is set to 'xy' (the default),
  2845. the broadcasting instructions for the first two dimensions are swapped.
  2846. Inputs:
  2847. - **input_x** (Union[tuple, list]) - A Tuple or list of N 1-D Tensor objects.
  2848. The length of input_x should be greater than 1
  2849. Outputs:
  2850. Tensors, A Tuple of N N-D Tensor objects.
  2851. Examples:
  2852. >>> x = np.array([1, 2, 3, 4]).astype(np.int32)
  2853. >>> y = np.array([5, 6, 7]).astype(np.int32)
  2854. >>> z = np.array([8, 9, 0, 1, 2]).astype(np.int32)
  2855. >>> inputs = (x, y, z)
  2856. >>> meshgrid = P.Meshgrid(indexing="xy")
  2857. >>> meshgrid(inputs)
  2858. (Tensor(shape=[3, 4, 6], dtype=UInt32, value=
  2859. [[[1, 1, 1, 1, 1],
  2860. [2, 2, 2, 2, 2],
  2861. [3, 3, 3, 3, 3],
  2862. [4, 4, 4, 4, 4]],
  2863. [[1, 1, 1, 1, 1],
  2864. [2, 2, 2, 2, 2],
  2865. [3, 3, 3, 3, 3],
  2866. [4, 4, 4, 4, 4]],
  2867. [[1, 1, 1, 1, 1],
  2868. [2, 2, 2, 2, 2],
  2869. [3, 3, 3, 3, 3],
  2870. [4, 4, 4, 4, 4]]]),
  2871. Tensor(shape=[3, 4, 6], dtype=UInt32, value=
  2872. [[[5, 5, 5, 5, 5],
  2873. [5, 5, 5, 5, 5],
  2874. [5, 5, 5, 5, 5],
  2875. [5, 5, 5, 5, 5]],
  2876. [[6, 6, 6, 6, 6],
  2877. [6, 6, 6, 6, 6],
  2878. [6, 6, 6, 6, 6],
  2879. [6, 6, 6, 6, 6]],
  2880. [[7, 7, 7, 7, 7],
  2881. [7, 7, 7, 7, 7],
  2882. [7, 7, 7, 7, 7],
  2883. [7, 7, 7, 7, 7]]]),
  2884. Tensor(shape=[3, 4, 6], dtype=UInt32, value=
  2885. [[[8, 9, 0, 1, 2],
  2886. [8, 9, 0, 1, 2],
  2887. [8, 9, 0, 1, 2],
  2888. [8, 9, 0, 1, 2]],
  2889. [[8, 9, 0, 1, 2],
  2890. [8, 9, 0, 1, 2],
  2891. [8, 9, 0, 1, 2],
  2892. [8, 9, 0, 1, 2]],
  2893. [[8, 9, 0, 1, 2],
  2894. [8, 9, 0, 1, 2],
  2895. [8, 9, 0, 1, 2],
  2896. [8, 9, 0, 1, 2]]]))
  2897. """
  2898. @prim_attr_register
  2899. def __init__(self, indexing="xy"):
  2900. """Init Meshgrid"""
  2901. validator.check_value_type("indexing", indexing, (str), self.name)
  2902. if indexing not in ("xy", "ij"):
  2903. raise ValueError("indexing parameter must be either 'xy' or 'ij'")
  2904. self.indexing = indexing
  2905. def infer_shape(self, x_shape):
  2906. validator.check_value_type("shape", x_shape, [tuple, list], self.name)
  2907. validator.check_integer("len of input_x", len(x_shape), 2, Rel.GE, self.name)
  2908. n = len(x_shape)
  2909. shape_0 = []
  2910. for s in x_shape:
  2911. validator.check_integer('each_input_rank', len(s), 1, Rel.EQ, self.name)
  2912. shape_0.append(s[0])
  2913. if self.indexing == "xy":
  2914. shape_0[0], shape_0[1] = shape_0[1], shape_0[0]
  2915. out_shape = tuple(tuple(shape_0) for _ in range(n))
  2916. return out_shape
  2917. def infer_dtype(self, x_type):
  2918. validator.check_subclass("input_x[0]", x_type[0], mstype.tensor, self.name)
  2919. n = len(x_type)
  2920. for i in range(1, n):
  2921. validator.check('x_type[%d]' % i, x_type[i], 'base', x_type[0], Rel.EQ, self.name, TypeError)
  2922. return x_type
  2923. class InplaceUpdate(PrimitiveWithInfer):
  2924. r"""
  2925. Updates specified rows with values in `v`.
  2926. Args:
  2927. indices (Union[int, tuple]): Indices into the left-most dimension of `x`, and determines which rows of x
  2928. to update with v. It is a int or tuple, whose value is in [0, the first dimension size of x).
  2929. Inputs:
  2930. - **x** (Tensor) - A tensor which to be inplace updated. It can be one of the following data types:
  2931. float32, float16 and int32.
  2932. - **v** (Tensor) - A tensor with the same type as `x` and the same dimension size as `x` except
  2933. the first dimension, which must be the same as the size of `indices`.
  2934. Outputs:
  2935. Tensor, with the same type and shape as the input `x`.
  2936. Examples:
  2937. >>> indices = (0, 1)
  2938. >>> x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32)
  2939. >>> v = Tensor(np.array([[0.5, 1.0], [1.0, 1.5]]), mindspore.float32)
  2940. >>> inplace_update = P.InplaceUpdate(indices)
  2941. >>> result = inplace_update(x, v)
  2942. [[0.5, 1.0],
  2943. [1.0, 1.5],
  2944. [5.0, 6.0]]
  2945. """
  2946. @prim_attr_register
  2947. def __init__(self, indices):
  2948. """Initialize InplaceUpdate"""
  2949. self.init_prim_io_names(inputs=['x', 'v'], outputs=['y'])
  2950. self.indices = indices
  2951. validator.check_value_type("indices", indices, [int, tuple], self.name)
  2952. if isinstance(indices, int):
  2953. self.indices = (indices,)
  2954. for item in self.indices:
  2955. validator.check_value_type("item of indices", item, [int], self.name)
  2956. def infer_dtype(self, x_dtype, v_dtype):
  2957. args = {'x': x_dtype, 'v': v_dtype}
  2958. valid_type = [mstype.int32, mstype.float16, mstype.float32]
  2959. validator.check_tensor_type_same(args, valid_type, self.name)
  2960. return x_dtype
  2961. def infer_shape(self, x_shape, v_shape):
  2962. validator.check("x", len(x_shape), "v", len(v_shape), Rel.EQ, self.name)
  2963. validator.check("size of indices", len(self.indices), "v's first dimension", v_shape[0],
  2964. Rel.EQ, self.name)
  2965. for i in self.indices:
  2966. if i < 0 or i >= x_shape[0]:
  2967. raise ValueError(f'The value of indices must be in [0, {x_shape[0]}), but got {i}.')
  2968. x_rank = len(x_shape)
  2969. for idx in range(x_rank)[1:]:
  2970. validator.check('v dim %d' % idx, v_shape[idx], "x dim %d" % idx, x_shape[idx], Rel.EQ, self.name)
  2971. return x_shape
  2972. class ReverseSequence(PrimitiveWithInfer):
  2973. """
  2974. Reverses variable length slices.
  2975. Args:
  2976. seq_dim (int): The dimension where reversal is performed. Required.
  2977. batch_dim (int): The input is sliced in this dimension. Default: 0.
  2978. Inputs:
  2979. - **x** (Tensor) - The input to reverse, supporting all number types including bool.
  2980. - **seq_lengths** (Tensor) - Must be a 1-D vector with int32 or int64 types.
  2981. Outputs:
  2982. Reversed tensor with the same shape and data type as input.
  2983. Examples:
  2984. >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32)
  2985. >>> seq_lengths = Tensor(np.array([1, 2, 3]))
  2986. >>> reverse_sequence = P.ReverseSequence(seq_dim=1)
  2987. >>> output = reverse_sequence(x, seq_lengths)
  2988. [[1 2 3]
  2989. [5 4 6]
  2990. [9 8 7]]
  2991. """
  2992. @prim_attr_register
  2993. def __init__(self, seq_dim, batch_dim=0):
  2994. """Initialize ReverseSequence"""
  2995. self.init_prim_io_names(inputs=['x', 'seq_lengths'], outputs=['y'])
  2996. validator.check_value_type("seq_dim", seq_dim, [int], self.name)
  2997. self.seq_dim_ = seq_dim
  2998. validator.check_value_type("batch_dim", batch_dim, [int], self.name)
  2999. self.batch_dim_ = batch_dim
  3000. def infer_shape(self, x, seq_lengths):
  3001. validator.check("seq_dim", self.seq_dim_, "x rank", len(x), Rel.LE, self.name)
  3002. validator.check("batch_dim", self.batch_dim_, "x rank", len(x), Rel.LE, self.name)
  3003. validator.check("batch_dim", self.batch_dim_, "seq_dim", self.seq_dim_, Rel.NE, self.name)
  3004. validator.check("seq_lengths rank", len(seq_lengths), "expected", 1, Rel.EQ, self.name)
  3005. validator.check("seq_lengths vector size", seq_lengths[0],
  3006. "input size along batch_dim", x[self.batch_dim_], Rel.EQ, self.name)
  3007. return x
  3008. def infer_dtype(self, x, seq_lengths):
  3009. validator.check_tensor_type_same({"x_dtype": x}, mstype.number_type + (mstype.bool_,), self.name)
  3010. validator.check_tensor_type_same({"seq_lengths_dtype": seq_lengths}, [mstype.int32, mstype.int64], self.name)
  3011. return x
  3012. class EditDistance(PrimitiveWithInfer):
  3013. """
  3014. Computes the Levebshtein Edit Distance. It is used to measure the similarity of two sequences.
  3015. Args:
  3016. normalize (bool): If true, edit distances are normalized by length of truth. Default: True.
  3017. Inputs:
  3018. - **hypothesis_indices** (Tensor) - The indices of the hypothesis list SparseTensor. With int64 data type.
  3019. The shape of tensor is :math:`(N, R)`.
  3020. - **hypothesis_values** (Tensor) - The values of the hypothesis list SparseTensor.
  3021. Must be 1-D vector with length of N.
  3022. - **hypothesis_shape** (Tensor) - The shape of the hypothesis list SparseTensor.
  3023. Must be R-length vector with int64 data type. Only constant value is allowed.
  3024. - **truth_indices** (Tensor) - The indices of the truth list SparseTensor. With int64 data type.
  3025. The shape of tensor is :math:`(M, R)`.
  3026. - **truth_values** (Tensor) - The values of the truth list SparseTensor. Must be 1-D vector with length of M.
  3027. - **truth_shape** (Tensor) - The shape of the truth list SparseTensor.
  3028. Must be R-length vector with int64 data type. Only constant value is allowed.
  3029. Outputs:
  3030. Tensor, a dense tensor with rank `R-1` and float32 data type.
  3031. Examples:
  3032. >>> import numpy as np
  3033. >>> from mindspore import context
  3034. >>> from mindspore import Tensor
  3035. >>> import mindspore.nn as nn
  3036. >>> import mindspore.ops.operations as P
  3037. >>> context.set_context(mode=context.GRAPH_MODE)
  3038. >>> class EditDistance(nn.Cell):
  3039. >>> def __init__(self, hypothesis_shape, truth_shape, normalize=True):
  3040. >>> super(EditDistance, self).__init__()
  3041. >>> self.edit_distance = P.EditDistance(normalize)
  3042. >>> self.hypothesis_shape = hypothesis_shape
  3043. >>> self.truth_shape = truth_shape
  3044. >>>
  3045. >>> def construct(self, hypothesis_indices, hypothesis_values, truth_indices, truth_values):
  3046. >>> return self.edit_distance(hypothesis_indices, hypothesis_values, self.hypothesis_shape,
  3047. >>> truth_indices, truth_values, self.truth_shape)
  3048. >>>
  3049. >>> hypothesis_indices = Tensor(np.array([[0, 0, 0], [1, 0, 1], [1, 1, 1]]).astype(np.int64))
  3050. >>> hypothesis_values = Tensor(np.array([1, 2, 3]).astype(np.float32))
  3051. >>> hypothesis_shape = Tensor(np.array([1, 1, 2]).astype(np.int64))
  3052. >>> truth_indices = Tensor(np.array([[0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1]]).astype(np.int64))
  3053. >>> truth_values = Tensor(np.array([1, 3, 2, 1]).astype(np.float32))
  3054. >>> truth_shape = Tensor(np.array([2, 2, 2]).astype(np.int64))
  3055. >>> edit_distance = EditDistance(hypothesis_shape, truth_shape)
  3056. >>> out = edit_distance(hypothesis_indices, hypothesis_values, truth_indices, truth_values)
  3057. >>> [[1.0, 1.0], [1.0, 1.0]]
  3058. """
  3059. @prim_attr_register
  3060. def __init__(self, normalize=True):
  3061. """Initialize EditDistance"""
  3062. self.normalize = validator.check_value_type("normalize", normalize, [bool], self.name)
  3063. self.set_const_input_indexes([2, 5])
  3064. def __infer__(self, h_indices, h_values, h_shape, truth_indices, truth_values, truth_shape):
  3065. validator.check_const_input('hypothesis_shape', h_shape['value'], self.name)
  3066. validator.check_const_input('truth_shape', truth_shape['value'], self.name)
  3067. args_int = {"hypothesis_indices": h_indices['dtype'], "hypothesis_shape": h_shape['dtype'],
  3068. "truth_indices": truth_indices['dtype'], "truth_shape": truth_shape['dtype']}
  3069. validator.check_tensor_type_same(args_int, [mstype.int64], self.name)
  3070. args = {"hypothesis_values": h_values['dtype'], "truth_values": truth_values['dtype']}
  3071. validator.check_tensor_type_same(args, mstype.number_type, self.name)
  3072. hypothesis_indices_shp, truth_indices_shp = h_indices['shape'], truth_indices['shape']
  3073. validator.check("hypothesis_indices rank", len(hypothesis_indices_shp), "expected", 2, Rel.EQ, self.name)
  3074. validator.check("truth_indices rank", len(truth_indices_shp), "expected", 2, Rel.EQ, self.name)
  3075. validator.check("hypothesis_values rank", len(h_values['shape']), "expected", 1, Rel.EQ, self.name)
  3076. validator.check("hypothesis_shape rank", len(h_shape['shape']), "expected", 1, Rel.EQ, self.name)
  3077. validator.check("truth_values rank", len(truth_values['shape']), "expected", 1, Rel.EQ, self.name)
  3078. validator.check("truth_shape rank", len(truth_shape['shape']), "expected", 1, Rel.EQ, self.name)
  3079. validator.check("hypothesis_values shape", h_values['shape'][0],
  3080. "hypothesis_indices shape[0]", hypothesis_indices_shp[0], Rel.EQ, self.name)
  3081. validator.check("hypothesis_shape", h_shape['shape'][0],
  3082. "hypothesis_indices shape[1]", hypothesis_indices_shp[1], Rel.EQ, self.name)
  3083. validator.check("truth_values shape", truth_values['shape'][0],
  3084. "truth_indices shape[0]", truth_indices_shp[0], Rel.EQ, self.name)
  3085. validator.check("hypothesis_shape", h_shape['shape'][0],
  3086. "truth_shape", truth_shape['shape'][0], Rel.EQ, self.name)
  3087. hypothesis_shape_v = h_shape['value'].asnumpy()
  3088. truth_shape_v = truth_shape['value'].asnumpy()
  3089. out_shape_rank = len(hypothesis_shape_v) - 1
  3090. out_shape = []
  3091. for i in range(out_shape_rank):
  3092. out_shape.append(max(hypothesis_shape_v[i], truth_shape_v[i]))
  3093. return {'shape': tuple(out_shape),
  3094. 'dtype': mstype.tensor_type(mstype.float32),
  3095. 'value': None}
  3096. class TransShape(PrimitiveWithInfer):
  3097. """
  3098. Transforms the shape of input tensor to target shape.
  3099. Inputs:
  3100. - **input_x** (Tensor) - A input tensor.
  3101. - **out_shape** (tuple[int]) - The shape of output data.
  3102. Outputs:
  3103. Tensor, a tensor whose data type is same as 'input_x', and the shape is the same as the `out_shape`.
  3104. """
  3105. @prim_attr_register
  3106. def __init__(self):
  3107. self.__setattr_flag__ = True
  3108. def __infer__(self, x, shape):
  3109. shp = shape['value']
  3110. dtype = x['dtype']
  3111. validator.check_tensor_type_same({'x': dtype}, mstype.number_type + (mstype.bool_,), self.name)
  3112. self.add_prim_attr('out_shape', tuple(shp))
  3113. return {'shape': shp,
  3114. 'dtype': dtype,
  3115. 'value': None}
  3116. class Sort(PrimitiveWithInfer):
  3117. """
  3118. Sorts the elements of the input tensor along a given dimension in ascending order by value.
  3119. Args:
  3120. axis (int): The dimension to sort along. Default: -1.
  3121. descending (bool): Controls the sorting order. If descending is True then the elements
  3122. are sorted in descending order by value. Default: False.
  3123. Inputs:
  3124. - **x** (Tensor) - The input to sort, with float16 or float32 data type.
  3125. Outputs:
  3126. - **y1** (Tensor) - A tensor whose values are the sorted values, with the same shape and data type as input.
  3127. - **y2** (Tensor) - The indices of the elements in the original input tensor. Data type is int32.
  3128. Examples:
  3129. >>> x = Tensor(np.array([[8, 2, 1], [5, 9, 3], [4, 6, 7]]), mindspore.float16)
  3130. >>> sort = P.Sort()
  3131. >>> sort(x)
  3132. >>> ([[1.0, 2.0, 8.0], [3.0, 5.0, 9.0], [4.0, 6.0 ,7.0]],
  3133. [[2, 1, 0], [2, 0, 1], [0, 1, 2]])
  3134. """
  3135. @prim_attr_register
  3136. def __init__(self, axis=-1, descending=False):
  3137. """Initialize Sort"""
  3138. self.axis = validator.check_value_type("axis", axis, [int], self.name)
  3139. self.descending = validator.check_value_type("descending", descending, [bool], self.name)
  3140. def infer_shape(self, x_shape):
  3141. return x_shape, x_shape
  3142. def infer_dtype(self, x_dtype):
  3143. validator.check_tensor_type_same({"x_dtype": x_dtype}, [mstype.float32, mstype.float16], self.name)
  3144. return x_dtype, mstype.tensor_type(mstype.int32)
  3145. class EmbeddingLookup(PrimitiveWithInfer):
  3146. """
  3147. Returns a slice of input tensor based on the specified indices.
  3148. This Primitive has the similar functionality as GatherV2 operating on `axis = 0`, but has one more inputs:
  3149. `offset`.
  3150. Inputs:
  3151. - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  3152. This represents a Tensor slice, instead of the entire Tensor. Currently, the dimension is restricted to be 2.
  3153. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`.
  3154. Specifies the indices of elements of the original Tensor. Values can be out of range of `input_params`,
  3155. and the exceeding part will be filled with 0 in the output.
  3156. - **offset** (int) - Specifies the offset value of this `input_params` slice. Thus the real indices
  3157. are equal to `input_indices` minus `offset`.
  3158. Outputs:
  3159. Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`.
  3160. Examples:
  3161. >>> input_params = Tensor(np.array([[8, 9], [10, 11], [12, 13], [14, 15]]), mindspore.float32)
  3162. >>> input_indices = Tensor(np.array([[5, 2], [8, 5]]), mindspore.int32)
  3163. >>> offset = 4
  3164. >>> out = P.EmbeddingLookup()(input_params, input_indices, offset)
  3165. [[[10, 11], [0 ,0]], [[0, 0], [10, 11]]]
  3166. """
  3167. @prim_attr_register
  3168. def __init__(self):
  3169. """Initialize index_select"""
  3170. self.__setattr_flag__ = True
  3171. self.init_prim_io_names(inputs=['params', 'indices', 'offset'],
  3172. outputs=['output'])
  3173. def __infer__(self, params, indices, offset):
  3174. validator.check_subclass("params", params['dtype'], mstype.tensor, self.name)
  3175. validator.check_tensor_type_same({"indices": indices['dtype']}, mstype.int_type, self.name)
  3176. validator.check_subclass("offset", offset['dtype'], mstype.int_, self.name)
  3177. params_shp = params['shape']
  3178. if len(params_shp) != 2:
  3179. raise ValueError("The dimension of 'params' in EmbeddingLookup must be 2, but got %d." % len(params_shp))
  3180. out_shape = indices['shape'] + params_shp[1:]
  3181. out = {'shape': out_shape,
  3182. 'dtype': params['dtype'],
  3183. 'value': None}
  3184. return out
  3185. class GatherD(PrimitiveWithInfer):
  3186. """
  3187. Gathers values along an axis specified by dim.
  3188. Inputs:
  3189. - **x** (Tensor) - The source tensor.
  3190. - **dim** (int) - The axis along which to index. It must be int32. Only constant value is allowed.
  3191. - **index** (Tensor) - The indices of elements to gather. It can be one of the following data types:
  3192. int32, int64.
  3193. Outputs:
  3194. Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`.
  3195. Examples:
  3196. >>> x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.int32)
  3197. >>> index = Tensor(np.array([[0, 0], [1, 0]]), mindspore.int32)
  3198. >>> dim = 1
  3199. >>> out = P.GatherD()(x, dim, index)
  3200. [[1, 1], [4, 3]]
  3201. """
  3202. @prim_attr_register
  3203. def __init__(self):
  3204. """Initialize GatherD"""
  3205. def __infer__(self, x, dim, index):
  3206. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  3207. validator.check_tensor_type_same({"index": index['dtype']}, [mstype.int32, mstype.int64], self.name)
  3208. validator.check_subclass("dim", dim['dtype'], mstype.int32, self.name)
  3209. x_shp = x['shape']
  3210. idx_shp = index['shape']
  3211. x_rank = len(x_shp)
  3212. idx_rank = len(idx_shp)
  3213. validator.check("x_rank, idx_rank", x_rank, "expected", idx_rank, Rel.EQ, self.name)
  3214. dim_v = dim['value']
  3215. validator.check("dim value", dim_v, "expected", 0, Rel.GE, self.name)
  3216. validator.check("dim value", dim_v, "expected", x_rank, Rel.LT, self.name)
  3217. for i in range(x_rank):
  3218. if i == dim_v:
  3219. continue
  3220. validator.check("x_shp[{0}], idx_shp[{0}]".format(i), x_shp[i], "expected", idx_shp[i], Rel.EQ, self.name)
  3221. out = {'shape': index['shape'],
  3222. 'dtype': x['dtype'],
  3223. 'value': None}
  3224. return out
  3225. class Identity(PrimitiveWithInfer):
  3226. """
  3227. Returns a Tensor with the same shape and contents as input.
  3228. Inputs:
  3229. - **x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  3230. Outputs:
  3231. Tensor, the shape of tensor is the same as `input_x`, :math:`(x_1, x_2, ..., x_R)`.
  3232. Examples:
  3233. >>> x = Tensor(np.array([1, 2, 3, 4]), mindspore.int64)
  3234. >>> y = P.Identity()(x)
  3235. [1, 2, 3, 4]
  3236. """
  3237. @prim_attr_register
  3238. def __init__(self):
  3239. """Initialize identity"""
  3240. def __infer__(self, x):
  3241. out = {'shape': x['shape'],
  3242. 'dtype': x['dtype'],
  3243. 'value': None}
  3244. return out