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 208 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
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
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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244
  1. # coding: utf-8
  2. # Copyright 2020-2021 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 mindspore import log as logger
  23. from mindspore.common.initializer import Zero
  24. from .._utils import get_concat_offset
  25. from ..operations.math_ops import _infer_shape_reduce
  26. from ..primitive import Primitive, PrimitiveWithInfer, PrimitiveWithCheck, prim_attr_register, _run_op
  27. from .. import signature as sig
  28. from ..._checkparam import Rel
  29. from ..._checkparam import Validator as validator
  30. from ...common import dtype as mstype
  31. from ...common._decorator import deprecated
  32. from ...common.parameter import Parameter
  33. from ...common.tensor import Tensor
  34. class _ScatterOp(PrimitiveWithInfer):
  35. """
  36. Defines Scatter operators
  37. """
  38. __mindspore_signature__ = (
  39. sig.make_sig('x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
  40. sig.make_sig('indices', dtype=sig.sig_dtype.T1),
  41. sig.make_sig('updates', dtype=sig.sig_dtype.T)
  42. )
  43. def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name):
  44. if indices_shape != [-1] and updates_shape and updates_shape != indices_shape + x_shape[1:]:
  45. raise ValueError(f"For '{prim_name}', "
  46. f"updates_shape = indices_shape + x_shape[1:], but got x_shape: {x_shape}, "
  47. f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.")
  48. @prim_attr_register
  49. def __init__(self, use_locking=False):
  50. """Initialize _ScatterOp"""
  51. validator.check_value_type('use_locking', use_locking, [bool], self.name)
  52. self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y'])
  53. self.add_prim_attr('side_effect_mem', True)
  54. def infer_shape(self, x_shape, indices_shape, updates_shape):
  55. self._check_scatter_shape(x_shape, indices_shape, updates_shape, self.name)
  56. return x_shape
  57. def infer_dtype(self, x_dtype, indices_dtype, updates_dtype):
  58. validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32], self.name)
  59. args = {"x": x_dtype, "updates": updates_dtype}
  60. validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name)
  61. return x_dtype
  62. class _ScatterOp_Dynamic(PrimitiveWithCheck):
  63. """
  64. Defines Scatter operators with dynamic shape
  65. """
  66. __mindspore_signature__ = (
  67. sig.make_sig('x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
  68. sig.make_sig('indices', dtype=sig.sig_dtype.T1),
  69. sig.make_sig('updates', dtype=sig.sig_dtype.T)
  70. )
  71. def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name):
  72. # x_shape cannot be dynamic
  73. if np.any(np.array(x_shape) == -1):
  74. raise ValueError(f"x does not support dynamic shape")
  75. # support indices and updates dynamic
  76. if np.any(np.array(indices_shape) == -1) or np.any(np.array(updates_shape) == -1):
  77. pass
  78. elif indices_shape != [-1] and updates_shape and updates_shape != indices_shape + x_shape[1:]:
  79. raise ValueError(f"For '{prim_name}', "
  80. f"updates_shape = indices_shape + x_shape[1:], but got x_shape: {x_shape}, "
  81. f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.")
  82. @prim_attr_register
  83. def __init__(self, use_locking=False):
  84. """Initialize _ScatterOp_Dynamic"""
  85. validator.check_value_type('use_locking', use_locking, [bool], self.name)
  86. self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y'])
  87. self.add_prim_attr('side_effect_mem', True)
  88. def check_shape(self, x_shape, indices_shape, updates_shape):
  89. self._check_scatter_shape(x_shape, indices_shape, updates_shape, self.name)
  90. def check_dtype(self, x_dtype, indices_dtype, updates_dtype):
  91. validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32], self.name)
  92. args = {"x": x_dtype, "updates": updates_dtype}
  93. validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name)
  94. class _ScatterNdOp(_ScatterOp):
  95. """
  96. Defines _ScatterNd operators
  97. """
  98. def _check_scatter_shape(self, x_shape, indices_shape, updates_shape, prim_name):
  99. validator.check('the dimension of x', len(x_shape),
  100. 'the dimension of indices', indices_shape[-1], Rel.GE)
  101. if indices_shape[:-1] + x_shape[indices_shape[-1]:] != updates_shape:
  102. raise ValueError(f"For '{prim_name}', updates_shape = "
  103. f"indices_shape[:-1] + x_shape[indices_shape[-1]:], but got x_shape: {x_shape}, "
  104. f"indices_shape: {indices_shape}, updates_shape: {updates_shape}.")
  105. def _check_infer_attr_reduce(axis, keep_dims, prim_name):
  106. validator.check_value_type('keep_dims', keep_dims, [bool], prim_name)
  107. validator.check_value_type('axis', axis, [int, tuple], prim_name)
  108. if isinstance(axis, tuple):
  109. for index, value in enumerate(axis):
  110. validator.check_value_type('axis[%d]' % index, value, [int], prim_name)
  111. class ExpandDims(PrimitiveWithInfer):
  112. """
  113. Adds an additional dimension at the given axis.
  114. Note:
  115. If the specified axis is a negative number, the index is counted
  116. backward from the end and starts at 1.
  117. Inputs:
  118. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  119. - **axis** (int) - Specifies the dimension index at which to expand
  120. the shape of `input_x`. The value of axis must be in the range
  121. `[-input_x.ndim-1, input_x.ndim]`. Only constant value is allowed.
  122. Outputs:
  123. Tensor, the shape of tensor is :math:`(1, x_1, x_2, ..., x_R)` if the
  124. value of `axis` is 0. It has the same type as `input_x`.
  125. Raises:
  126. ValueError: If `axis` is not an int or not in the valid range.
  127. Supported Platforms:
  128. ``Ascend`` ``GPU`` ``CPU``
  129. Examples:
  130. >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  131. >>> expand_dims = ops.ExpandDims()
  132. >>> output = expand_dims(input_tensor, 0)
  133. >>> print(output)
  134. [[[2. 2.]
  135. [2. 2.]]]
  136. """
  137. @prim_attr_register
  138. def __init__(self):
  139. """Initialize ExpandDims"""
  140. self.init_prim_io_names(inputs=['x', 'axis'], outputs=['output'])
  141. def __infer__(self, x, axis):
  142. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  143. x_shape = list(x['shape'])
  144. axis_v = axis['value']
  145. rank = len(x_shape)
  146. validator.check_int_range(axis_v, -rank - 1, rank, Rel.INC_BOTH, 'axis', self.name)
  147. value = None
  148. if x['value'] is not None:
  149. value = x['value'].asnumpy()
  150. value = np.expand_dims(value, axis_v)
  151. value = Tensor(value)
  152. if axis_v < 0:
  153. axis_v = rank + 1 + axis_v
  154. x_shape.insert(axis_v, 1)
  155. out = {'shape': x_shape,
  156. 'dtype': x['dtype'],
  157. 'value': value}
  158. if 'min_shape' in x and 'max_shape' in x:
  159. out['min_shape'] = x['min_shape']
  160. out['min_shape'].insert(axis_v, 1)
  161. out['max_shape'] = x['max_shape']
  162. out['max_shape'].insert(axis_v, 1)
  163. return out
  164. class DType(Primitive):
  165. """
  166. Returns the data type of the input tensor as mindspore.dtype.
  167. Inputs:
  168. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  169. Outputs:
  170. mindspore.dtype, the data type of a tensor.
  171. Raises:
  172. TypeError: If `input_x` is not a Tensor.
  173. Supported Platforms:
  174. ``Ascend`` ``GPU`` ``CPU``
  175. Examples:
  176. >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  177. >>> output = ops.DType()(input_tensor)
  178. >>> print(output)
  179. Float32
  180. """
  181. @prim_attr_register
  182. def __init__(self):
  183. """Initialize DType"""
  184. class SameTypeShape(PrimitiveWithInfer):
  185. """
  186. Checks whether the data type and shape of two tensors are the same.
  187. Inputs:
  188. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  189. - **input_y** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_S)`.
  190. Outputs:
  191. Tensor, the shape of tensor is :math:`(x_1, x_2, ..., x_R)`,
  192. if data type and shape of `input_x` and `input_y` are the same.
  193. Raises:
  194. TypeError: If the data types of `input_x` and `input_y` are not the same.
  195. ValueError: If the shapes of `input_x` and `input_y` are not the same.
  196. Supported Platforms:
  197. ``Ascend`` ``GPU`` ``CPU``
  198. Examples:
  199. >>> input_x = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  200. >>> input_y = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  201. >>> output = ops.SameTypeShape()(input_x, input_y)
  202. >>> print(output)
  203. [[2. 2.]
  204. [2. 2.]]
  205. """
  206. @prim_attr_register
  207. def __init__(self):
  208. """Initialize Same"""
  209. def __call__(self, x, y):
  210. """run in PyNative mode"""
  211. validator.check_value_type('x', x, Tensor, self.name)
  212. validator.check_value_type('y', y, Tensor, self.name)
  213. validator.check('x dtype', x.dtype, 'y dtype', y.dtype, Rel.EQ, self.name, TypeError)
  214. validator.check('x shape', x.shape, 'y shape', y.shape, Rel.EQ, self.name)
  215. return x
  216. def __infer__(self, x, y):
  217. validator.check_subclass('x', x['dtype'], mstype.tensor, self.name)
  218. validator.check_subclass('y', y['dtype'], mstype.tensor, self.name)
  219. validator.check('x dtype', x['dtype'], 'y dtype', y['dtype'], Rel.EQ, self.name, TypeError)
  220. validator.check('x shape', x['shape'], 'y shape', y['shape'], Rel.EQ, self.name)
  221. return x
  222. class Cast(PrimitiveWithInfer):
  223. """
  224. Returns a tensor with the new specified data type.
  225. Inputs:
  226. - **input_x** (Union[Tensor, Number]) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  227. The tensor to be cast.
  228. - **type** (dtype.Number) - The valid data type of the output tensor. Only constant value is allowed.
  229. Outputs:
  230. Tensor, the shape of tensor is the same as `input_x`, :math:`(x_1, x_2, ..., x_R)`.
  231. Raises:
  232. TypeError: If `input_x` is neither Tensor nor Number.
  233. TypeError: If `type` is not a Number.
  234. Supported Platforms:
  235. ``Ascend`` ``GPU`` ``CPU``
  236. Examples:
  237. >>> input_np = np.random.randn(2, 3, 4, 5).astype(np.float32)
  238. >>> input_x = Tensor(input_np)
  239. >>> type_dst = mindspore.int32
  240. >>> cast = ops.Cast()
  241. >>> output = cast(input_x, type_dst)
  242. >>> print(output.dtype)
  243. Int32
  244. >>> print(output.shape)
  245. (2, 3, 4, 5)
  246. """
  247. @prim_attr_register
  248. def __init__(self):
  249. # if primitive need setattr in __infer__ need add this flag
  250. """Initialize Cast"""
  251. self.init_prim_io_names(inputs=['x', 'dst_type'], outputs=['output'])
  252. def check_elim(self, x, dtype):
  253. if isinstance(x, (Tensor, numbers.Number, Parameter)):
  254. if isinstance(x, Parameter):
  255. data = x.data
  256. if data.dtype == dtype:
  257. return (True, x)
  258. if isinstance(x, Tensor) and x.dtype == dtype:
  259. x = Tensor(x)
  260. x.set_cast_dtype()
  261. return (True, x)
  262. if isinstance(x, numbers.Number):
  263. return (True, Tensor(x, dtype=dtype))
  264. return (False, None)
  265. def __infer__(self, x, t):
  266. src_type = x['dtype']
  267. dst_type = t['value']
  268. validator.check_subclass("input_x", src_type, [mstype.tensor, mstype.number], self.name)
  269. validator.check_subclass("type", dst_type, mstype.number, self.name)
  270. if isinstance(src_type, type(mstype.tensor)):
  271. src_type = x['dtype'].element_type()
  272. if isinstance(dst_type, type(mstype.tensor)):
  273. dst_type = dst_type.element_type()
  274. self.add_prim_attr('DstT', dst_type)
  275. self.add_prim_attr('SrcT', src_type)
  276. self.add_prim_attr('dst_type', dst_type)
  277. value = None
  278. if x['value'] is not None:
  279. np_dst_type = mstype.dtype_to_nptype(dst_type)
  280. if isinstance(x['value'], (int, float)):
  281. value = Tensor(np.array(x['value']).astype(np_dst_type))
  282. else:
  283. value = Tensor(x['value'].asnumpy().astype(np_dst_type))
  284. out = {'shape': x['shape'],
  285. 'dtype': mstype.tensor_type(t['value']),
  286. 'value': value}
  287. if 'min_shape' in x and 'max_shape' in x:
  288. out['min_shape'] = x['min_shape']
  289. out['max_shape'] = x['max_shape']
  290. return out
  291. class IsSubClass(PrimitiveWithInfer):
  292. """
  293. Checks whether this type is a sub-class of another type.
  294. Inputs:
  295. - **sub_type** (mindspore.dtype) - The type to be checked. Only constant value is allowed.
  296. - **type_** (mindspore.dtype) - The target type. Only constant value is allowed.
  297. Outputs:
  298. bool, the check result.
  299. Raises:
  300. TypeError: If `sub_type` or `type_` is not a Type.
  301. Supported Platforms:
  302. ``Ascend`` ``GPU`` ``CPU``
  303. Examples:
  304. >>> output = ops.IsSubClass()(mindspore.int32, mindspore.intc)
  305. >>> print(output)
  306. True
  307. """
  308. @prim_attr_register
  309. def __init__(self):
  310. pass
  311. def __infer__(self, sub_type, type_):
  312. sub_type_t = sub_type['value']
  313. type_v = type_['value']
  314. validator.check_value_type("sub_type", sub_type_t, [mstype.Type], self.name)
  315. validator.check_value_type("type_", type_v, [mstype.Type], self.name)
  316. value = mstype.issubclass_(sub_type_t, type_v)
  317. out = {'shape': (),
  318. 'dtype': mstype.type_type,
  319. 'value': value}
  320. return out
  321. class IsInstance(PrimitiveWithInfer):
  322. """
  323. Checks whether an object is an instance of a target type.
  324. Inputs:
  325. - **inst** (Any Object) - The instance to be checked. Only constant value is allowed.
  326. - **type_** (mindspore.dtype) - The target type. Only constant value is allowed.
  327. Outputs:
  328. bool, the check result.
  329. Raises:
  330. TypeError: If `type_` is not a Type.
  331. Supported Platforms:
  332. ``Ascend`` ``GPU`` ``CPU``
  333. Examples:
  334. >>> a = 1
  335. >>> output = ops.IsInstance()(a, mindspore.int32)
  336. >>> print(output)
  337. False
  338. """
  339. @prim_attr_register
  340. def __init__(self):
  341. pass
  342. def __infer__(self, inst, type_):
  343. sub_type_t = inst['dtype']
  344. type_v = type_['value']
  345. validator.check_value_type("type_", type_v, [mstype.Type], self.name)
  346. if type_v == mstype.list_:
  347. value = isinstance(sub_type_t, list)
  348. elif type_v == mstype.tuple_:
  349. value = isinstance(sub_type_t, tuple)
  350. else:
  351. value = mstype.issubclass_(sub_type_t, type_v)
  352. out = {'shape': (),
  353. 'dtype': mstype.type_type,
  354. 'value': value}
  355. return out
  356. class Reshape(PrimitiveWithInfer):
  357. """
  358. Reshapes the input tensor with the same values based on a given shape tuple.
  359. Inputs:
  360. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  361. - **input_shape** (tuple[int]) - The input tuple is constructed by multiple
  362. integers, i.e., :math:`(y_1, y_2, ..., y_S)`. Only constant value is allowed.
  363. Outputs:
  364. Tensor, the shape of tensor is :math:`(y_1, y_2, ..., y_S)`.
  365. Raises:
  366. ValueError: Given a shape tuple, if it has several -1; or if the product
  367. of its elements is less than or equal to 0 or cannot be divided by the product
  368. of the input tensor shape; or if it does not match the input's array size.
  369. Supported Platforms:
  370. ``Ascend`` ``GPU`` ``CPU``
  371. Examples:
  372. >>> input_tensor = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  373. >>> reshape = ops.Reshape()
  374. >>> output = reshape(input_tensor, (3, 2))
  375. >>> print(output)
  376. [[-0.1 0.3]
  377. [ 3.6 0.4]
  378. [ 0.5 -3.2]]
  379. """
  380. @prim_attr_register
  381. def __init__(self):
  382. """Initialize Reshape"""
  383. self.init_prim_io_names(inputs=['tensor', 'shape'], outputs=['output'])
  384. def __infer__(self, x, shape):
  385. shape_v = shape['value']
  386. x_shp = x['shape']
  387. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  388. validator.check_value_type("shape", shape_v, [tuple], self.name)
  389. shape_v = list(shape_v)
  390. neg_index = -1
  391. dim_prod = 1
  392. for i, shp_i in enumerate(shape_v):
  393. validator.check_value_type("shape[%d]" % i, shp_i, [int], self.name)
  394. if shp_i == -1:
  395. if neg_index != -1:
  396. raise ValueError(f'The shape can only has one -1 at most, but {shape_v}.')
  397. neg_index = i
  398. else:
  399. dim_prod *= shp_i
  400. arr_prod = np.prod(x_shp)
  401. if arr_prod <= 0:
  402. if 'max_shape' in x:
  403. x_max_shape = x['max_shape']
  404. else:
  405. x_max_shape = x['shape']
  406. if 'min_shape' in x:
  407. x_min_shape = x['min_shape']
  408. else:
  409. x_min_shape = x['shape']
  410. max_arr_prod = np.prod(x_max_shape)
  411. min_arr_prod = np.prod(x_min_shape)
  412. max_shape = list(shape_v)
  413. min_shape = list(shape_v)
  414. if neg_index != -1:
  415. max_shape[neg_index] = int(max_arr_prod / dim_prod)
  416. min_shape[neg_index] = int(min_arr_prod / dim_prod)
  417. else:
  418. raise ValueError(f'For dynamic shape, Reshape must have neg index')
  419. out = {'shape': shape['value'],
  420. 'dtype': x['dtype'],
  421. 'value': None,
  422. 'max_shape': tuple(max_shape),
  423. 'min_shape': tuple(min_shape)}
  424. else:
  425. if dim_prod <= 0 or arr_prod % dim_prod != 0:
  426. raise ValueError(f'For \'{self.name}\' input_x\'s shape is {x_shp}, input_shape\'s value is {shape_v}.'
  427. f'The product of input_x\'s shape should > 0, '
  428. f'and can be divided by product of input_shape, but '
  429. f'product of input_x\'s shape is {arr_prod}, product of input_shape is {dim_prod}.')
  430. if neg_index != -1:
  431. shape_v[neg_index] = int(arr_prod / dim_prod)
  432. dim_prod *= shape_v[neg_index]
  433. if dim_prod != arr_prod:
  434. raise ValueError(f'For \'{self.name}\' input_x\'s shape is {x_shp}, input_shape\'s value is {shape_v}.'
  435. f'The product of input_x\'s shape should be equal to product of input_shape, but '
  436. f'product of input_x\'s shape is {arr_prod}, product of input_shape is {dim_prod}.')
  437. value = None
  438. if x['value'] is not None:
  439. value = Tensor(x['value'].asnumpy().reshape(shape_v))
  440. out = {'shape': tuple(shape_v),
  441. 'dtype': x['dtype'],
  442. 'value': value}
  443. return out
  444. class Shape(Primitive):
  445. """
  446. Returns the shape of the input tensor.
  447. Inputs:
  448. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  449. Outputs:
  450. tuple[int], the output tuple is constructed by multiple integers,
  451. :math:`(x_1, x_2, ..., x_R)`.
  452. Raises:
  453. TypeError: If `input_x` is not a Tensor.
  454. Supported Platforms:
  455. ``Ascend`` ``GPU`` ``CPU``
  456. Examples:
  457. >>> input_tensor = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32)
  458. >>> shape = ops.Shape()
  459. >>> output = shape(input_tensor)
  460. >>> print(output)
  461. (3, 2, 1)
  462. """
  463. @prim_attr_register
  464. def __init__(self):
  465. """Initialize Shape"""
  466. class DynamicShape(Primitive):
  467. """
  468. Returns the shape of the input tensor.
  469. Inputs:
  470. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  471. Outputs:
  472. Tensor[int], 1-dim Tensor of type int32
  473. Raises:
  474. TypeError: If `input_x` is not a Tensor.
  475. Supported Platforms:
  476. ``Ascend`` ``GPU`` ``CPU``
  477. Examples:
  478. >>> input_tensor = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32)
  479. >>> shape = ops.DynamicShape()
  480. >>> output = shape(input_tensor)
  481. >>> print(output)
  482. [3 2 1]
  483. """
  484. @prim_attr_register
  485. def __init__(self):
  486. """init Shape"""
  487. self.init_prim_io_names(inputs=['tensor'], outputs=['output'])
  488. self.add_prim_attr('is_dynamic_shape', True)
  489. class Squeeze(PrimitiveWithInfer):
  490. """
  491. Returns a tensor with the same type but dimensions of 1 are removed based on `axis`.
  492. If `axis` is specified, it will remove the dimensions of size 1 in the given `axis`.
  493. It `axis` is None, it will remove all the dimensions of size 1.
  494. Note:
  495. The dimension index starts at 0 and must be in the range `[-input.ndim, input.ndim]`.
  496. Args:
  497. axis (Union[int, tuple(int)]): Specifies the dimension indexes of shape to be removed, which will remove
  498. all the dimensions that are equal to 1. If specified, it must be int32 or int64.
  499. Default: (), an empty tuple.
  500. Inputs:
  501. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  502. Outputs:
  503. Tensor, the shape of tensor is :math:`(x_1, x_2, ..., x_S)`.
  504. Raises:
  505. TypeError: If `axis` is neither an int nor tuple.
  506. TypeError: If `axis` is a tuple whose elements are not all int.
  507. ValueError: If the corresponding dimension of the specified axis does not equal to 1.
  508. Supported Platforms:
  509. ``Ascend`` ``GPU`` ``CPU``
  510. Examples:
  511. >>> input_tensor = Tensor(np.ones(shape=[3, 2, 1]), mindspore.float32)
  512. >>> squeeze = ops.Squeeze(2)
  513. >>> output = squeeze(input_tensor)
  514. >>> print(output)
  515. [[1. 1.]
  516. [1. 1.]
  517. [1. 1.]]
  518. """
  519. @prim_attr_register
  520. def __init__(self, axis=()):
  521. """Initialize Squeeze"""
  522. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  523. validator.check_value_type('axis', axis, [int, tuple], self.name)
  524. if isinstance(axis, tuple):
  525. for idx, item in enumerate(axis):
  526. validator.check_value_type("axis[%d]" % idx, item, [int], self.name)
  527. else:
  528. self.axis = (axis,)
  529. self.add_prim_attr("axis", (axis,))
  530. def infer_shape(self, x_shape):
  531. axis = self.axis
  532. x_shape = list(x_shape)
  533. ndim = len(x_shape)
  534. if not axis:
  535. ret = [d for d in x_shape if d != 1]
  536. else:
  537. for a in axis:
  538. validator.check_int_range(a, -ndim, ndim - 1, Rel.INC_BOTH, 'axis or its elements', self.name)
  539. if x_shape[a] != 1:
  540. raise ValueError('Cannot select an axis to squeeze out which has size not equal to one.')
  541. ret = [x_shape[i] for i in range(ndim) if not (i in axis or (i - ndim) in axis)]
  542. return ret
  543. def infer_dtype(self, x_dtype):
  544. validator.check_subclass("x", x_dtype, mstype.tensor, self.name)
  545. return x_dtype
  546. class Transpose(PrimitiveWithInfer):
  547. """
  548. Permutes the dimensions of the input tensor according to input permutation.
  549. Inputs:
  550. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  551. - **input_perm** (tuple[int]) - The permutation to be converted. The input tuple is constructed by multiple
  552. indexes. The length of `input_perm` and the shape of `input_x` must be the same. Only constant value is
  553. allowed. Must be in the range [0, rank(input_x)).
  554. Outputs:
  555. Tensor, the type of output tensor is the same as `input_x` and the shape of output tensor is decided by the
  556. shape of `input_x` and the value of `input_perm`.
  557. Raises:
  558. TypeError: If `input_perm` is not a tuple.
  559. ValueError: If length of shape of `input_x` is not equal to length of shape of `input_perm`.
  560. Supported Platforms:
  561. ``Ascend`` ``GPU`` ``CPU``
  562. Examples:
  563. >>> input_tensor = Tensor(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]), mindspore.float32)
  564. >>> perm = (0, 2, 1)
  565. >>> transpose = ops.Transpose()
  566. >>> output = transpose(input_tensor, perm)
  567. >>> print(output)
  568. [[[ 1. 4.]
  569. [ 2. 5.]
  570. [ 3. 6.]]
  571. [[ 7. 10.]
  572. [ 8. 11.]
  573. [ 9. 12.]]]
  574. """
  575. @prim_attr_register
  576. def __init__(self):
  577. """Initialize Transpose"""
  578. self.init_prim_io_names(inputs=['x', 'perm'], outputs=['output'])
  579. def __infer__(self, x, perm):
  580. x_shape = x['shape']
  581. p_value = perm['value']
  582. x_type = x['dtype']
  583. validator.check_value_type("p_value", p_value, [tuple], self.name)
  584. validator.check_subclass("x_type", x_type, mstype.tensor, self.name)
  585. if len(x_shape) != len(p_value):
  586. raise ValueError('The dimension of x and perm must be equal.')
  587. tmp = list(p_value)
  588. for i, dim in enumerate(p_value):
  589. validator.check_int(dim, 0, Rel.GE, f'perm[{i}]', self.name)
  590. validator.check_int(dim, len(p_value), Rel.LT, f'perm[{i}]', self.name)
  591. tmp.remove(dim)
  592. if dim in tmp:
  593. raise ValueError('The value of perm is wrong.')
  594. out_shapes = []
  595. for i in p_value:
  596. out_shapes.append(x_shape[i])
  597. out = {'shape': tuple(out_shapes),
  598. 'dtype': x['dtype'],
  599. 'value': None}
  600. if 'min_shape' in x and 'max_shape' in x:
  601. min_vec = []
  602. max_vec = []
  603. for i in p_value:
  604. min_vec.append(x['min_shape'][i])
  605. max_vec.append(x['max_shape'][i])
  606. out['min_shape'] = tuple(min_vec)
  607. out['max_shape'] = tuple(max_vec)
  608. return out
  609. class Unique(Primitive):
  610. """
  611. Returns the unique elements of input tensor and also return a tensor containing the index of each value of input
  612. tensor corresponding to the output unique tensor.
  613. The shape of Tensor `y` and Tensor `idx` is different in most cases, because Tensor `y` will be deduplicated,
  614. and the shape of Tensor `idx` is consistent with the input.
  615. To get the same shape between `idx` and `y`, please ref to 'UniqueWithPad' operator
  616. Inputs:
  617. - **x** (Tensor) - The input tensor.
  618. Outputs:
  619. Tuple, containing Tensor objects `(y, idx), `y` is a tensor with the
  620. same type as `x`, and contains the unique elements in `x`, sorted in
  621. ascending order. `idx` is a tensor containing indices of elements in
  622. the input corresponding to the output tensor.
  623. Raises:
  624. TypeError: If `x` is not a Tensor.
  625. Supported Platforms:
  626. ``Ascend`` ``GPU`` ``CPU``
  627. Examples:
  628. >>> x = Tensor(np.array([1, 2, 5, 2]), mindspore.int32)
  629. >>> output = ops.Unique()(x)
  630. >>> print(output)
  631. (Tensor(shape=[3], dtype=Int32, value= [1, 2, 5]), Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 1]))
  632. >>>
  633. >>> # note that for GPU, this operator must be wrapped inside a model, and executed in graph mode.
  634. >>> class UniqueNet(nn.Cell):
  635. ... def __init__(self):
  636. ... super(UniqueNet, self).__init__()
  637. ... self.unique_op = ops.Unique()
  638. ...
  639. ... def construct(self, x):
  640. ... output, indices = self.unique_op(x)
  641. ... return output, indices
  642. ...
  643. >>> x = Tensor(np.array([1, 2, 5, 2]), mindspore.int32)
  644. >>> net = UniqueNet()
  645. >>> output = net(x)
  646. >>> print(output)
  647. (Tensor(shape=[3], dtype=Int32, value= [1, 2, 5]), Tensor(shape=[4], dtype=Int32, value= [0, 1, 2, 1]))
  648. """
  649. @prim_attr_register
  650. def __init__(self):
  651. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  652. class Gather(Primitive):
  653. r"""
  654. Returns a slice of the input tensor based on the specified indices and axis.
  655. Slices the input tensor base on the indices at specified axis. See the following example for more clear.
  656. Inputs:
  657. - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  658. The original Tensor.
  659. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`.
  660. Specifies the indices of elements of the original Tensor. Must be in the range
  661. `[0, input_param.shape[axis])`.
  662. - **axis** (int) - Specifies the dimension index to gather indices.
  663. Outputs:
  664. Tensor, the shape of tensor is
  665. :math:`input\_params.shape[:axis] + input\_indices.shape + input\_params.shape[axis + 1:]`.
  666. Raises:
  667. TypeError: If `axis` is not an int.
  668. Supported Platforms:
  669. ``Ascend`` ``GPU`` ``CPU``
  670. Examples:
  671. >>> input_params = Tensor(np.array([[1, 2, 7, 42], [3, 4, 54, 22], [2, 2, 55, 3]]), mindspore.float32)
  672. >>> input_indices = Tensor(np.array([1, 2]), mindspore.int32)
  673. >>> axis = 1
  674. >>> output = ops.Gather()(input_params, input_indices, axis)
  675. >>> print(output)
  676. [[ 2. 7.]
  677. [ 4. 54.]
  678. [ 2. 55.]]
  679. >>> axis = 0
  680. >>> output = ops.Gather()(input_params, input_indices, axis)
  681. >>> print(output)
  682. [[3. 4. 54. 22.]
  683. [2. 2. 55. 3.]]
  684. """
  685. @prim_attr_register
  686. def __init__(self):
  687. """Initialize index_select"""
  688. self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output'])
  689. class GatherV2(PrimitiveWithCheck):
  690. """
  691. Same as operator Gather. GatherV2 will be deprecated in the future.
  692. Please use Gather instead.
  693. """
  694. # deprecate_new_name = "Gather"
  695. @deprecated("1.1", "Gather", True)
  696. @prim_attr_register
  697. def __init__(self):
  698. """Initialize index_select"""
  699. self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output'])
  700. def __check__(self, params, indices, axis):
  701. validator.check_subclass("params", params['dtype'], mstype.tensor, self.name)
  702. validator.check_tensor_dtype_valid("indices", indices['dtype'], mstype.int_type, self.name)
  703. validator.check_subclass("axis", axis['dtype'], [mstype.number], self.name)
  704. axis_v = axis['value']
  705. validator.check_value_type('axis', axis_v, [int], self.name)
  706. rank = len(params['shape'])
  707. validator.check_int_range(axis_v, -rank, rank, Rel.INC_LEFT, "axis", self.name)
  708. class SparseGatherV2(PrimitiveWithCheck):
  709. """
  710. Returns a slice of input tensor based on the specified indices and axis.
  711. Inputs:
  712. - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  713. The original Tensor.
  714. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`.
  715. Specifies the indices of elements of the original Tensor, must be in the range
  716. `[0, input_param.shape[axis])`.
  717. - **axis** (int) - Specifies the dimension index to gather indices.
  718. Outputs:
  719. Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`.
  720. Raises:
  721. TypeError: If `axis` is not an int.
  722. Supported Platforms:
  723. ``Ascend`` ``GPU``
  724. Examples:
  725. >>> input_params = Tensor(np.array([[1, 2, 7, 42], [3, 4, 54, 22], [2, 2, 55, 3]]), mindspore.float32)
  726. >>> input_indices = Tensor(np.array([1, 2]), mindspore.int32)
  727. >>> axis = 1
  728. >>> out = ops.SparseGatherV2()(input_params, input_indices, axis)
  729. >>> print(out)
  730. [[2. 7.]
  731. [4. 54.]
  732. [2. 55.]]
  733. """
  734. @prim_attr_register
  735. def __init__(self):
  736. """Initialize index_select"""
  737. self.init_prim_io_names(inputs=['params', 'indices', 'axis'], outputs=['output'])
  738. def __check__(self, params, indices, axis):
  739. validator.check_subclass("params", params['dtype'], mstype.tensor, self.name)
  740. validator.check_tensor_dtype_valid("indices", indices['dtype'], mstype.int_type, self.name)
  741. validator.check_subclass("axis", axis['dtype'], [mstype.number], self.name)
  742. axis_v = axis['value']
  743. validator.check_value_type('axis', axis_v, [int], self.name)
  744. rank = len(params['shape'])
  745. validator.check_int_range(axis_v, -rank, rank, Rel.INC_LEFT, "axis", self.name)
  746. class Padding(PrimitiveWithInfer):
  747. """
  748. Extends the last dimension of the input tensor from 1 to pad_dim_size, by filling with 0.
  749. Args:
  750. pad_dim_size (int): The value of the last dimension of x to be extended, which must be positive.
  751. Inputs:
  752. - **x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`. The rank of x must be at least 2.
  753. The last dimension of x must be 1.
  754. Outputs:
  755. Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`.
  756. Raises:
  757. TypeError: If `pad_dim_size` is not an int.
  758. ValueError: If `pad_dim_size` is less than 1.
  759. Supported Platforms:
  760. ``Ascend``
  761. Examples:
  762. >>> x = Tensor(np.array([[8], [10]]), mindspore.float32)
  763. >>> pad_dim_size = 4
  764. >>> output = ops.Padding(pad_dim_size)(x)
  765. >>> print(output)
  766. [[ 8. 0. 0. 0.]
  767. [10. 0. 0. 0.]]
  768. """
  769. @prim_attr_register
  770. def __init__(self, pad_dim_size=8):
  771. """Initialize padding"""
  772. validator.check_value_type("pad_dim_size", pad_dim_size, [int], self.name)
  773. validator.check_positive_int(pad_dim_size, "pad_dim_size", self.name)
  774. self.pad_dim_size = pad_dim_size
  775. def __infer__(self, x):
  776. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  777. x_shape = list(x['shape'])
  778. validator.check_int(len(x_shape), 1, Rel.GT, "rank of x", self.name)
  779. validator.check_int(x_shape[-1], 1, Rel.EQ, "last dim of x", self.name)
  780. out_shape = x_shape
  781. out_shape[-1] = self.pad_dim_size
  782. out = {'shape': out_shape,
  783. 'dtype': x['dtype'],
  784. 'value': None}
  785. return out
  786. class UniqueWithPad(PrimitiveWithInfer):
  787. """
  788. Returns unique elements and relative indexes in 1-D tensor, filled with padding num.
  789. The basic function is the same as the Unique operator, but the UniqueWithPad operator adds a Pad function.
  790. The returned tuple(`y`,`idx`) after the input Tensor `x` is processed by the unique operator,
  791. in which the shapes of `y` and `idx` are mostly not equal. Therefore, in order to solve the above situation,
  792. the UniqueWithPad operator will fill the `y` Tensor with the `pad_num` specified by the user
  793. to make it have the same shape as the Tensor `idx`.
  794. Inputs:
  795. - **x** (Tensor) - The tensor need to be unique. Must be 1-D vector with types: int32, int64.
  796. - **pad_num** (int) - Pad num.
  797. Outputs:
  798. tuple(Tensor), tuple of 2 tensors, y and idx.
  799. - y (Tensor) - The unique elements filled with pad_num, the shape and type same as x.
  800. - idx (Tensor) - The index of each value of x in the unique output y, the shape and type same as x.
  801. Raises:
  802. TypeError: If dtype of `x` is neither int32 nor int64.
  803. ValueError: If length of shape of `x` is not equal to 1.
  804. Supported Platforms:
  805. ``Ascend`` ``CPU``
  806. Examples:
  807. >>> x = Tensor(np.array([1, 1, 5, 5, 4, 4, 3, 3, 2, 2,]), mindspore.int32)
  808. >>> pad_num = 8
  809. >>> output = ops.UniqueWithPad()(x, pad_num)
  810. >>> print(output)
  811. (Tensor(shape=[10], dtype=Int32, value= [1, 5, 4, 3, 2, 8, 8, 8, 8, 8]),
  812. Tensor(shape=[10], dtype=Int32, value= [0, 0, 1, 1, 2, 2, 3, 3, 4, 4]))
  813. """
  814. @prim_attr_register
  815. def __init__(self):
  816. """init UniqueWithPad"""
  817. def __infer__(self, x, pad_num):
  818. validator.check_tensor_dtype_valid("x", x['dtype'], [mstype.int32, mstype.int64], self.name)
  819. validator.check_subclass("pad_num", pad_num['dtype'], [mstype.int32, mstype.int64], self.name)
  820. x_shape = list(x['shape'])
  821. validator.check("rank of x", len(x_shape), "expected", 1, Rel.EQ, self.name)
  822. out_shape = x_shape
  823. out = {'shape': (out_shape, out_shape),
  824. 'dtype': (x['dtype'], x['dtype']),
  825. 'value': None}
  826. return out
  827. class Split(PrimitiveWithCheck):
  828. """
  829. Splits the input tensor into output_num of tensors along the given axis and output numbers.
  830. The `input_x` tensor will be split into equally sized sub-tensors.
  831. This requires that `input_x.shape(axis)` is divisible by `output_num`.
  832. Args:
  833. axis (int): Index of the split position. Default: 0.
  834. output_num (int): The number of output tensors. Must be positive int. Default: 1.
  835. Inputs:
  836. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  837. Outputs:
  838. tuple[Tensor], the shape of each output tensor is the same, which is
  839. :math:`(y_1, y_2, ..., y_S)`.
  840. Raises:
  841. TypeError: If `axis` or `output_num` is not an int.
  842. ValueError: If `axis` is out of the range [-len(`input_x.shape`), len(`input_x.shape`)),
  843. or if the `output_num` is less than or equal to 0.
  844. Supported Platforms:
  845. ``Ascend`` ``GPU`` ``CPU``
  846. Examples:
  847. >>> split = ops.Split(1, 2)
  848. >>> x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]]), mindspore.int32)
  849. >>> output = split(x)
  850. >>> print(output)
  851. (Tensor(shape=[2, 2], dtype=Int32, value=
  852. [[1, 1],
  853. [2, 2]]), Tensor(shape=[2, 2], dtype=Int32, value=
  854. [[1, 1],
  855. [2, 2]]))
  856. """
  857. @prim_attr_register
  858. def __init__(self, axis=0, output_num=1):
  859. """Initialize Split"""
  860. validator.check_value_type("axis", axis, [int], self.name)
  861. validator.check_value_type("output_num", output_num, [int], self.name)
  862. validator.check_positive_int(output_num, "output_num", self.name)
  863. self.axis = axis
  864. self.output_num = output_num
  865. def __check__(self, x):
  866. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  867. x_shape = list(x['shape'])
  868. dim = len(x_shape)
  869. validator.check_int_range(self.axis, -dim, dim, Rel.INC_LEFT, 'axis value', self.name)
  870. if -1 not in x_shape:
  871. # only validate when shape fully known
  872. output_valid_check = x_shape[self.axis] % self.output_num
  873. if output_valid_check != 0:
  874. raise ValueError(f"x_shape[{self.axis}] {x_shape[self.axis]} must be divide exactly by"
  875. f" output_num {self.output_num}")
  876. size_splits = [x_shape[self.axis] // self.output_num] * self.output_num
  877. self.add_prim_attr('size_splits', size_splits)
  878. class Rank(PrimitiveWithInfer):
  879. """
  880. Returns the rank of a tensor.
  881. Returns a 0-D int32 Tensor representing the rank of input; the rank of a tensor
  882. is the number of indices required to uniquely select each element of the tensor.
  883. Inputs:
  884. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  885. Outputs:
  886. Tensor. 0-D int32 Tensor representing the rank of input, i.e., :math:`R`.
  887. Raises:
  888. TypeError: If `input_x` is not a Tensor.
  889. Supported Platforms:
  890. ``Ascend`` ``GPU`` ``CPU``
  891. Examples:
  892. >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  893. >>> rank = ops.Rank()
  894. >>> output = rank(input_tensor)
  895. >>> print(output)
  896. 2
  897. """
  898. @prim_attr_register
  899. def __init__(self):
  900. """Initialize Rank"""
  901. def __infer__(self, x):
  902. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  903. out = {'shape': None,
  904. 'dtype': None,
  905. 'value': len(x['shape'])}
  906. return out
  907. class TruncatedNormal(PrimitiveWithInfer):
  908. """
  909. Returns a tensor of the specified shape filled with truncated normal values.
  910. The generated values follow a normal distribution.
  911. Args:
  912. seed (int): A integer number used to create random seed. Default: 0.
  913. dtype (:class:`mindspore.dtype`): Data type. Default: mindspore.float32.
  914. Inputs:
  915. - **shape** (tuple[int]) - The shape of the output tensor, is a tuple of positive integer.
  916. Outputs:
  917. Tensor, the data type of output tensor is the same as attribute `dtype`.
  918. Examples:
  919. >>> shape = (1, 2, 3)
  920. >>> truncated_normal = ops.TruncatedNormal()
  921. >>> output = truncated_normal(shape)
  922. """
  923. @prim_attr_register
  924. def __init__(self, seed=0, dtype=mstype.float32):
  925. """Initialize TruncatedNormal"""
  926. validator.check_value_type('seed', seed, [int], self.name)
  927. validator.check_types_same_and_valid({'dtype': dtype}, mstype.number_type, self.name)
  928. def __infer__(self, shape):
  929. shape_value = shape['value']
  930. validator.check_value_type("shape", shape_value, [tuple], self.name)
  931. for i, value in enumerate(shape_value):
  932. validator.check_positive_int(value, f'{i}th value of shape', self.name)
  933. out = {'shape': shape_value,
  934. 'dtype': mstype.tensor_type(self.dtype),
  935. 'value': None}
  936. return out
  937. class Size(PrimitiveWithInfer):
  938. r"""
  939. Returns the size of a tensor.
  940. Returns an int scalar representing the elements size of input, the total number of elements in the tensor.
  941. Inputs:
  942. - **input_x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  943. Outputs:
  944. int, a scalar representing the elements size of `input_x`, tensor is the number of elements
  945. in a tensor, :math:`size=x_1*x_2*...x_R`.
  946. Raises:
  947. TypeError: If `input_x` is not a Tensor.
  948. Supported Platforms:
  949. ``Ascend`` ``GPU`` ``CPU``
  950. Examples:
  951. >>> input_tensor = Tensor(np.array([[2, 2], [2, 2]]), mindspore.float32)
  952. >>> size = ops.Size()
  953. >>> output = size(input_tensor)
  954. >>> print(output)
  955. 4
  956. """
  957. @prim_attr_register
  958. def __init__(self):
  959. """Initialize Size"""
  960. def __infer__(self, x):
  961. size = 1
  962. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  963. shp = x['shape']
  964. if not shp:
  965. size = 0
  966. else:
  967. size = functools.reduce(lambda x, y: x * y, x['shape'])
  968. out = {'shape': None,
  969. 'dtype': mstype.int32,
  970. 'value': size}
  971. return out
  972. class Fill(PrimitiveWithInfer):
  973. """
  974. Creates a tensor filled with a scalar value.
  975. Creates a tensor with shape described by the first argument and fills it with values in the second argument.
  976. Inputs:
  977. - **type** (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed.
  978. - **shape** (tuple) - The specified shape of output tensor. Only constant value is allowed.
  979. - **value** (scalar) - Value to fill the returned tensor. Only constant value is allowed.
  980. Outputs:
  981. Tensor, has the same type and shape as input value.
  982. Raises:
  983. TypeError: If `shape` is not a tuple.
  984. Supported Platforms:
  985. ``Ascend`` ``GPU`` ``CPU``
  986. Examples:
  987. >>> fill = ops.Fill()
  988. >>> output = fill(mindspore.float32, (2, 2), 1)
  989. >>> print(output)
  990. [[1. 1.]
  991. [1. 1.]]
  992. """
  993. @prim_attr_register
  994. def __init__(self):
  995. """Initialize Fill"""
  996. def __infer__(self, dtype, dims, x):
  997. validator.check_value_type("shape", dims['value'], [tuple], self.name)
  998. validator.check_value_type("value", x['value'], [numbers.Number, bool], self.name)
  999. for i, item in enumerate(dims['value']):
  1000. validator.check_positive_int(item, f'dims[{i}]', self.name)
  1001. valid_dtypes = [mstype.bool_, mstype.int8, mstype.int16, mstype.int32, mstype.int64,
  1002. mstype.uint8, mstype.uint16, mstype.uint32, mstype.uint64,
  1003. mstype.float16, mstype.float32, mstype.float64]
  1004. validator.check_types_same_and_valid({"value": dtype['value']}, valid_dtypes, self.name)
  1005. x_nptype = mstype.dtype_to_nptype(dtype['value'])
  1006. ret = np.full(dims['value'], x['value'], x_nptype)
  1007. out = {
  1008. 'value': Tensor(ret),
  1009. 'shape': dims['value'],
  1010. 'dtype': x['dtype'],
  1011. }
  1012. return out
  1013. class Ones(PrimitiveWithInfer):
  1014. r"""
  1015. Creates a tensor filled with value ones.
  1016. Creates a tensor with shape described by the first argument and
  1017. fills it with value ones in type of the second argument.
  1018. Inputs:
  1019. - **shape** (Union[tuple[int], int]) - The specified shape of output tensor.
  1020. Only constant positive int is allowed.
  1021. - **type** (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed.
  1022. Outputs:
  1023. Tensor, has the same type and shape as input shape value.
  1024. Raises:
  1025. TypeError: If `shape` is neither tuple nor int.
  1026. Supported Platforms:
  1027. ``Ascend`` ``GPU`` ``CPU``
  1028. Examples:
  1029. >>> from mindspore.ops import operations as ops
  1030. >>> ones = ops.Ones()
  1031. >>> output = ones((2, 2), mindspore.float32)
  1032. >>> print(output)
  1033. [[1. 1.]
  1034. [1. 1.]]
  1035. """
  1036. @prim_attr_register
  1037. def __init__(self):
  1038. """Initialize Ones"""
  1039. def __infer__(self, dims, dtype):
  1040. if isinstance(dims['value'], int):
  1041. shape = (dims['value'],)
  1042. else:
  1043. shape = dims['value']
  1044. validator.check_value_type("shape", shape, [tuple], self.name)
  1045. for i, item in enumerate(shape):
  1046. validator.check_non_negative_int(item, shape[i], self.name)
  1047. valid_types = [mstype.bool_, mstype.int8, mstype.int16, mstype.int32, mstype.int64,
  1048. mstype.uint8, mstype.uint16, mstype.uint32, mstype.uint64,
  1049. mstype.float16, mstype.float32, mstype.float64]
  1050. validator.check_types_same_and_valid({"value": dtype['value']}, valid_types, self.name)
  1051. x_nptype = mstype.dtype_to_nptype(dtype['value'])
  1052. ret = np.ones(shape, x_nptype)
  1053. out = {
  1054. 'value': Tensor(ret),
  1055. 'shape': shape,
  1056. 'dtype': x_nptype,
  1057. }
  1058. return out
  1059. class Zeros(Primitive):
  1060. r"""
  1061. Creates a tensor filled with value zeros.
  1062. Creates a tensor with shape described by the first argument and
  1063. fills it with value zeros in type of the second argument.
  1064. Inputs:
  1065. - **shape** (Union[tuple[int], int]) - The specified shape of output tensor.
  1066. Only constant positive int is allowed.
  1067. - **type** (mindspore.dtype) - The specified type of output tensor. Only constant value is allowed.
  1068. Outputs:
  1069. Tensor, has the same type and shape as input shape value.
  1070. Raises:
  1071. TypeError: If `shape` is neither int nor tuple.
  1072. TypeError: If `shape` is a tuple whose elements are not all int.
  1073. Supported Platforms:
  1074. ``Ascend`` ``GPU`` ``CPU``
  1075. Examples:
  1076. >>> from mindspore.ops import operations as ops
  1077. >>> zeros = ops.Zeros()
  1078. >>> output = zeros((2, 2), mindspore.float32)
  1079. >>> print(output)
  1080. [[0. 0.]
  1081. [0. 0.]]
  1082. """
  1083. @prim_attr_register
  1084. def __init__(self):
  1085. """Initialize Zeros"""
  1086. class OnesLike(Primitive):
  1087. """
  1088. Creates a new tensor. The values of all elements are 1.
  1089. Returns a tensor of ones with the same shape and type as the input.
  1090. Inputs:
  1091. - **input_x** (Tensor) - Input tensor.
  1092. Outputs:
  1093. Tensor, has the same shape and type as `input_x` but filled with ones.
  1094. Raises:
  1095. TypeError: If `input_x` is not a Tensor.
  1096. Supported Platforms:
  1097. ``Ascend`` ``GPU`` ``CPU``
  1098. Examples:
  1099. >>> oneslike = ops.OnesLike()
  1100. >>> x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.int32))
  1101. >>> output = oneslike(x)
  1102. >>> print(output)
  1103. [[1 1]
  1104. [1 1]]
  1105. """
  1106. @prim_attr_register
  1107. def __init__(self):
  1108. """Initialize OnesLike"""
  1109. class ZerosLike(PrimitiveWithCheck):
  1110. """
  1111. Creates a new tensor. All elements value are 0.
  1112. Returns a tensor of zeros with the same shape and data type as the input tensor.
  1113. Inputs:
  1114. - **input_x** (Tensor) - Input tensor.
  1115. Outputs:
  1116. Tensor, has the same shape and data type as `input_x` but filled with zeros.
  1117. Raises:
  1118. TypeError: If `input_x` is not a Tensor.
  1119. Supported Platforms:
  1120. ``Ascend`` ``GPU`` ``CPU``
  1121. Examples:
  1122. >>> zeroslike = ops.ZerosLike()
  1123. >>> x = Tensor(np.array([[0, 1], [2, 1]]).astype(np.float32))
  1124. >>> output = zeroslike(x)
  1125. >>> print(output)
  1126. [[0. 0.]
  1127. [0. 0.]]
  1128. """
  1129. @prim_attr_register
  1130. def __init__(self):
  1131. """Initialize ZerosLike"""
  1132. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1133. def check_dtype(self, x_dtype):
  1134. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type + (mstype.bool_,), self.name)
  1135. class TupleToArray(PrimitiveWithInfer):
  1136. """
  1137. Converts a tuple to a tensor.
  1138. If the type of the first number in the tuple is integer, the data type of the output tensor is int.
  1139. Otherwise, the data type of the output tensor is float.
  1140. Inputs:
  1141. - **input_x** (tuple) - A tuple of numbers. These numbers have the same type. Only constant value is allowed.
  1142. Outputs:
  1143. Tensor, if the input tuple contains `N` numbers, then the shape of the output tensor is (N,).
  1144. Raises:
  1145. TypeError: If `input_x` is not a tuple.
  1146. ValueError: If length of `input_x` is less than or equal to 0.
  1147. Supported Platforms:
  1148. ``Ascend`` ``GPU`` ``CPU``
  1149. Examples:
  1150. >>> type = ops.TupleToArray()((1,2,3))
  1151. >>> print(type)
  1152. [1 2 3]
  1153. """
  1154. @prim_attr_register
  1155. def __init__(self):
  1156. """Initialize TupleToArray"""
  1157. def infer_value(self, x):
  1158. validator.check_value_type("x", x, [tuple], self.name)
  1159. validator.check("size of x", len(x), '', 0, Rel.GT, self.name)
  1160. dtype = type(x[0])
  1161. for i, item in enumerate(x):
  1162. validator.check_value_type(f"x[{i}]", item, [numbers.Number], self.name)
  1163. if not all(isinstance(item, dtype) for item in x):
  1164. raise TypeError("For \'{self.name}\' all elements of input x must be have same type.")
  1165. if isinstance(x[0], int):
  1166. ret = np.array(x, np.int32)
  1167. else:
  1168. ret = np.array(x, np.float32)
  1169. return Tensor(ret)
  1170. def __call__(self, x):
  1171. args = list()
  1172. if isinstance(x, range):
  1173. args.append(tuple(x))
  1174. else:
  1175. args.append(x)
  1176. return _run_op(self, self.name, args)
  1177. class ScalarToArray(PrimitiveWithInfer):
  1178. """
  1179. Converts a scalar to a `Tensor`.
  1180. Inputs:
  1181. - **input_x** (Union[int, float]) - The input is a scalar. Only constant value is allowed.
  1182. Outputs:
  1183. Tensor. 0-D Tensor and the content is the input.
  1184. Raises:
  1185. TypeError: If `input_x` is neither int nor float.
  1186. Supported Platforms:
  1187. ``Ascend`` ``GPU`` ``CPU``
  1188. Examples:
  1189. >>> op = ops.ScalarToArray()
  1190. >>> data = 1.0
  1191. >>> output = op(data)
  1192. >>> print(output)
  1193. 1.0
  1194. """
  1195. @prim_attr_register
  1196. def __init__(self):
  1197. pass
  1198. def infer_value(self, x):
  1199. validator.check_value_type("x", x, [int, float], self.name)
  1200. if isinstance(x, int):
  1201. ret = np.array(x, np.int32)
  1202. else:
  1203. ret = np.array(x, np.float32)
  1204. return Tensor(ret)
  1205. class ScalarToTensor(PrimitiveWithInfer):
  1206. """
  1207. Converts a scalar to a `Tensor`, and converts the data type to the specified type.
  1208. Inputs:
  1209. - **input_x** (Union[int, float]) - The input is a scalar. Only constant value is allowed.
  1210. - **dtype** (mindspore.dtype) - The target data type. Default: mindspore.float32. Only
  1211. constant value is allowed.
  1212. Outputs:
  1213. Tensor. 0-D Tensor and the content is the input.
  1214. Raises:
  1215. TypeError: If `input_x` is neither int nor float.
  1216. Supported Platforms:
  1217. ``Ascend`` ``GPU`` ``CPU``
  1218. Examples:
  1219. >>> op = ops.ScalarToTensor()
  1220. >>> data = 1
  1221. >>> output = op(data, mindspore.float32)
  1222. >>> print(output)
  1223. 1.0
  1224. """
  1225. @prim_attr_register
  1226. def __init__(self):
  1227. pass
  1228. def infer_value(self, x, dtype=mstype.float32):
  1229. validator.check_value_type("x", x, [int, float], self.name)
  1230. validator.check_subclass("dtype", dtype, mstype.number, self.name)
  1231. data_type = mstype.dtype_to_nptype(dtype)
  1232. return Tensor(np.array(x, data_type))
  1233. class InvertPermutation(PrimitiveWithInfer):
  1234. r"""
  1235. Computes the inverse of an index permutation.
  1236. Given a tuple input, this operation inserts a dimension of 1 at the dimension
  1237. This operation calculates the inverse of the index replacement. It requires a
  1238. 1-dimensional tuple x, which represents the array starting at zero,
  1239. and swaps each value with its index position. In other words, for the output
  1240. tuple y and the input tuple x, this operation calculates the following:
  1241. :math:`y[x[i]] = i, \quad i \in [0, 1, \ldots, \text{len}(x)-1]`.
  1242. Note:
  1243. These values must include 0. There must be no duplicate values and the
  1244. values can not be negative.
  1245. Inputs:
  1246. - **input_x** (Union(tuple[int], list[int]) - The input is constructed by multiple
  1247. integers, i.e., :math:`(y_1, y_2, ..., y_S)` representing the indices.
  1248. The values must include 0. There can be no duplicate values or negative values.
  1249. Only constant value is allowed. The maximum value must be equal to length of input_x.
  1250. Outputs:
  1251. tuple[int]. It has the same length as the input.
  1252. Raises:
  1253. TypeError: If `input_x` is neither tuple nor list.
  1254. TypeError: If element of `input_x` is not an int.
  1255. Supported Platforms:
  1256. ``Ascend`` ``GPU`` ``CPU``
  1257. Examples:
  1258. >>> invert = ops.InvertPermutation()
  1259. >>> input_data = (3, 4, 0, 2, 1)
  1260. >>> output = invert(input_data)
  1261. >>> print(output)
  1262. (2, 4, 3, 0, 1)
  1263. """
  1264. @prim_attr_register
  1265. def __init__(self):
  1266. """Initialize InvertPermutation"""
  1267. self.set_const_prim(True)
  1268. def __infer__(self, x):
  1269. x_shp = x['shape']
  1270. x_value = x['value']
  1271. if x_value is None:
  1272. raise ValueError(f'For \'{self.name}\' the input value must be const.')
  1273. validator.check_value_type("shape", x_shp, [tuple, list], self.name)
  1274. if mstype.issubclass_(x['dtype'], mstype.tensor):
  1275. raise ValueError(f'For \'{self.name}\' the input value must be non-Tensor.')
  1276. for shp in x_shp:
  1277. if shp != []:
  1278. x_rank = len(np.array(x_value, np.int64).shape)
  1279. raise ValueError(f'For \'{self.name}\' the rank of input must be 1, but got {x_rank}.')
  1280. for i, value in enumerate(x_value):
  1281. validator.check_value_type("input[%d]" % i, value, [int], self.name)
  1282. z = [x_value[i] for i in range(len(x_value))]
  1283. z.sort()
  1284. for i in range(1, len(z)):
  1285. if z[i - 1] == z[i]:
  1286. raise ValueError(f"For {self.name}, {z[i]} is duplicated in the input.")
  1287. validator.check(f'value min', min(x_value), '', 0, Rel.EQ, self.name)
  1288. validator.check(f'value max', max(x_value), '', len(x_value) - 1, Rel.EQ, self.name)
  1289. y = [None] * len(x_value)
  1290. for i, value in enumerate(x_value):
  1291. validator.check_value_type("input[%d]" % i, value, [int], self.name)
  1292. validator.check(f'value', z[i], f'index', i, Rel.EQ, self.name)
  1293. y[value] = i
  1294. z.append(value)
  1295. return {'shape': x_shp,
  1296. 'dtype': x['dtype'],
  1297. 'value': tuple(y)}
  1298. class Argmax(PrimitiveWithInfer):
  1299. """
  1300. Returns the indices of the maximum value of a tensor across the axis.
  1301. If the shape of input tensor is :math:`(x_1, ..., x_N)`, the shape of the output tensor will be
  1302. :math:`(x_1, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`.
  1303. Args:
  1304. axis (int): Axis where the Argmax operation applies to. Default: -1.
  1305. output_type (:class:`mindspore.dtype`): An optional data type of `mindspore.dtype.int32`.
  1306. Default: `mindspore.dtype.int32`.
  1307. Inputs:
  1308. - **input_x** (Tensor) - Input tensor.
  1309. Outputs:
  1310. Tensor, indices of the max value of input tensor across the axis.
  1311. Raises:
  1312. TypeError: If `axis` is not an int.
  1313. TypeError: If `output_type` is neither int32 nor int64.
  1314. Supported Platforms:
  1315. ``Ascend`` ``GPU`` ``CPU``
  1316. Examples:
  1317. >>> input_x = Tensor(np.array([[1, 20, 5], [67, 8, 9], [130, 24, 15]]).astype(np.float32))
  1318. >>> output = ops.Argmax(output_type=mindspore.int32)(input_x)
  1319. >>> print(output)
  1320. [1 0 0]
  1321. """
  1322. @prim_attr_register
  1323. def __init__(self, axis=-1, output_type=mstype.int32):
  1324. """Initialize Argmax"""
  1325. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  1326. validator.check_value_type("axis", axis, [int], self.name)
  1327. validator.check_types_same_and_valid({'output': output_type}, [mstype.int32], self.name)
  1328. self.axis = axis
  1329. self.add_prim_attr('output_type', output_type)
  1330. def infer_shape(self, x_shape):
  1331. axis = self.axis
  1332. if axis is None:
  1333. axis = 0
  1334. x_rank = len(x_shape)
  1335. validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name)
  1336. axis = axis + x_rank if axis < 0 else axis
  1337. ouput_shape = [x_shape[i] for i in range(x_rank) if i != axis]
  1338. return ouput_shape
  1339. def infer_dtype(self, x_dtype):
  1340. validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name)
  1341. return mstype.tensor_type(self.output_type)
  1342. class Argmin(PrimitiveWithInfer):
  1343. """
  1344. Returns the indices of the minimum value of a tensor across the axis.
  1345. If the shape of input tensor is :math:`(x_1, ..., x_N)`, the shape of the output tensor is
  1346. :math:`(x_1, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`.
  1347. Args:
  1348. axis (int): Axis where the Argmin operation applies to. Default: -1.
  1349. output_type (:class:`mindspore.dtype`): An optional data type of `mindspore.dtype.int32`.
  1350. Default: `mindspore.dtype.int32`.
  1351. Inputs:
  1352. - **input_x** (Tensor) - Input tensor.
  1353. Outputs:
  1354. Tensor, indices of the min value of input tensor across the axis.
  1355. Raises:
  1356. TypeError: If `axis` is not an int.
  1357. TypeError: If `output_type` is neither int32 nor int64.
  1358. Supported Platforms:
  1359. ``Ascend``
  1360. Examples:
  1361. >>> input_x = Tensor(np.array([2.0, 3.1, 1.2]), mindspore.float32)
  1362. >>> index = ops.Argmin()(input_x)
  1363. >>> print(index)
  1364. 2
  1365. """
  1366. @prim_attr_register
  1367. def __init__(self, axis=-1, output_type=mstype.int32):
  1368. """Initialize Argmin"""
  1369. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  1370. validator.check_value_type("axis", axis, [int], self.name)
  1371. validator.check_type_name("output_type", output_type, [mstype.int32, mstype.int64], self.name)
  1372. self.axis = axis
  1373. self.add_prim_attr('output_type', output_type)
  1374. def infer_shape(self, x_shape):
  1375. axis = self.axis
  1376. if axis is None:
  1377. axis = 0
  1378. x_rank = len(x_shape)
  1379. validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name)
  1380. axis = axis + x_rank if axis < 0 else axis
  1381. ouput_shape = [x_shape[i] for i in range(x_rank) if i != axis]
  1382. return ouput_shape
  1383. def infer_dtype(self, x_dtype):
  1384. validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name)
  1385. return mstype.tensor_type(self.output_type)
  1386. class ArgMaxWithValue(PrimitiveWithInfer):
  1387. """
  1388. Calculates the maximum value with the corresponding index.
  1389. Calculates the maximum value along with the given axis for the input tensor. It returns the maximum values and
  1390. indices.
  1391. Note:
  1392. In auto_parallel and semi_auto_parallel mode, the first output index can not be used.
  1393. Args:
  1394. axis (int): The dimension to reduce. Default: 0.
  1395. keep_dims (bool): Whether to reduce dimension, if true, the output will keep same dimension with the input,
  1396. the output will reduce dimension if false. Default: False.
  1397. Inputs:
  1398. - **input_x** (Tensor) - The input tensor, can be any dimension. Set the shape of input tensor as
  1399. :math:`(x_1, x_2, ..., x_N)`.
  1400. Outputs:
  1401. tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the maximum value of the input
  1402. tensor.
  1403. - index (Tensor) - The index for the maximum value of the input tensor. If `keep_dims` is true, the shape of
  1404. output tensors is :math:`(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)`. Otherwise, the shape is
  1405. :math:`(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`.
  1406. - output_x (Tensor) - The maximum value of input tensor, with the same shape as index.
  1407. Raises:
  1408. TypeError: If `keep_dims` is not a bool.
  1409. TypeError: If `axis` is not an int.
  1410. Supported Platforms:
  1411. ``Ascend`` ``GPU``
  1412. Examples:
  1413. >>> input_x = Tensor(np.array([0.0, 0.4, 0.6, 0.7, 0.1]), mindspore.float32)
  1414. >>> index, output = ops.ArgMaxWithValue()(input_x)
  1415. >>> print(index, output)
  1416. 3 0.7
  1417. """
  1418. @prim_attr_register
  1419. def __init__(self, axis=0, keep_dims=False):
  1420. """Initialize ArgMaxWithValue"""
  1421. self.axis = axis
  1422. self.keep_dims = keep_dims
  1423. validator.check_value_type('keep_dims', keep_dims, [bool], self.name)
  1424. validator.check_value_type('axis', axis, [int], self.name)
  1425. def infer_shape(self, x_shape):
  1426. axis = self.axis
  1427. x_rank = len(x_shape)
  1428. validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name)
  1429. ouput_shape = _infer_shape_reduce(x_shape, self.axis, self.keep_dims, self.name)
  1430. return ouput_shape, ouput_shape
  1431. def infer_dtype(self, x_dtype):
  1432. validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name)
  1433. return mstype.tensor_type(mstype.int32), x_dtype
  1434. class ArgMinWithValue(PrimitiveWithInfer):
  1435. """
  1436. Calculates the minimum value with corresponding index, and returns indices and values.
  1437. Calculates the minimum value along with the given axis for the input tensor. It returns the minimum values and
  1438. indices.
  1439. Note:
  1440. In auto_parallel and semi_auto_parallel mode, the first output index can not be used.
  1441. Args:
  1442. axis (int): The dimension to reduce. Default: 0.
  1443. keep_dims (bool): Whether to reduce dimension, if true the output will keep the same dimension as the input,
  1444. the output will reduce dimension if false. Default: False.
  1445. Inputs:
  1446. - **input_x** (Tensor) - The input tensor, can be any dimension. Set the shape of input tensor as
  1447. :math:`(x_1, x_2, ..., x_N)`.
  1448. Outputs:
  1449. tuple (Tensor), tuple of 2 tensors, containing the corresponding index and the minimum value of the input
  1450. tensor.
  1451. - index (Tensor) - The index for the minimum value of the input tensor. If `keep_dims` is true, the shape of
  1452. output tensors is :math:`(x_1, x_2, ..., x_{axis-1}, 1, x_{axis+1}, ..., x_N)`. Otherwise, the shape is
  1453. :math:`(x_1, x_2, ..., x_{axis-1}, x_{axis+1}, ..., x_N)`.
  1454. - output_x (Tensor) - The minimum value of input tensor, with the same shape as index.
  1455. Raises:
  1456. TypeError: If `keep_dims` is not a bool.
  1457. TypeError: If `axis` is not an int.
  1458. Supported Platforms:
  1459. ``Ascend`` ``CPU``
  1460. Examples:
  1461. >>> input_x = Tensor(np.array([0.0, 0.4, 0.6, 0.7, 0.1]), mindspore.float32)
  1462. >>> output = ops.ArgMinWithValue()(input_x)
  1463. >>> print(output)
  1464. (Tensor(shape=[], dtype=Int32, value= 0), Tensor(shape=[], dtype=Float32, value= 0.0))
  1465. """
  1466. @prim_attr_register
  1467. def __init__(self, axis=0, keep_dims=False):
  1468. """Initialize ArgMinWithValue"""
  1469. self.axis = axis
  1470. self.keep_dims = keep_dims
  1471. validator.check_value_type('keep_dims', keep_dims, [bool], self.name)
  1472. validator.check_value_type('axis', axis, [int], self.name)
  1473. def infer_shape(self, x_shape):
  1474. axis = self.axis
  1475. x_rank = len(x_shape)
  1476. validator.check_int_range(axis, -x_rank, x_rank, Rel.INC_LEFT, "axis", self.name)
  1477. ouput_shape = _infer_shape_reduce(x_shape, self.axis, self.keep_dims, self.name)
  1478. return ouput_shape, ouput_shape
  1479. def infer_dtype(self, x_dtype):
  1480. validator.check_subclass("input_x", x_dtype, mstype.tensor, self.name)
  1481. return mstype.tensor_type(mstype.int32), x_dtype
  1482. class Tile(PrimitiveWithInfer):
  1483. r"""
  1484. Replicates a tensor with given multiples times.
  1485. Creates a new tensor by replicating `input_x` `multiples` times. The i'th dimension of
  1486. output tensor has `input_x.shape(i) * multiples[i]` elements, and the values of `input_x`
  1487. are replicated `multiples[i]` times along the i'th dimension.
  1488. Inputs:
  1489. - **input_x** (Tensor) - 1-D or higher Tensor. Set the shape of input tensor as
  1490. :math:`(x_1, x_2, ..., x_S)`.
  1491. - **multiples** (tuple[int]) - The input tuple is constructed by multiple
  1492. integers, i.e., :math:`(y_1, y_2, ..., y_S)`. The length of `multiples`
  1493. cannot be smaller than the length of the shape of `input_x`.
  1494. Only constant value is allowed.
  1495. Outputs:
  1496. Tensor, has the same data type as the `input_x`.
  1497. - If the length of `multiples` is the same as the length of shape of `input_x`,
  1498. then the shape of their corresponding positions can be multiplied, and
  1499. the shape of Outputs is :math:`(x_1*y_1, x_2*y_2, ..., x_S*y_R)`.
  1500. - If the length of `multiples` is larger than the length of shape of `input_x`,
  1501. fill in multiple 1 in the length of the shape of `input_x` until their lengths are consistent.
  1502. Such as set the shape of `input_x` as :math:`(1, ..., x_1, x_2, ..., x_S)`,
  1503. then the shape of their corresponding positions can be multiplied, and
  1504. the shape of Outputs is :math:`(1*y_1, ..., x_S*y_R)`.
  1505. Raises:
  1506. TypeError: If `multiples` is not a tuple or its elements are not all int.
  1507. ValueError: If the elements of `multiples` are not all greater than 0.
  1508. Supported Platforms:
  1509. ``Ascend`` ``GPU`` ``CPU``
  1510. Examples:
  1511. >>> tile = ops.Tile()
  1512. >>> input_x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.float32)
  1513. >>> multiples = (2, 3)
  1514. >>> output = tile(input_x, multiples)
  1515. >>> print(output)
  1516. [[1. 2. 1. 2. 1. 2.]
  1517. [3. 4. 3. 4. 3. 4.]
  1518. [1. 2. 1. 2. 1. 2.]
  1519. [3. 4. 3. 4. 3. 4.]]
  1520. """
  1521. @prim_attr_register
  1522. def __init__(self):
  1523. """Initialize Tile"""
  1524. self.init_prim_io_names(inputs=['x', 'multiples'], outputs=['output'])
  1525. def check_elim(self, base_tensor, multiplier):
  1526. if (not isinstance(base_tensor, Tensor)) or (not isinstance(multiplier, tuple)):
  1527. raise TypeError("Expecting (Tensor, tuple), got: ({}, {})".format(base_tensor, multiplier))
  1528. if all(v == 1 for v in multiplier):
  1529. return (True, base_tensor)
  1530. return (False, None)
  1531. def __infer__(self, x, multiples):
  1532. multiples_v = multiples['value']
  1533. x_shp = x['shape']
  1534. validator.check_value_type("multiples", multiples_v, [tuple], self.name)
  1535. for i, multiple in enumerate(multiples_v):
  1536. validator.check_positive_int(multiple, "multiples[%d]" % i, self.name)
  1537. validator.check_value_type("x[\'dtype\']", x["dtype"], mstype.tensor_type, self.name)
  1538. len_sub = len(multiples_v) - len(x_shp)
  1539. multiples_w = None
  1540. if len_sub == 0:
  1541. multiples_w = multiples_v
  1542. if len_sub > 0:
  1543. for i in range(0, len_sub):
  1544. x_shp.insert(0, 1)
  1545. multiples_w = multiples_v
  1546. elif len_sub < 0:
  1547. raise ValueError(f'For \'{self.name}\' the length of multiples can not be smaller than '
  1548. f'the length of dimension in input_x.')
  1549. for i, a in enumerate(multiples_w):
  1550. x_shp[i] *= a
  1551. value = None
  1552. if x['value'] is not None:
  1553. value = Tensor(np.tile(x['value'].asnumpy(), multiples_w))
  1554. return {'shape': x_shp,
  1555. 'dtype': x['dtype'],
  1556. 'value': value}
  1557. class UnsortedSegmentSum(PrimitiveWithInfer):
  1558. r"""
  1559. Computes the sum of a tensor along segments.
  1560. Calculates a tensor such that :math:`\text{output}[i] = \sum_{segment\_ids[j] == i} \text{data}[j, \ldots]`, where
  1561. :math:`j` is a tuple describing the index of element in data. `segment_ids` selects which elements in data to sum
  1562. up. Segment_ids does not need to be sorted, and it does not need to cover all values in the entire valid value
  1563. range.
  1564. Note:
  1565. If the segment_id i is absent in the segment_ids, then output[i] will be filled with 0.
  1566. If the sum of the given segment_ids :math:`i` is empty, then :math:`\text{output}[i] = 0`. If the given segment_ids
  1567. is negative, the value will be ignored. 'num_segments' must be equal to the number of different segment_ids.
  1568. Inputs:
  1569. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`.
  1570. - **segment_ids** (Tensor) - Set the shape as :math:`(x_1, x_2, ..., x_N)`, where 0 < N <= R. Type must be int.
  1571. - **num_segments** (int) - Set :math:`z` as num_segments.
  1572. Outputs:
  1573. Tensor, the shape is :math:`(z, x_{N+1}, ..., x_R)`.
  1574. Raises:
  1575. TypeError: If `num_segments` is not an int.
  1576. ValueError: If length of shape of `segment_ids` is less than 1.
  1577. Supported Platforms:
  1578. ``Ascend`` ``GPU`` ``CPU``
  1579. Examples:
  1580. >>> input_x = Tensor([1, 2, 3, 4], mindspore.float32)
  1581. >>> segment_ids = Tensor([0, 0, 1, 2], mindspore.int32)
  1582. >>> num_segments = 4
  1583. >>> output = ops.UnsortedSegmentSum()(input_x, segment_ids, num_segments)
  1584. >>> print(output)
  1585. [3. 3. 4. 0.]
  1586. """
  1587. @prim_attr_register
  1588. def __init__(self):
  1589. """Initialize UnsortedSegmentSum"""
  1590. self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y'])
  1591. def __infer__(self, x, segment_ids, num_segments):
  1592. x_type = x['dtype']
  1593. x_shp = x['shape']
  1594. validator.check_subclass("input_x", x_type, mstype.tensor, self.name)
  1595. validator.check_value_type("x_shape", x_shp, [list], self.name)
  1596. x_shp_len = len(x_shp)
  1597. validator.check_positive_int(x_shp_len, "rank of input_x", self.name)
  1598. segment_ids_shp = segment_ids['shape']
  1599. segment_ids_type = segment_ids['dtype']
  1600. validator.check_subclass("segment_ids", segment_ids_type, mstype.tensor, self.name)
  1601. validator.check_value_type("segment_ids", segment_ids_shp, [list], self.name)
  1602. segment_ids_shp_len = len(segment_ids_shp)
  1603. validator.check_positive_int(segment_ids_shp_len, "rank of segment_ids", self.name)
  1604. validator.check(f'rank of input_x', len(x_shp),
  1605. 'rank of segments_id', len(segment_ids_shp), Rel.GE, self.name)
  1606. if (not -1 in x_shp and not -1 in segment_ids_shp):
  1607. # only validate when both shapes fully known
  1608. for i, value in enumerate(segment_ids_shp):
  1609. validator.check("ids[%d]" % i, value, 'input[%d]' % i, x_shp[i], Rel.EQ, self.name)
  1610. num_segments_v = num_segments['value']
  1611. num_segments_type = num_segments['dtype']
  1612. validator.check_subclass("num_segments", num_segments_type, [mstype.tensor, mstype.number], self.name)
  1613. if isinstance(num_segments_type, type(mstype.tensor)):
  1614. validator.check_tensor_dtype_valid("num_segments", num_segments_type, [mstype.int32, mstype.int64],
  1615. self.name)
  1616. shp = [-1]
  1617. else:
  1618. validator.check_value_type('num_segments', num_segments_v, [int], self.name)
  1619. validator.check_positive_int(num_segments_v, "num_segments", self.name)
  1620. shp = [num_segments_v]
  1621. shp += x_shp[segment_ids_shp_len:]
  1622. if "max_value" in num_segments and "min_value" in num_segments:
  1623. output_max_shape = list(num_segments['max_value'])
  1624. output_min_shape = list(num_segments['min_value'])
  1625. else:
  1626. if isinstance(num_segments_type, type(mstype.tensor)):
  1627. raise ValueError("Num_segments only support int type when it is not a dynamic value")
  1628. output_max_shape = [num_segments_v]
  1629. output_min_shape = [num_segments_v]
  1630. if 'max_shape' in x and 'min_shape' in x:
  1631. max_output_incoming = x['max_shape']
  1632. min_output_incoming = x['min_shape']
  1633. else:
  1634. max_output_incoming = x_shp
  1635. min_output_incoming = x_shp
  1636. output_max_shape += max_output_incoming[segment_ids_shp_len:]
  1637. output_min_shape += min_output_incoming[segment_ids_shp_len:]
  1638. return {'shape': shp,
  1639. 'max_shape': output_max_shape,
  1640. 'min_shape': output_min_shape,
  1641. 'dtype': mstype.tensor_type(x_type.element_type()),
  1642. 'value': None}
  1643. class UnsortedSegmentMin(PrimitiveWithCheck):
  1644. """
  1645. Computes the minimum of a tensor along segments.
  1646. Note:
  1647. If the segment_id i is absent in the segment_ids, then output[i] will be filled with
  1648. the maximum value of the input_x's type.
  1649. Inputs:
  1650. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`.
  1651. The data type must be float16, float32 or int32.
  1652. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be >= 0.
  1653. The data type must be int32.
  1654. - **num_segments** (int) - The value specifies the number of distinct `segment_ids`.
  1655. Outputs:
  1656. Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`.
  1657. Raises:
  1658. TypeError: If `num_segments` is not an int.
  1659. ValueError: If length of shape of `segment_ids` is not equal to 1.
  1660. Supported Platforms:
  1661. ``Ascend`` ``GPU``
  1662. Examples:
  1663. >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32))
  1664. >>> segment_ids = Tensor(np.array([0, 1, 1]).astype(np.int32))
  1665. >>> num_segments = 2
  1666. >>> unsorted_segment_min = ops.UnsortedSegmentMin()
  1667. >>> output = unsorted_segment_min(input_x, segment_ids, num_segments)
  1668. >>> print(output)
  1669. [[1. 2. 3.]
  1670. [4. 2. 1.]]
  1671. """
  1672. @prim_attr_register
  1673. def __init__(self):
  1674. """Initialize UnsortedSegmentMin"""
  1675. self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y'])
  1676. def __check__(self, x, segment_ids, num_segments):
  1677. x_shape = x['shape']
  1678. segment_ids_shape = segment_ids['shape']
  1679. valid_type = [mstype.float16, mstype.float32, mstype.int32]
  1680. validator.check_tensor_dtype_valid("x", x['dtype'], valid_type, self.name)
  1681. validator.check_tensor_dtype_valid("segment_ids", segment_ids['dtype'], [mstype.int32], self.name)
  1682. validator.check_equal_int(len(segment_ids_shape), 1, "rank of segment_ids_shape", self.name)
  1683. num_segments_type = num_segments['dtype']
  1684. validator.check_subclass("num_segments", num_segments_type, [mstype.number], self.name)
  1685. if (not -1 in x_shape and not -1 in segment_ids_shape):
  1686. # only validate when both shapes fully known
  1687. validator.check(f'first shape of input_x', x_shape[0],
  1688. 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name)
  1689. num_segments_v = num_segments['value']
  1690. validator.check_value_type('num_segments', num_segments_v, [int], self.name)
  1691. validator.check_positive_int(num_segments_v, "num_segments", self.name)
  1692. class UnsortedSegmentMax(PrimitiveWithCheck):
  1693. """
  1694. Computes the maximum along segments of a tensor.
  1695. Note:
  1696. If the segment_id i is absent in the segment_ids, then output[i] will be filled with
  1697. the minimum value of the input_x's type.
  1698. Inputs:
  1699. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`.
  1700. The data type must be float16, float32 or int32.
  1701. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be >= 0.
  1702. The data type must be int32.
  1703. - **num_segments** (int) - The value specifies the number of distinct `segment_ids`.
  1704. Outputs:
  1705. Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`.
  1706. Raises:
  1707. TypeError: If `num_segments` is not an int.
  1708. ValueError: If length of shape of `segment_ids` is not equal to 1.
  1709. Supported Platforms:
  1710. ``Ascend`` ``GPU``
  1711. Examples:
  1712. >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32))
  1713. >>> segment_ids = Tensor(np.array([0, 1, 1]).astype(np.int32))
  1714. >>> num_segments = 2
  1715. >>> unsorted_segment_max = ops.UnsortedSegmentMax()
  1716. >>> output = unsorted_segment_max(input_x, segment_ids, num_segments)
  1717. >>> print(output)
  1718. [[1. 2. 3.]
  1719. [4. 5. 6.]]
  1720. """
  1721. @prim_attr_register
  1722. def __init__(self):
  1723. """Initialize UnsortedSegmentMax"""
  1724. self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y'])
  1725. def __check__(self, x, segment_ids, num_segments):
  1726. x_shape = x['shape']
  1727. segment_ids_shape = segment_ids['shape']
  1728. valid_type = [mstype.float16, mstype.float32, mstype.int32]
  1729. validator.check_tensor_dtype_valid("x", x['dtype'], valid_type, self.name)
  1730. validator.check_tensors_dtypes_same_and_valid({"segment_ids": segment_ids['dtype']},
  1731. [mstype.int32, mstype.int64], self.name)
  1732. validator.check_equal_int(len(segment_ids_shape), 1, "rank of segment_ids_shape", self.name)
  1733. num_segments_type = num_segments['dtype']
  1734. validator.check_subclass("num_segments", num_segments_type, [mstype.number], self.name)
  1735. if (not -1 in x_shape and not -1 in segment_ids_shape):
  1736. # only validate when both shapes fully known
  1737. validator.check(f'first shape of input_x', x_shape[0],
  1738. 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name)
  1739. num_segments_v = num_segments['value']
  1740. validator.check_value_type('num_segments', num_segments_v, [int], self.name)
  1741. validator.check_positive_int(num_segments_v, "num_segments", self.name)
  1742. class UnsortedSegmentProd(PrimitiveWithInfer):
  1743. """
  1744. Computes the product of a tensor along segments.
  1745. Inputs:
  1746. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`.
  1747. With float16, float32 or int32 data type.
  1748. - **segment_ids** (Tensor) - A `1-D` tensor whose shape is :math:`(x_1)`, the value must be >= 0.
  1749. Data type must be int32.
  1750. - **num_segments** (int) - The value specifies the number of distinct `segment_ids`,
  1751. must be greater than 0.
  1752. Outputs:
  1753. Tensor, set the number of `num_segments` as `N`, the shape is :math:`(N, x_2, ..., x_R)`.
  1754. Raises:
  1755. TypeError: If `num_segments` is not an int.
  1756. ValueError: If length of shape of `segment_ids` is not equal to 1.
  1757. Supported Platforms:
  1758. ``Ascend``
  1759. Examples:
  1760. >>> input_x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [4, 2, 1]]).astype(np.float32))
  1761. >>> segment_ids = Tensor(np.array([0, 1, 0]).astype(np.int32))
  1762. >>> num_segments = 2
  1763. >>> unsorted_segment_prod = ops.UnsortedSegmentProd()
  1764. >>> output = unsorted_segment_prod(input_x, segment_ids, num_segments)
  1765. >>> print(output)
  1766. [[4. 4. 3.]
  1767. [4. 5. 6.]]
  1768. """
  1769. @prim_attr_register
  1770. def __init__(self):
  1771. """Initialize UnsortedSegmentProd"""
  1772. self.init_prim_io_names(inputs=['x', 'segment_ids', 'num_segments'], outputs=['y'])
  1773. def __infer__(self, x, segment_ids, num_segments):
  1774. x_type = x['dtype']
  1775. x_shape = x['shape']
  1776. segment_ids_shape = segment_ids['shape']
  1777. validator.check_subclass("input_x", x_type, mstype.tensor, self.name)
  1778. validator.check_value_type("x_shape", x_shape, [list], self.name)
  1779. valid_type = [mstype.float16, mstype.float32, mstype.int32]
  1780. validator.check_tensor_dtype_valid("x", x['dtype'], valid_type, self.name)
  1781. validator.check_tensor_dtype_valid("segment_ids", segment_ids['dtype'], [mstype.int32], self.name)
  1782. validator.check_equal_int(len(segment_ids_shape), 1, "rank of segment_ids_shape", self.name)
  1783. validator.check(f'first shape of input_x', x_shape[0],
  1784. 'length of segments_id', segment_ids_shape[0], Rel.EQ, self.name)
  1785. num_segments_v = num_segments['value']
  1786. validator.check_value_type('num_segments', num_segments_v, [int], self.name)
  1787. validator.check_positive_int(num_segments_v, "num_segments", self.name)
  1788. segment_ids_shape_len = len(segment_ids_shape)
  1789. out_shape = [num_segments_v]
  1790. out_shape += x_shape[segment_ids_shape_len:]
  1791. out = {'shape': out_shape,
  1792. 'dtype': mstype.tensor_type(x_type.element_type()),
  1793. 'value': None}
  1794. return out
  1795. class Concat(PrimitiveWithInfer):
  1796. r"""
  1797. Connect tensor in the specified axis.
  1798. Connect input tensors along with the given axis.
  1799. The input data is a tuple of tensors. These tensors have the same rank `R`. Set the given axis as `m`, and
  1800. :math:`0 \le m < R`. Set the number of input tensors as `N`. For the :math:`i`-th tensor :math:`t_i`, it has
  1801. the shape of :math:`(x_1, x_2, ..., x_{mi}, ..., x_R)`. :math:`x_{mi}` is the :math:`m`-th dimension of the
  1802. :math:`i`-th tensor. Then, the shape of the output tensor is
  1803. .. math::
  1804. (x_1, x_2, ..., \sum_{i=1}^Nx_{mi}, ..., x_R)
  1805. Args:
  1806. axis (int): The specified axis. Default: 0.
  1807. Inputs:
  1808. - **input_x** (tuple, list) - A tuple or a list of input tensors.
  1809. Outputs:
  1810. Tensor, the shape is :math:`(x_1, x_2, ..., \sum_{i=1}^Nx_{mi}, ..., x_R)`.
  1811. Raises:
  1812. TypeError: If `axis` is not an int.
  1813. Supported Platforms:
  1814. ``Ascend`` ``GPU`` ``CPU``
  1815. Examples:
  1816. >>> data1 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.float32))
  1817. >>> data2 = Tensor(np.array([[0, 1], [2, 1]]).astype(np.float32))
  1818. >>> op = ops.Concat()
  1819. >>> output = op((data1, data2))
  1820. >>> print(output)
  1821. [[0. 1.]
  1822. [2. 1.]
  1823. [0. 1.]
  1824. [2. 1.]]
  1825. """
  1826. @prim_attr_register
  1827. def __init__(self, axis=0):
  1828. """Initialize Concat"""
  1829. validator.check_value_type("axis", axis, [int], self.name)
  1830. def __infer__(self, input_x):
  1831. axis = self.axis
  1832. x_shp = input_x['shape']
  1833. x_type = input_x['dtype']
  1834. _, all_shp, _ = get_concat_offset(x_shp, x_type, axis, self.name)
  1835. self.add_prim_attr('inputNums', len(x_shp))
  1836. ret_shp = x_shp[0].copy()
  1837. value = None
  1838. if input_x['value'] is not None:
  1839. value = Tensor(np.concatenate([x.asnumpy() for x in input_x['value']], axis=axis))
  1840. ret_shp[axis] = all_shp
  1841. out = {'shape': ret_shp,
  1842. 'dtype': x_type[0],
  1843. 'value': value}
  1844. if -1 in x_shp[0]:
  1845. x_min_shp = input_x['min_shape']
  1846. ret_min_shp = x_min_shp[0].copy()
  1847. ret_min_shp[axis] = 0
  1848. for all_min_shp in x_min_shp:
  1849. ret_min_shp[axis] += all_min_shp[axis]
  1850. out['min_shape'] = ret_min_shp
  1851. x_max_shp = input_x['max_shape']
  1852. ret_max_shp = x_max_shp[0].copy()
  1853. ret_max_shp[axis] = 0
  1854. for all_max_shp in x_max_shp:
  1855. ret_max_shp[axis] += all_max_shp[axis]
  1856. out['max_shape'] = ret_max_shp
  1857. return out
  1858. class ParallelConcat(PrimitiveWithInfer):
  1859. r"""
  1860. Concats tensor in the first dimension.
  1861. Concats input tensors along with the first dimension.
  1862. Note:
  1863. The input tensors are all required to have size 1 in the first dimension.
  1864. Inputs:
  1865. - **values** (tuple, list) - A tuple or a list of input tensors. The data type and shape of these
  1866. tensors must be the same.
  1867. Outputs:
  1868. Tensor, data type is the same as `values`.
  1869. Raises:
  1870. ValueError: If length of shape of `values` is less than 1.
  1871. Supported Platforms:
  1872. ``Ascend``
  1873. Examples:
  1874. >>> data1 = Tensor(np.array([[0, 1]]).astype(np.int32))
  1875. >>> data2 = Tensor(np.array([[2, 1]]).astype(np.int32))
  1876. >>> op = ops.ParallelConcat()
  1877. >>> output = op((data1, data2))
  1878. >>> print(output)
  1879. [[0 1]
  1880. [2 1]]
  1881. """
  1882. @prim_attr_register
  1883. def __init__(self):
  1884. """Initialize ParallelConcat"""
  1885. def __infer__(self, values):
  1886. x_shp = values['shape']
  1887. x_type = values['dtype']
  1888. validator.check_int(len(x_shp), 1, Rel.GE, f'x_shp length', self.name)
  1889. args = {f"x_type[{i}]": elem for i, elem in enumerate(x_type)}
  1890. validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type + (mstype.bool_,), self.name)
  1891. first_elem = x_shp[0]
  1892. for i, elem in enumerate(x_shp[1:]):
  1893. j = i + 1
  1894. validator.check_equal_int(elem[0], 1, f'x_shp[{j}][0]', self.name)
  1895. validator.check(f"x_shp[0] shape", first_elem, f"x_shp[{j}] shape", elem, Rel.EQ, self.name)
  1896. ret_shp = x_shp[0].copy()
  1897. ret_shp[0] = len(x_shp)
  1898. self.add_prim_attr('shape', ret_shp)
  1899. self.add_prim_attr('N', len(x_shp))
  1900. out = {'shape': ret_shp,
  1901. 'dtype': x_type[0],
  1902. 'value': None}
  1903. return out
  1904. def _get_stack_shape(x_shape, x_type, axis, prim_name):
  1905. """for stack output shape"""
  1906. validator.check_value_type("shape", x_shape, [tuple, list], prim_name)
  1907. validator.check_int(len(x_shape), 1, Rel.GE, "len of input_x", prim_name)
  1908. validator.check_subclass("input_x[0]", x_type[0], mstype.tensor, prim_name)
  1909. rank_base = len(x_shape[0])
  1910. N = len(x_shape)
  1911. out_shape = x_shape[0]
  1912. validator.check_int_range(axis, -rank_base - 1, rank_base, Rel.INC_BOTH, 'axis', prim_name)
  1913. if axis < 0:
  1914. axis = axis + rank_base + 1
  1915. for i in range(1, N):
  1916. validator.check('x_type[%d]' % i, x_type[i], 'base', x_type[0], Rel.EQ, prim_name, TypeError)
  1917. if x_shape[i] != x_shape[0]:
  1918. raise ValueError(f"For \'{prim_name}\' element {i} shape in input can not pack with first element")
  1919. out_shape.insert(axis, N)
  1920. return out_shape
  1921. class Pack(PrimitiveWithInfer):
  1922. """
  1923. Same as operator Stack. Pack will be deprecated in the future.
  1924. Please use Stack instead.
  1925. """
  1926. @deprecated("1.1", "Stack", True)
  1927. @prim_attr_register
  1928. def __init__(self, axis=0):
  1929. """Initialize Pack"""
  1930. validator.check_value_type("axis", axis, [int], self.name)
  1931. self.axis = axis
  1932. def __infer__(self, value):
  1933. x_shape = value['shape']
  1934. x_type = value['dtype']
  1935. self.add_prim_attr('num', len(x_shape))
  1936. all_shape = _get_stack_shape(x_shape, x_type, self.axis, self.name)
  1937. out = {'shape': all_shape,
  1938. 'dtype': x_type[0],
  1939. 'value': None}
  1940. return out
  1941. class Stack(PrimitiveWithInfer):
  1942. r"""
  1943. Stacks a list of tensors in specified axis.
  1944. Stacks the list of input tensors with the same rank `R`, output is a tensor of rank `(R+1)`.
  1945. Given input tensors of shape :math:`(x_1, x_2, ..., x_R)`. Set the number of input tensors as `N`.
  1946. 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)`.
  1947. Args:
  1948. axis (int): Dimension to stack. Default: 0.
  1949. Negative values wrap around. The range is [-(R+1), R+1).
  1950. Inputs:
  1951. - **input_x** (Union[tuple, list]) - A Tuple or list of Tensor objects with the same shape and type.
  1952. Outputs:
  1953. Tensor. A stacked Tensor with the same type as `input_x`.
  1954. Raises:
  1955. TypeError: If the data types of elements in `input_x` are not the same.
  1956. ValueError: If the length of `input_x` is not greater than 1;
  1957. or if axis is out of the range [-(R+1), R+1);
  1958. or if the shapes of elements in input_x are not the same.
  1959. Supported Platforms:
  1960. ``Ascend`` ``GPU`` ``CPU``
  1961. Examples:
  1962. >>> data1 = Tensor(np.array([0, 1]).astype(np.float32))
  1963. >>> data2 = Tensor(np.array([2, 3]).astype(np.float32))
  1964. >>> stack = ops.Stack()
  1965. >>> output = stack([data1, data2])
  1966. >>> print(output)
  1967. [[0. 1.]
  1968. [2. 3.]]
  1969. """
  1970. @prim_attr_register
  1971. def __init__(self, axis=0):
  1972. """Initialize Stack"""
  1973. validator.check_value_type("axis", axis, [int], self.name)
  1974. self.axis = axis
  1975. def __infer__(self, value):
  1976. x_shape = value['shape']
  1977. x_type = value['dtype']
  1978. self.add_prim_attr('num', len(x_shape))
  1979. all_shape = _get_stack_shape(x_shape, x_type, self.axis, self.name)
  1980. out = {'shape': all_shape,
  1981. 'dtype': x_type[0],
  1982. 'value': None}
  1983. return out
  1984. class Unpack(PrimitiveWithInfer):
  1985. """
  1986. Same as operator Unstack. Unpack will be deprecated in the future.
  1987. Please use Unstack instead.
  1988. """
  1989. @deprecated("1.1", "Unstack", True)
  1990. @prim_attr_register
  1991. def __init__(self, axis=0):
  1992. """Initialize Unpack"""
  1993. validator.check_value_type("axis", axis, [int], self.name)
  1994. self.axis = axis
  1995. def __infer__(self, x):
  1996. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  1997. x_shape = list(x['shape'])
  1998. dim = len(x_shape)
  1999. validator.check_int_range(self.axis, -dim, dim, Rel.INC_LEFT, 'axis value', self.name)
  2000. if self.axis < 0:
  2001. self.axis = self.axis + dim
  2002. output_num = x_shape[self.axis]
  2003. validator.check_value_type("num", output_num, [int], self.name)
  2004. validator.check_positive_int(output_num, "output_num", self.name)
  2005. self.add_prim_attr('num', output_num)
  2006. output_valid_check = x_shape[self.axis] - output_num
  2007. validator.check_int(output_valid_check, 0, Rel.EQ,
  2008. "The dimension which to unstack divides output_num", self.name)
  2009. out_shapes = []
  2010. out_dtypes = []
  2011. out_shape = x_shape[:self.axis] + x_shape[self.axis + 1:]
  2012. for _ in range(output_num):
  2013. out_shapes.append(tuple(out_shape))
  2014. out_dtypes.append(x['dtype'])
  2015. out_shapes = tuple(out_shapes)
  2016. out_dtypes = tuple(out_dtypes)
  2017. out = {'shape': out_shapes,
  2018. 'dtype': out_dtypes,
  2019. 'value': None}
  2020. return out
  2021. class Unstack(PrimitiveWithInfer):
  2022. r"""
  2023. Unstacks tensor in specified axis.
  2024. Unstacks a tensor of rank `R` along axis dimension, output tensors will have rank `(R-1)`.
  2025. Given a tensor of shape :math:`(x_1, x_2, ..., x_R)`. If :math:`0 \le axis`,
  2026. the shape of tensor in output is :math:`(x_1, x_2, ..., x_{axis}, x_{axis+2}, ..., x_R)`.
  2027. This is the opposite of pack.
  2028. Args:
  2029. axis (int): Dimension along which to pack. Default: 0.
  2030. Negative values wrap around. The range is [-R, R).
  2031. Inputs:
  2032. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_R)`.
  2033. A tensor to be unstacked and the rank of the tensor must be greater than 0.
  2034. Outputs:
  2035. A tuple of tensors, the shape of each objects is the same.
  2036. Raises:
  2037. ValueError: If axis is out of the range [-len(input_x.shape), len(input_x.shape)).
  2038. Supported Platforms:
  2039. ``Ascend`` ``GPU`` ``CPU``
  2040. Examples:
  2041. >>> unstack = ops.Unstack()
  2042. >>> input_x = Tensor(np.array([[1, 1, 1, 1], [2, 2, 2, 2]]))
  2043. >>> output = unstack(input_x)
  2044. >>> print(output)
  2045. (Tensor(shape=[4], dtype=Int64, value= [1, 1, 1, 1]), Tensor(shape=[4], dtype=Int64, value= [2, 2, 2, 2]))
  2046. """
  2047. @prim_attr_register
  2048. def __init__(self, axis=0):
  2049. """Initialize Unstack"""
  2050. validator.check_value_type("axis", axis, [int], self.name)
  2051. self.axis = axis
  2052. def __infer__(self, x):
  2053. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  2054. x_shape = list(x['shape'])
  2055. dim = len(x_shape)
  2056. validator.check_int_range(self.axis, -dim, dim, Rel.INC_LEFT, 'axis value', self.name)
  2057. if self.axis < 0:
  2058. self.axis = self.axis + dim
  2059. output_num = x_shape[self.axis]
  2060. validator.check_value_type("num", output_num, [int], self.name)
  2061. validator.check_positive_int(output_num, "output_num", self.name)
  2062. self.add_prim_attr('num', output_num)
  2063. output_valid_check = x_shape[self.axis] - output_num
  2064. validator.check_int(output_valid_check, 0, Rel.EQ,
  2065. "The dimension which to unstack divides output_num", self.name)
  2066. out_shapes = []
  2067. out_dtypes = []
  2068. out_shape = x_shape[:self.axis] + x_shape[self.axis + 1:]
  2069. for _ in range(output_num):
  2070. out_shapes.append(tuple(out_shape))
  2071. out_dtypes.append(x['dtype'])
  2072. out_shapes = tuple(out_shapes)
  2073. out_dtypes = tuple(out_dtypes)
  2074. out = {'shape': out_shapes,
  2075. 'dtype': out_dtypes,
  2076. 'value': None}
  2077. return out
  2078. class Slice(PrimitiveWithInfer):
  2079. """
  2080. Slices a tensor in the specified shape.
  2081. Slice the tensor 'input_x` in shape of `size` and starting at the location specified by `begin`,
  2082. The slice `begin` represents the offset in each dimension of `input_x`,
  2083. The slice `size` represents the size of the output tensor.
  2084. Note that `begin` is zero-based and `size` is one-based.
  2085. If `size[i]` is -1, all remaining elements in dimension i are included in the slice.
  2086. This is equivalent to setting :math:`size[i] = input_x.shape(i) - begin[i]`
  2087. Inputs:
  2088. - **input_x** (Tensor): The target tensor.
  2089. - **begin** (Union[tuple, list]): The beginning of the slice. Only constant value is allowed.
  2090. - **size** (Union[tuple, list]): The size of the slice. Only constant value is allowed.
  2091. Outputs:
  2092. Tensor, the shape is : input `size`, the data type is the same as `input_x`.
  2093. Raises:
  2094. TypeError: If `begin` or `size` is neither tuple nor list.
  2095. Supported Platforms:
  2096. ``Ascend`` ``GPU`` ``CPU``
  2097. Examples:
  2098. >>> data = Tensor(np.array([[[1, 1, 1], [2, 2, 2]],
  2099. ... [[3, 3, 3], [4, 4, 4]],
  2100. ... [[5, 5, 5], [6, 6, 6]]]).astype(np.int32))
  2101. >>> slice = ops.Slice()
  2102. >>> output = slice(data, (1, 0, 0), (1, 1, 3))
  2103. >>> print(output)
  2104. [[[3 3 3]]]
  2105. """
  2106. @prim_attr_register
  2107. def __init__(self):
  2108. """Initialize slice"""
  2109. self.init_prim_io_names(inputs=['x', 'begin', 'size'], outputs=['output'])
  2110. def __infer__(self, x, begin, size):
  2111. x_shape = x['shape']
  2112. x_shp_len = len(x_shape)
  2113. validator.check_const_input('begin', begin['value'], self.name)
  2114. validator.check_const_input('size', size['value'], self.name)
  2115. begin_v, size_v = begin['value'], size['value']
  2116. if begin_v is None or size_v is None:
  2117. return {'shape': None,
  2118. 'dtype': x['dtype'],
  2119. 'value': None}
  2120. validator.check_value_type("input begin", begin_v, [tuple, list], self.name)
  2121. validator.check_value_type("input size", size_v, [tuple, list], self.name)
  2122. for key, value in zip(('begin', 'size'), (begin_v, size_v)):
  2123. validator.check(f'len of {key}', len(value),
  2124. 'len x\'s dim', x_shp_len)
  2125. for i in range(x_shp_len):
  2126. validator.check_positive_int(size_v[i], f'input size[{i}]')
  2127. if x_shape[i] < begin_v[i] + size_v[i]:
  2128. y = begin_v[i] + size_v[i]
  2129. raise ValueError("For '%s' slice shape can not bigger than origin shape %d, %d." %
  2130. (self.name, x_shape[i], y))
  2131. return {'shape': size_v,
  2132. 'dtype': x['dtype'],
  2133. 'value': None}
  2134. class ReverseV2(PrimitiveWithInfer):
  2135. """
  2136. Reverses specific dimensions of a tensor.
  2137. Args:
  2138. axis (Union[tuple(int), list(int)): The indices of the dimensions to reverse.
  2139. Inputs:
  2140. - **input_x** (Tensor) - The target tensor.
  2141. Outputs:
  2142. Tensor, has the same shape and type as `input_x`.
  2143. Raises:
  2144. TypeError: If `axis` is neither list nor tuple.
  2145. TypeError: If element of `axis` is not an int.
  2146. Supported Platforms:
  2147. ``Ascend``
  2148. Examples:
  2149. >>> input_x = Tensor(np.array([[1, 2, 3, 4], [5, 6, 7, 8]]), mindspore.int32)
  2150. >>> op = ops.ReverseV2(axis=[1])
  2151. >>> output = op(input_x)
  2152. >>> print(output)
  2153. [[4 3 2 1]
  2154. [8 7 6 5]]
  2155. """
  2156. @prim_attr_register
  2157. def __init__(self, axis):
  2158. validator.check_value_type('axis', axis, [list, tuple], self.name)
  2159. for i, each in enumerate(axis):
  2160. validator.check_value_type(f'axis[{i}]', each, [int], self.name)
  2161. self.axis = axis
  2162. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  2163. def infer_shape(self, x_shape):
  2164. dim = len(x_shape)
  2165. for i, each in enumerate(self.axis):
  2166. validator.check_int_range(each, -dim, dim, Rel.INC_LEFT, f'axis[{i}]', self.name)
  2167. return x_shape
  2168. def infer_dtype(self, x_dtype):
  2169. validator.check_tensor_dtype_valid('x', x_dtype, (mstype.bool_,) + mstype.number_type, self.name)
  2170. return x_dtype
  2171. class Rint(PrimitiveWithInfer):
  2172. """
  2173. Returns an integer that is closest to x element-wise.
  2174. Inputs:
  2175. - **input_x** (Tensor) - The target tensor, which must be one of the following types:
  2176. float16, float32.
  2177. Outputs:
  2178. Tensor, has the same shape and type as `input_x`.
  2179. Raises:
  2180. TypeError: If dtype of `input_x` is neither float16 nor float32.
  2181. Supported Platforms:
  2182. ``Ascend`` ``GPU`` ``CPU``
  2183. Examples:
  2184. >>> input_x = Tensor(np.array([-1.6, -0.1, 1.5, 2.0]), mindspore.float32)
  2185. >>> op = ops.Rint()
  2186. >>> output = op(input_x)
  2187. >>> print(output)
  2188. [-2. 0. 2. 2.]
  2189. """
  2190. @prim_attr_register
  2191. def __init__(self):
  2192. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  2193. def infer_shape(self, x_shape):
  2194. return x_shape
  2195. def infer_dtype(self, x_dtype):
  2196. validator.check_tensor_dtype_valid('x', x_dtype, [mstype.float16, mstype.float32], self.name)
  2197. return x_dtype
  2198. class Select(PrimitiveWithInfer):
  2199. r"""
  2200. Returns the selected elements, either from input :math:`x` or input :math:`y`, depending on the `condition`.
  2201. Given a tensor as input, this operation inserts a dimension of 1 at the dimension,
  2202. it was invalid when both math: 'x' and math: 'y' are none.
  2203. Keep in mind that the shape of the output tensor can vary depending
  2204. on how many true values are in the input. Indexes are output in row-first
  2205. order.
  2206. If neither is None, math:`x` and :math:`y` must have the same shape. If :math:`x` and :math:`y` are
  2207. scalars, the conditional tensor must be a scalar. If :math:`x` and :math:`y` are
  2208. higher-dimensional vectors, the `condition` must be a vector whose size matches the
  2209. first dimension of :math:`x`, or must have the same shape as :math:`y`.
  2210. The conditional tensor acts as an optional compensation (mask), which
  2211. determines whether the corresponding element / row in the output must be
  2212. selected from :math:`x` (if true) or :math:`y` (if false) based on the value of each
  2213. element.
  2214. It can be defined as:
  2215. .. math::
  2216. out_i = \begin{cases}
  2217. x_i, & \text{if } condition_i \\
  2218. y_i, & \text{otherwise}
  2219. \end{cases}
  2220. If condition is a vector, then :math:`x` and :math:`y` are higher-dimensional matrices, then it
  2221. chooses to copy that row (external dimensions) from :math:`x` and :math:`y`. If condition has
  2222. the same shape as :math:`x` and :math:`y`, you can choose to copy these elements from :math:`x`
  2223. and :math:`y`.
  2224. Inputs:
  2225. - **input_cond** (Tensor[bool]) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`.
  2226. The condition tensor, decides which element is chosen.
  2227. - **input_x** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`.
  2228. The first input tensor.
  2229. - **input_y** (Tensor) - The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`.
  2230. The second input tensor.
  2231. Outputs:
  2232. Tensor, has the same shape as `input_x`. The shape is :math:`(x_1, x_2, ..., x_N, ..., x_R)`.
  2233. Raises:
  2234. TypeError: If `input_x` or `input_y` is not a Tensor.
  2235. ValueError: If shape of `input_x` is not equal to shape of `input_y` or shape of `input_cond`.
  2236. Supported Platforms:
  2237. ``Ascend`` ``GPU`` ``CPU``
  2238. Examples:
  2239. >>> select = ops.Select()
  2240. >>> input_cond = Tensor([True, False])
  2241. >>> input_x = Tensor([2,3], mindspore.float32)
  2242. >>> input_y = Tensor([1,2], mindspore.float32)
  2243. >>> output = select(input_cond, input_x, input_y)
  2244. >>> print(output)
  2245. [2. 2.]
  2246. """
  2247. @prim_attr_register
  2248. def __init__(self):
  2249. """init"""
  2250. self.init_prim_io_names(inputs=['condition', 'x', 'y'], outputs=['output'])
  2251. def infer_shape(self, cond_shape, x_shape, y_shape):
  2252. if cond_shape != x_shape or x_shape != y_shape:
  2253. raise ValueError('The x_shape and y_shape must be the same as cond_shape.')
  2254. return x_shape
  2255. def infer_dtype(self, cond_type, x_type, y_type):
  2256. validator.check_subclass("x_type", x_type, mstype.tensor, self.name)
  2257. validator.check_subclass("y_type", y_type, mstype.tensor, self.name)
  2258. validator.check_tensor_dtype_valid("cond", cond_type, [mstype.bool_], self.name)
  2259. if x_type != y_type:
  2260. raise TypeError('\'%s\' the x_type %s must be the same as y_type %s.' % (self.name, x_type, y_type))
  2261. return x_type
  2262. def infer_value(self, cond, x, y):
  2263. if cond is not None and x is not None and y is not None:
  2264. cond = cond.asnumpy()
  2265. x = x.asnumpy()
  2266. y = y.asnumpy()
  2267. out = np.where(cond, x, y)
  2268. return Tensor(out)
  2269. return None
  2270. def _compute_slicing_length(begin, end, stride, x_shape, i):
  2271. """Computes the length of the slicing."""
  2272. if i >= len(x_shape):
  2273. raise ValueError(f"For 'StridedSlice', When their is no new axis, the index length must be less or "
  2274. f"equal than the dim of x.")
  2275. x_dim = x_shape[i]
  2276. if stride > 0:
  2277. # When slicing forward, convert begin and end to positive numbers.
  2278. if begin >= x_dim or end < -x_dim:
  2279. # When slicing forward, if begin >= x_dim or end < -x_dim, the length of the slicing is 0.
  2280. slicing_length = 0
  2281. else:
  2282. if -x_dim <= begin < 0:
  2283. begin += x_dim
  2284. if begin < -x_dim:
  2285. # When slicing forward, if begin < -x_dim, set begin = 0, which means start from the 0th element.
  2286. begin = 0
  2287. if -x_dim <= end < 0:
  2288. end += x_dim
  2289. if end > x_dim:
  2290. # When slicing forward, if end > x_dim, set end = x_dims, which means slice to the last element.
  2291. end = x_dim
  2292. if begin >= end:
  2293. # When slicing forward, if begin >= end, the length of the slicing is 0.
  2294. slicing_length = 0
  2295. else:
  2296. slicing_length = 1 + (end - 1 - begin) // stride
  2297. else:
  2298. # When slicing backward, convert begin and end to negative numbers.
  2299. if begin < -x_dim or end >= x_dim:
  2300. # When slicing backward, if begin < -x_dim or end >= x_dim, the length of the slicing is 0.
  2301. slicing_length = 0
  2302. else:
  2303. if 0 <= begin < x_dim:
  2304. begin += -x_dim
  2305. if begin >= x_dim:
  2306. begin = -1
  2307. if 0 <= end < x_dim:
  2308. end += -x_dim
  2309. if end < -x_dim - 1:
  2310. # When slicing backward, if end < -x_dim - 1, set end = -x_dim - 1, which means
  2311. # slicing to the 0th element.
  2312. end = -x_dim - 1
  2313. if begin <= end:
  2314. # When slicing backward, if begin <= end, the length of the slicing is 0.
  2315. slicing_length = 0
  2316. else:
  2317. slicing_length = 1 + (end + 1 - begin) // stride
  2318. return slicing_length
  2319. class StridedSlice(PrimitiveWithInfer):
  2320. r"""
  2321. Extracts a strided slice of a tensor.
  2322. Given an input tensor, this operation inserts a dimension of length 1 at the dimension.
  2323. This operation extracts a fragment of size (end-begin)/stride from the given 'input_tensor'.
  2324. Starting from the beginning position, the fragment continues adding stride to the index until
  2325. all dimensions are not less than the ending position.
  2326. Given a `input_x[m1, m2, ..., mn]`, `begin`, `end` and `strides` will be vectors of length n.
  2327. In each mask field (`begin_mask`, `end_mask`, `ellipsis_mask`, `new_axis_mask`, `shrink_axis_mask`)
  2328. the ith bit will correspond to the ith m.
  2329. If the ith bit of `begin_mask` is set, `begin[i]` is ignored and the fullest possible range in that dimension
  2330. is used instead. `end_mask` is analogous, except with the end range.
  2331. As for a 5*6*7 tensor, `x[2:,:3,:]` is equivalent to `x[2:5,0:3,0:7]`.
  2332. If the ith bit of `ellipsis_mask` is set, as many unspecified dimensions as needed will be inserted between
  2333. other dimensions. Only one non-zero bit is allowed in `ellipsis_mask`.
  2334. As for a 5*6*7*8 tensor, `x[2:,...,:6]` is equivalent to `x[2:5,:,:,0:6]`.
  2335. `x[2:,...]` is equivalent to `x[2:5,:,:,:]`.
  2336. If the ith bit of `new_axis_mask` is set, `begin`, `end` and `strides` are ignored and a new length 1
  2337. dimension is added at the specified position in tthe output tensor.
  2338. As for a 5*6*7 tensor, `x[:2, newaxis, :6]` will produce a tensor with shape (2, 1, 7).
  2339. If the ith bit of `shrink_axis_mask` is set, ith size shrinks the dimension by 1, taking on the value
  2340. at index `begin[i]`, `end[i]` and `strides[i]` are ignored.
  2341. As for a 5*6*7 tensor, `x[:, 5, :]` will result in `shrink_axis_mask` equal to 4.
  2342. Note:
  2343. The stride may be negative value, which causes reverse slicing.
  2344. The shape of `begin`, `end` and `strides` must be the same.
  2345. `begin` and `end` are zero-indexed. The element of `strides` must be non-zero.
  2346. Args:
  2347. begin_mask (int): Starting index of the slice. Default: 0.
  2348. end_mask (int): Ending index of the slice. Default: 0.
  2349. ellipsis_mask (int): An int mask. Default: 0.
  2350. new_axis_mask (int): An int mask. Default: 0.
  2351. shrink_axis_mask (int): An int mask. Default: 0.
  2352. Inputs:
  2353. - **input_x** (Tensor) - The input Tensor.
  2354. - **begin** (tuple[int]) - A tuple which represents the location where to start. Only
  2355. constant value is allowed.
  2356. - **end** (tuple[int]) - A tuple or which represents the maximum location where to end.
  2357. Only constant value is allowed.
  2358. - **strides** (tuple[int]) - A tuple which represents the stride is continuously added
  2359. before reaching the maximum location. Only constant value is allowed.
  2360. Outputs:
  2361. Tensor, The output is explained by following example.
  2362. In the 0th dimension, begin is 1, end is 2, and strides is 1,
  2363. because :math:`1+1=2\geq2`, the interval is :math:`[1,2)`.
  2364. Thus, return the element with :math:`index = 1` in 0th dimension, i.e., [[3, 3, 3], [4, 4, 4]].
  2365. In the 1st dimension, similarly, the interval is :math:`[0,1)`.
  2366. Based on the return value of the 0th dimension, return the element with :math:`index = 0`,
  2367. i.e., [3, 3, 3].
  2368. In the 2nd dimension, similarly, the interval is :math:`[0,3)`.
  2369. Based on the return value of the 1st dimension, return the element with :math:`index = 0,1,2`,
  2370. i.e., [3, 3, 3].
  2371. Finally, the output is [3, 3, 3].
  2372. Raises:
  2373. TypeError: If `begin_mask`, `end_mask`, `ellipsis_mask`, `new_axis_mask` or `shrink_axis_mask` is not an int.
  2374. TypeError: If `begin`, `end` or `strides` is not a tuple.
  2375. ValueError: If `begin_mask`, `end_mask`, `ellipsis_mask`, `new_axis_mask` or `shrink_axis_mask` is less than 0.
  2376. Supported Platforms:
  2377. ``Ascend`` ``GPU`` ``CPU``
  2378. Examples:
  2379. >>> input_x = Tensor([[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]],
  2380. ... [[5, 5, 5], [6, 6, 6]]], mindspore.float32)
  2381. >>> slice = ops.StridedSlice()
  2382. >>> output = slice(input_x, (1, 0, 0), (2, 1, 3), (1, 1, 1))
  2383. >>> print(output)
  2384. [[[3. 3. 3.]]]
  2385. """
  2386. @prim_attr_register
  2387. def __init__(self,
  2388. begin_mask=0,
  2389. end_mask=0,
  2390. ellipsis_mask=0,
  2391. new_axis_mask=0,
  2392. shrink_axis_mask=0):
  2393. """Initialize StridedSlice"""
  2394. self.init_prim_io_names(inputs=['x', 'begin', 'end', 'strides'], outputs=['output'])
  2395. validator.check_non_negative_int(begin_mask, 'begin_mask', self.name)
  2396. validator.check_non_negative_int(end_mask, 'end_mask', self.name)
  2397. validator.check_non_negative_int(ellipsis_mask, 'ellipsis_mask', self.name)
  2398. if len(tuple(filter(lambda x: x == '1', bin(ellipsis_mask)[-1:1:-1]))) > 1:
  2399. raise ValueError(f"For '{self.name}', only support one ellipsis in the index, but got {end_mask}.")
  2400. validator.check_non_negative_int(new_axis_mask, 'new_axis_mask', self.name)
  2401. validator.check_non_negative_int(shrink_axis_mask, 'shrink_axis_mask', self.name)
  2402. def __infer__(self, x, begin, end, strides):
  2403. begin_v, end_v, strides_v = begin['value'], end['value'], strides['value']
  2404. validator.check_value_type("begin", begin_v, [tuple], self.name)
  2405. validator.check_value_type("end", end_v, [tuple], self.name)
  2406. validator.check_value_type("strides", strides_v, [tuple], self.name)
  2407. if tuple(filter(lambda x: not isinstance(x, int), begin_v + end_v + strides_v)):
  2408. raise TypeError(f"For {self.name}, both the begins, ends, and strides must be a tuple of int, "
  2409. f"but got begins: {begin_v}, ends: {end_v}, strides: {strides_v}.")
  2410. if tuple(filter(lambda x: x == 0, strides_v)):
  2411. raise ValueError(f"For '{self.name}', the strides cannot contain 0, but got strides: {strides_v}.")
  2412. if len(end_v) != len(begin_v) or len(strides_v) != len(begin_v):
  2413. raise ValueError(f"For '{self.name}' the length of begin index: {begin_v}, end index: {end_v} and "
  2414. f"strides: {strides_v} must be equal.")
  2415. ret_shape = self._compute_slicing_shape(x['shape'], begin_v, end_v, strides_v)
  2416. if all(ret_shape):
  2417. value = None
  2418. else:
  2419. init_func = Zero()
  2420. init_func.__enable_zero_dim__ = True
  2421. value = Tensor(dtype=x['dtype'].element_type(), shape=ret_shape, init=init_func)
  2422. if "max_value" in x and "min_value" in x:
  2423. validator.check_value_type("min_value", x["min_value"], [tuple, list], self.name)
  2424. validator.check_value_type("max_value", x["max_value"], [tuple, list], self.name)
  2425. max_value_np = np.array(x["max_value"])
  2426. min_value_np = np.array(x["min_value"])
  2427. slice_index = []
  2428. for begin_i, end_i, strides_i in zip(begin_v, end_v, strides_v):
  2429. s = slice(begin_i, end_i, strides_i)
  2430. slice_index.append(s)
  2431. slice_index = tuple(slice_index)
  2432. max_value_slice = max_value_np[slice_index]
  2433. min_value_slice = min_value_np[slice_index]
  2434. max_value_slice = tuple(max_value_slice.tolist())
  2435. min_value_slice = tuple(min_value_slice.tolist())
  2436. return {'shape': ret_shape,
  2437. 'dtype': x['dtype'],
  2438. 'value': value,
  2439. 'max_value': max_value_slice,
  2440. 'min_value': min_value_slice}
  2441. return {'shape': ret_shape,
  2442. 'dtype': x['dtype'],
  2443. 'value': value}
  2444. def _compute_slicing_shape(self, x_shape, begin_v, end_v, strides_v):
  2445. """Computes the shape of the slicing."""
  2446. x_rank = len(x_shape)
  2447. slice_len = len(begin_v)
  2448. # After the integer is converted to binary, it is a str and the first two chars are the flag char '0b'.
  2449. begin_pos = bin(self.begin_mask)[-1:1:-1]
  2450. end_pos = bin(self.end_mask)[-1:1:-1]
  2451. ellipsis_pos = bin(self.ellipsis_mask)[-1:1:-1]
  2452. new_axis_pos = bin(self.new_axis_mask)[-1:1:-1]
  2453. shrink_axis_pos = bin(self.shrink_axis_mask)[-1:1:-1]
  2454. ret_shape = []
  2455. i, j = 0, 0
  2456. has_ellipsis = False
  2457. while i < x_rank or j < slice_len:
  2458. if j < slice_len:
  2459. begin, end, stride = begin_v[j], end_v[j], strides_v[j]
  2460. if j < len(ellipsis_pos) and ellipsis_pos[j] == '1':
  2461. # When there is ellipsis, the latter part of the ellipsis will be processed separately.
  2462. has_ellipsis = True
  2463. break
  2464. if j < len(begin_pos) and begin_pos[j] == '1':
  2465. begin = -1 if strides_v[j] < 0 else 0
  2466. if j < len(end_pos) and end_pos[j] == '1':
  2467. end = -(x_shape[i] + 1) if strides_v[j] < 0 else x_shape[i]
  2468. if j < len(new_axis_pos) and new_axis_pos[j] == '1':
  2469. ret_shape.append(1)
  2470. j += 1
  2471. continue
  2472. if j < len(shrink_axis_pos) and shrink_axis_pos[j] == '1':
  2473. if (not -x_shape[i] <= begin < x_shape[i]) or stride < 0:
  2474. raise IndexError(f"For {self.name}, when shrink axis, the stride cannot be negative number, "
  2475. f"and begin should be in [-{x_shape[i]}, {x_shape[i]}), "
  2476. f"but got stride: {stride}, begin: {begin}.")
  2477. j += 1
  2478. i += 1
  2479. continue
  2480. else:
  2481. begin, end, stride = 0, x_shape[i], 1
  2482. slicing_length = _compute_slicing_length(begin, end, stride, x_shape, i)
  2483. ret_shape.append(slicing_length)
  2484. i += 1
  2485. j += 1
  2486. if has_ellipsis:
  2487. # When there is ellipsis, handle the second half of the ellipsis split.
  2488. ellipsis_occupied_dims = x_rank - i - (slice_len - (j + 1)) + \
  2489. len(tuple(filter(lambda x: x == '1', new_axis_pos[j + 1:slice_len])))
  2490. ret_shape.extend(x_shape[i:i + ellipsis_occupied_dims])
  2491. j += 1
  2492. i += ellipsis_occupied_dims
  2493. while i < x_rank or j < slice_len:
  2494. begin, end, stride = begin_v[j], end_v[j], strides_v[j]
  2495. if j < len(begin_pos) and begin_pos[j] == '1':
  2496. begin = -1 if strides_v[j] < 0 else 0
  2497. if j < len(end_pos) and end_pos[j] == '1':
  2498. end = -(x_shape[i] + 1) if strides_v[j] < 0 else x_shape[i]
  2499. if j < len(new_axis_pos) and new_axis_pos[j] == '1':
  2500. ret_shape.append(1)
  2501. j += 1
  2502. continue
  2503. if j < len(shrink_axis_pos) and shrink_axis_pos[j] == '1':
  2504. if (not -x_shape[i] <= begin < x_shape[i]) or stride < 0:
  2505. raise ValueError(f"For {self.name}, when shrink axis, the stride cannot be negative number, "
  2506. f"and begin should be in [-{x_shape[i]}, {x_shape[i]}), "
  2507. f"but got stride: {stride}, begin: {begin}.")
  2508. j += 1
  2509. i += 1
  2510. continue
  2511. slicing_length = _compute_slicing_length(begin, end, stride, x_shape, i)
  2512. ret_shape.append(slicing_length)
  2513. i += 1
  2514. j += 1
  2515. return ret_shape
  2516. class Diag(PrimitiveWithInfer):
  2517. r"""
  2518. Constructs a diagonal tensor with a given diagonal values.
  2519. Assume `input_x` has dimensions :math:`[D_1,... D_k]`, the output is a tensor of
  2520. rank 2k with dimensions :math:`[D_1,..., D_k, D_1,..., D_k]` where:
  2521. :math:`output[i_1,..., i_k, i_1,..., i_k] = input_x[i_1,..., i_k]` and 0 everywhere else.
  2522. Inputs:
  2523. - **input_x** (Tensor) - The input tensor. The input shape must be less than 5d.
  2524. Outputs:
  2525. Tensor, has the same dtype as the `input_x`.
  2526. Examples:
  2527. >>> input_x = Tensor([1, 2, 3, 4])
  2528. >>> diag = ops.Diag()
  2529. >>> output = diag(input_x)
  2530. >>> print(output)
  2531. [[1, 0, 0, 0],
  2532. [0, 2, 0, 0],
  2533. [0, 0, 3, 0],
  2534. [0, 0, 0, 4]]
  2535. """
  2536. @prim_attr_register
  2537. def __init__(self):
  2538. """Initialize Diag"""
  2539. def infer_dtype(self, x_type):
  2540. validator.check_subclass('input_x', x_type, mstype.tensor, self.name)
  2541. return x_type
  2542. def infer_shape(self, x_shape):
  2543. validator.check("x rank", len(x_shape), "", 1, Rel.GE)
  2544. ret_shape = copy.deepcopy(x_shape)
  2545. ret_shape = ret_shape + ret_shape
  2546. return ret_shape
  2547. def infer_value(self, x):
  2548. if x is None:
  2549. return None
  2550. # do constant-folding only when x rank is 1
  2551. if len(x.shape) != 1:
  2552. return None
  2553. ret = np.diag(x.asnumpy())
  2554. return Tensor(ret)
  2555. class DiagPart(PrimitiveWithInfer):
  2556. r"""
  2557. Extracts the diagonal part from given tensor.
  2558. Assume input has dimensions :math:`[D_1,..., D_k, D_1,..., D_k]`, the output is a tensor
  2559. of rank k with dimensions :math:`[D_1,..., D_k]` where:
  2560. :math:`output[i_1,..., i_k] = input[i_1,..., i_k, i_1,..., i_k]`.
  2561. Inputs:
  2562. - **input_x** (Tensor) - tensor of rank k where k is even and not zero.
  2563. Outputs:
  2564. Tensor, the extracted diagonal has the same dtype as the `input_x`.
  2565. Examples
  2566. >>> input_x = Tensor([[1, 0, 0, 0],
  2567. ... [0, 2, 0, 0],
  2568. ... [0, 0, 3, 0],
  2569. ... [0, 0, 0, 4]])
  2570. >>> diag_part = ops.DiagPart()
  2571. >>> output = diag_part(input_x)
  2572. >>> print(output)
  2573. [1 2 3 4]
  2574. """
  2575. @prim_attr_register
  2576. def __init__(self):
  2577. """Initialize DiagPart"""
  2578. def infer_dtype(self, x_type):
  2579. validator.check_subclass('input_x', x_type, mstype.tensor, self.name)
  2580. return x_type
  2581. def infer_shape(self, x_shape):
  2582. if len(x_shape) % 2 != 0 or \
  2583. not x_shape:
  2584. raise ValueError(f"For \'{self.name}\' input rank must be non-zero and even, but got rank {len(x_shape)}, "
  2585. f"with shapes {x_shape}")
  2586. length = len(x_shape) // 2
  2587. for i in range(length):
  2588. validator.check('input_shape[i + len(input_shape)/2]', x_shape[i + length],
  2589. 'input_shape[i]', x_shape[i], Rel.EQ, self.name)
  2590. ret_shape = x_shape[0:length]
  2591. return ret_shape
  2592. def infer_value(self, x):
  2593. if x is None:
  2594. return None
  2595. # do constant-folding only when x rank is 2
  2596. if len(x.shape) != 2:
  2597. return None
  2598. ret = np.diag(x.asnumpy())
  2599. return Tensor(ret)
  2600. class Eye(PrimitiveWithInfer):
  2601. """
  2602. Creates a tensor with ones on the diagonal and zeros the rest.
  2603. Inputs:
  2604. - **n** (int) - The number of rows of returned tensor
  2605. - **m** (int) - The number of columns of returned tensor
  2606. - **t** (mindspore.dtype) - MindSpore's dtype, The data type of the returned tensor.
  2607. Outputs:
  2608. Tensor, a tensor with ones on the diagonal and the rest of elements are zero.
  2609. Raises:
  2610. TypeError: If `m` or `n` is not an int.
  2611. ValueError: If `m` or `n` is less than 1.
  2612. Supported Platforms:
  2613. ``Ascend`` ``GPU`` ``CPU``
  2614. Examples:
  2615. >>> eye = ops.Eye()
  2616. >>> output = eye(2, 2, mindspore.int32)
  2617. >>> print(output)
  2618. [[1 0]
  2619. [0 1]]
  2620. """
  2621. @prim_attr_register
  2622. def __init__(self):
  2623. """Initialize Eye"""
  2624. def infer_value(self, n, m, t):
  2625. validator.check_positive_int(n, "n", self.name)
  2626. validator.check_positive_int(m, "m", self.name)
  2627. args = {"dtype": t}
  2628. validator.check_types_same_and_valid(args, mstype.number_type + (mstype.bool_,), self.name)
  2629. np_type = mstype.dtype_to_nptype(t)
  2630. ret = np.eye(n, m, dtype=np_type)
  2631. return Tensor(ret)
  2632. class ScatterNd(PrimitiveWithInfer):
  2633. r"""
  2634. Scatters a tensor into a new tensor depending on the specified indices.
  2635. Creates an empty tensor with the given `shape`, and set values by scattering the update tensor depending on indices.
  2636. The empty tensor has rank P and `indices` has rank Q where `Q >= 2`.
  2637. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`.
  2638. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of the empty tensor.
  2639. `updates` is a tensor of rank `Q-1+P-N`. Its shape is: :math:`(i_0, i_1, ..., i_{Q-2}, shape_N, ..., shape_{P-1})`.
  2640. Inputs:
  2641. - **indices** (Tensor) - The index of scattering in the new tensor with int32 data type.
  2642. The rank of indices must be at least 2 and `indices_shape[-1] <= len(shape)`.
  2643. - **updates** (Tensor) - The source Tensor to be scattered.
  2644. It has shape `indices_shape[:-1] + shape[indices_shape[-1]:]`.
  2645. - **shape** (tuple[int]) - Define the shape of the output tensor, has the same type as indices.
  2646. Outputs:
  2647. Tensor, the new tensor, has the same type as `update` and the same shape as `shape`.
  2648. Raises:
  2649. TypeError: If `shape` is not a tuple.
  2650. ValueError: If any element of `shape` is less than 1.
  2651. Supported Platforms:
  2652. ``Ascend`` ``GPU``
  2653. Examples:
  2654. >>> op = ops.ScatterNd()
  2655. >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32)
  2656. >>> updates = Tensor(np.array([3.2, 1.1]), mindspore.float32)
  2657. >>> shape = (3, 3)
  2658. >>> output = op(indices, updates, shape)
  2659. >>> print(output)
  2660. [[0. 3.2 0. ]
  2661. [0. 1.1 0. ]
  2662. [0. 0. 0. ]]
  2663. """
  2664. @prim_attr_register
  2665. def __init__(self):
  2666. """Initialize ScatterNd"""
  2667. self.init_prim_io_names(inputs=['indices', 'update', 'shape'], outputs=['output'])
  2668. def __infer__(self, indices, update, shape):
  2669. shp = shape['value']
  2670. validator.check_subclass("update_dtype", update['dtype'], mstype.tensor, self.name)
  2671. validator.check_tensor_dtype_valid("indices", indices['dtype'], [mstype.int32, mstype.int64], self.name)
  2672. validator.check_value_type("shape", shp, [tuple], self.name)
  2673. for i, x in enumerate(shp):
  2674. validator.check_positive_int(x, f'shape[{i}]', self.name)
  2675. indices_shape, update_shape = indices["shape"], update["shape"]
  2676. if indices_shape[0] != update_shape[0]:
  2677. raise ValueError(f'For \'{self.name}\' The indices_shape[0] and update_shape[0] must be equal.')
  2678. return {'shape': shp,
  2679. 'dtype': update['dtype'],
  2680. 'value': None}
  2681. class ResizeNearestNeighbor(PrimitiveWithInfer):
  2682. r"""
  2683. Resizes the input tensor by using the nearest neighbor algorithm.
  2684. Resizes the input tensor to a given size by using the nearest neighbor algorithm. The nearest
  2685. neighbor algorithm selects the value of the nearest point and does not consider the
  2686. values of neighboring points at all, yielding a piecewise-constant interpolant.
  2687. Args:
  2688. size (Union[tuple, list]): The target size. The dimension of size must be 2.
  2689. align_corners (bool): Whether the centers of the 4 corner pixels of the input
  2690. and output tensors are aligned. Default: False.
  2691. Inputs:
  2692. - **input_x** (Tensor) - The input tensor. The shape of the tensor is :math:`(N, C, H, W)`.
  2693. Outputs:
  2694. Tensor, the shape of the output tensor is :math:`(N, C, NEW\_H, NEW\_W)`.
  2695. Raises:
  2696. TypeError: If `size` is neither tuple nor list.
  2697. TypeError: If `align_corners` is not a bool.
  2698. ValueError: If length of `size` is not equal to 2.
  2699. Supported Platforms:
  2700. ``Ascend`` ``GPU`` ``CPU``
  2701. Examples:
  2702. >>> input_tensor = Tensor(np.array([[[[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]]]), mindspore.float32)
  2703. >>> resize = ops.ResizeNearestNeighbor((2, 2))
  2704. >>> output = resize(input_tensor)
  2705. >>> print(output)
  2706. [[[[-0.1 0.3]
  2707. [ 0.4 0.5]]]]
  2708. """
  2709. @prim_attr_register
  2710. def __init__(self, size, align_corners=False):
  2711. """Initialize ResizeNearestNeighbor"""
  2712. validator.check_value_type("size", size, [tuple, list], self.name)
  2713. validator.check_value_type("align_corners", align_corners, [bool], self.name)
  2714. validator.check_equal_int(len(size), 2, "length of size", self.name)
  2715. for i, value in enumerate(size):
  2716. validator.check_non_negative_int(value, f'{i}th value of size', self.name)
  2717. self.init_prim_io_names(inputs=['image_in'], outputs=['image_out'])
  2718. def infer_shape(self, x_shape):
  2719. validator.check('the dimension of input_x', len(x_shape), '', 4, Rel.EQ, self.name)
  2720. return tuple(x_shape)[:-2] + tuple(self.size)
  2721. def infer_dtype(self, x_dtype):
  2722. validator.check_tensor_dtype_valid("x", x_dtype, mstype.number_type, self.name)
  2723. return x_dtype
  2724. class GatherNd(PrimitiveWithInfer):
  2725. r"""
  2726. Gathers slices from a tensor by indices.
  2727. Using given indices to gather slices from a tensor with a specified shape.
  2728. `indices` is an K-dimensional integer tensor. Supposes it as a (K-1)-dimensional tensor and each element of it
  2729. defines a slice of `input_x`:
  2730. .. math::
  2731. output[(i_0, ..., i_{K-2})] = input\_x[indices[(i_0, ..., i_{K-2})]]
  2732. The last dimension of `indices` can not more than the rank of `input_x`:
  2733. :math:`indices.shape[-1] <= input\_x.rank`.
  2734. Inputs:
  2735. - **input_x** (Tensor) - The target tensor to gather values.
  2736. - **indices** (Tensor) - The index tensor, with int data type.
  2737. Outputs:
  2738. Tensor, has the same type as `input_x` and the shape is indices_shape[:-1] + x_shape[indices_shape[-1]:].
  2739. Raises:
  2740. ValueError: If length of shape of `input_x` is less than the last dimension of `indices`.
  2741. Supported Platforms:
  2742. ``Ascend`` ``GPU`` ``CPU``
  2743. Examples:
  2744. >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  2745. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2746. >>> op = ops.GatherNd()
  2747. >>> output = op(input_x, indices)
  2748. >>> print(output)
  2749. [-0.1 0.5]
  2750. """
  2751. @prim_attr_register
  2752. def __init__(self):
  2753. """Initialize GatherNd"""
  2754. self.init_prim_io_names(inputs=['input_x', 'indices'], outputs=['y'])
  2755. def infer_shape(self, x_shape, indices_shape):
  2756. validator.check('the dimension of x', len(x_shape),
  2757. 'the dimension of indices', indices_shape[-1], Rel.GE, self.name)
  2758. return indices_shape[:-1] + x_shape[indices_shape[-1]:]
  2759. def infer_dtype(self, x_dtype, indices_dtype):
  2760. validator.check_tensor_dtype_valid("indices", indices_dtype, mstype.int_type, self.name)
  2761. return x_dtype
  2762. class TensorScatterUpdate(PrimitiveWithInfer):
  2763. """
  2764. Creates a new tensor by updating the positions in `input_x` indicicated by
  2765. `indices`, with values from `update`. This operation is almost equivalent to using
  2766. ScatterNd, except that the updates are applied on `input_x` instead of a zero tensor.
  2767. `indices` must have rank at least 2, the last axis is the depth of each index
  2768. vectors. For each index vector, there must be a corresponding value in `update`. If
  2769. the depth of each index tensor matches the rank of `input_x`, then each index
  2770. vector corresponds to a scalar in `input_x` and each update updates a scalar. If
  2771. the depth of each index tensor is less than the rank of `input_x`, then each index
  2772. vector corresponds to a slice in `input_x`, and each update updates a slice.
  2773. The order in which updates are applied is nondeterministic, meaning that if there
  2774. are multiple index vectors in `indices` that correspond to the same position, the
  2775. value of that position in the output will be nondeterministic.
  2776. Inputs:
  2777. - **input_x** (Tensor) - The target tensor. The dimension of input_x must be no less than indices.shape[-1].
  2778. - **indices** (Tensor) - The index of input tensor whose data type is int32 or int64.
  2779. The rank must be at least 2.
  2780. - **update** (Tensor) - The tensor to update the input tensor, has the same type as input,
  2781. and update.shape = indices.shape[:-1] + input_x.shape[indices.shape[-1]:].
  2782. Outputs:
  2783. Tensor, has the same shape and type as `input_x`.
  2784. Raises:
  2785. TypeError: If dtype of `indices` is neither int32 nor int64.
  2786. ValueError: If length of shape of `input_x` is less than the last dimension of shape of `indices`.
  2787. Supported Platforms:
  2788. ``Ascend`` ``GPU``
  2789. Examples:
  2790. >>> input_x = Tensor(np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]]), mindspore.float32)
  2791. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2792. >>> update = Tensor(np.array([1.0, 2.2]), mindspore.float32)
  2793. >>> op = ops.TensorScatterUpdate()
  2794. >>> output = op(input_x, indices, update)
  2795. >>> print(output)
  2796. [[ 1. 0.3 3.6]
  2797. [ 0.4 2.2 -3.2]]
  2798. """
  2799. @prim_attr_register
  2800. def __init__(self):
  2801. """Initialize TensorScatterUpdate"""
  2802. self.init_prim_io_names(inputs=['x', 'indices', 'value'], outputs=['y'])
  2803. def infer_shape(self, x_shape, indices_shape, value_shape):
  2804. validator.check('the dimension of x', len(x_shape),
  2805. 'the dimension of indices', indices_shape[-1], Rel.GE)
  2806. if indices_shape[:-1] + x_shape[indices_shape[-1]:] != value_shape:
  2807. raise ValueError("For 'TensorScatterUpdate', input value are not match with input indices.")
  2808. return x_shape
  2809. def infer_dtype(self, x_dtype, indices_dtype, value_dtype):
  2810. validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32, mstype.int64], self.name)
  2811. args = {"x": x_dtype, "value": value_dtype}
  2812. validator.check_tensors_dtypes_same_and_valid(args, (mstype.bool_,) + mstype.number_type, self.name)
  2813. return x_dtype
  2814. class ScatterUpdate(_ScatterOp_Dynamic):
  2815. r"""
  2816. Updates tensor values by using input indices and value.
  2817. Using given values to update tensor value, along with the input indices.
  2818. for each `i, ..., j` in `indices.shape`:
  2819. .. math::
  2820. \text{input_x}[\text{indices}[i, ..., j], :] = \text{updates}[i, ..., j, :]
  2821. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2822. If they have different data types, lower priority data type will be converted to
  2823. relatively highest priority data type.
  2824. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2825. Args:
  2826. use_locking (bool): Whether protect the assignment by a lock. Default: True.
  2827. Inputs:
  2828. - **input_x** (Parameter) - The target tensor, with data type of Parameter.
  2829. - **indices** (Tensor) - The index of input tensor. With int32 data type.
  2830. If there are duplicates in indices, the order for updating is undefined.
  2831. - **updates** (Tensor) - The tensor to update the input tensor, has the same type as input,
  2832. and updates.shape = indices.shape + input_x.shape[1:].
  2833. Outputs:
  2834. Tensor, has the same shape and type as `input_x`.
  2835. Raises:
  2836. TypeError: If `use_locking` is not a bool.
  2837. Supported Platforms:
  2838. ``Ascend`` ``GPU`` ``CPU``
  2839. Examples:
  2840. >>> np_x = np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]])
  2841. >>> input_x = mindspore.Parameter(Tensor(np_x, mindspore.float32), name="x")
  2842. >>> indices = Tensor(np.array([0, 1]), mindspore.int32)
  2843. >>> np_updates = np.array([[2.0, 1.2, 1.0], [3.0, 1.2, 1.0]])
  2844. >>> updates = Tensor(np_updates, mindspore.float32)
  2845. >>> op = ops.ScatterUpdate()
  2846. >>> output = op(input_x, indices, updates)
  2847. >>> print(output)
  2848. [[2. 1.2 1. ]
  2849. [3. 1.2 1. ]]
  2850. """
  2851. @prim_attr_register
  2852. def __init__(self, use_locking=True):
  2853. """Initialize ScatterUpdate"""
  2854. validator.check_value_type('use_locking', use_locking, [bool], self.name)
  2855. self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y'])
  2856. self.add_prim_attr('side_effect_mem', True)
  2857. class ScatterNdUpdate(_ScatterNdOp):
  2858. r"""
  2859. Updates tensor values by using input indices and value.
  2860. Using given values to update tensor value, along with the input indices.
  2861. `input_x` has rank P and `indices` has rank Q where `Q >= 2`.
  2862. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`.
  2863. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of `input_x`.
  2864. `updates` is a tensor of rank `Q-1+P-N`. Its shape is:
  2865. :math:`(i_0, i_1, ..., i_{Q-2}, x\_shape_N, ..., x\_shape_{P-1})`.
  2866. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2867. If they have different data types, lower priority data type will be converted to
  2868. relatively highest priority data type.
  2869. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2870. Args:
  2871. use_locking (bool): Whether protect the assignment by a lock. Default: True.
  2872. Inputs:
  2873. - **input_x** (Parameter) - The target tensor, with data type of Parameter.
  2874. - **indices** (Tensor) - The index of input tensor, with int32 data type.
  2875. The rank of indices must be at least 2 and `indices_shape[-1] <= len(shape)`.
  2876. - **updates** (Tensor) - The tensor to be updated to the input tensor, has the same type as input.
  2877. The shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`.
  2878. Outputs:
  2879. Tensor, has the same shape and type as `input_x`.
  2880. Raises:
  2881. TypeError: If `use_locking` is not a bool.
  2882. Supported Platforms:
  2883. ``Ascend`` ``CPU``
  2884. Examples:
  2885. >>> np_x = np.array([[-0.1, 0.3, 3.6], [0.4, 0.5, -3.2]])
  2886. >>> input_x = mindspore.Parameter(Tensor(np_x, mindspore.float32), name="x")
  2887. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2888. >>> updates = Tensor(np.array([1.0, 2.2]), mindspore.float32)
  2889. >>> op = ops.ScatterNdUpdate()
  2890. >>> output = op(input_x, indices, updates)
  2891. >>> print(output)
  2892. [[1. 0.3 3.6]
  2893. [0.4 2.2 -3.2]]
  2894. """
  2895. @prim_attr_register
  2896. def __init__(self, use_locking=True):
  2897. """Initialize ScatterNdUpdate"""
  2898. validator.check_value_type('use_locking', use_locking, [bool], self.name)
  2899. self.init_prim_io_names(inputs=['x', 'indices', 'value'], outputs=['y'])
  2900. self.add_prim_attr('side_effect_mem', True)
  2901. def infer_dtype(self, x_dtype, indices_dtype, value_dtype):
  2902. validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32], self.name)
  2903. args = {"x": x_dtype, "value": value_dtype}
  2904. validator.check_tensors_dtypes_same_and_valid(args, (mstype.bool_,) + mstype.number_type, self.name)
  2905. return x_dtype
  2906. class ScatterMax(_ScatterOp):
  2907. r"""
  2908. Updates the value of the input tensor through the maximum operation.
  2909. Using given values to update tensor value through the max operation, along with the input indices.
  2910. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2911. for each `i, ..., j` in `indices.shape`:
  2912. .. math::
  2913. \text{input_x}[\text{indices}[i, ..., j], :]
  2914. = max(\text{input_x}[\text{indices}[i, ..., j], :], \text{updates}[i, ..., j, :])
  2915. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2916. If they have different data types, lower priority data type will be converted to
  2917. relatively highest priority data type.
  2918. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2919. Args:
  2920. use_locking (bool): Whether protect the assignment by a lock. Default: True.
  2921. Inputs:
  2922. - **input_x** (Parameter) - The target parameter.
  2923. - **indices** (Tensor) - The index to do max operation whose data type must be mindspore.int32.
  2924. - **updates** (Tensor) - The tensor that performs the maximum operation with `input_x`,
  2925. the data type is the same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  2926. Outputs:
  2927. Parameter, the updated `input_x`.
  2928. Raises:
  2929. TypeError: If `use_locking` is not a bool.
  2930. Supported Platforms:
  2931. ``Ascend`` ``CPU``
  2932. Examples:
  2933. >>> input_x = Parameter(Tensor(np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]), mindspore.float32), name="input_x")
  2934. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2935. >>> updates = Tensor(np.ones([2, 2, 3]) * 88, mindspore.float32)
  2936. >>> scatter_max = ops.ScatterMax()
  2937. >>> output = scatter_max(input_x, indices, updates)
  2938. >>> print(output)
  2939. [[88. 88. 88.]
  2940. [88. 88. 88.]]
  2941. """
  2942. class ScatterMin(_ScatterOp):
  2943. r"""
  2944. Updates the value of the input tensor through the minimum operation.
  2945. Using given values to update tensor value through the min operation, along with the input indices.
  2946. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2947. for each `i, ..., j` in `indices.shape`:
  2948. .. math::
  2949. \text{input_x}[\text{indices}[i, ..., j], :]
  2950. = min(\text{input_x}[\text{indices}[i, ..., j], :], \text{updates}[i, ..., j, :])
  2951. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2952. If they have different data types, lower priority data type will be converted to
  2953. relatively highest priority data type.
  2954. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2955. Args:
  2956. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  2957. Inputs:
  2958. - **input_x** (Parameter) - The target parameter.
  2959. - **indices** (Tensor) - The index to do min operation whose data type must be mindspore.int32.
  2960. - **updates** (Tensor) - The tensor doing the min operation with `input_x`,
  2961. the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  2962. Outputs:
  2963. Parameter, the updated `input_x`.
  2964. Raises:
  2965. TypeError: If `use_locking` is not a bool.
  2966. Supported Platforms:
  2967. ``Ascend`` ``CPU``
  2968. Examples:
  2969. >>> input_x = Parameter(Tensor(np.array([[0.0, 1.0, 2.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="input_x")
  2970. >>> indices = Tensor(np.array([[0, 0], [1, 1]]), mindspore.int32)
  2971. >>> update = Tensor(np.ones([2, 2, 3]), mindspore.float32)
  2972. >>> scatter_min = ops.ScatterMin()
  2973. >>> output = scatter_min(input_x, indices, update)
  2974. >>> print(output)
  2975. [[0. 1. 1.]
  2976. [0. 0. 0.]]
  2977. """
  2978. class ScatterAdd(_ScatterOp_Dynamic):
  2979. r"""
  2980. Updates the value of the input tensor through the addition operation.
  2981. Using given values to update tensor value through the add operation, along with the input indices.
  2982. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  2983. for each `i, ..., j` in `indices.shape`:
  2984. .. math::
  2985. \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{+}= \text{updates}[i, ..., j, :]
  2986. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  2987. If they have different data types, lower priority data type will be converted to
  2988. relatively highest priority data type.
  2989. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2990. Args:
  2991. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  2992. Inputs:
  2993. - **input_x** (Parameter) - The target parameter.
  2994. - **indices** (Tensor) - The index to do add operation whose data type must be mindspore.int32.
  2995. - **updates** (Tensor) - The tensor that performs the add operation with `input_x`,
  2996. the data type is the same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  2997. Outputs:
  2998. Parameter, the updated `input_x`.
  2999. Raises:
  3000. TypeError: If `use_locking` is not a bool.
  3001. Supported Platforms:
  3002. ``Ascend`` ``GPU`` ``CPU``
  3003. Examples:
  3004. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]), mindspore.float32), name="x")
  3005. >>> indices = Tensor(np.array([[0, 1], [1, 1]]), mindspore.int32)
  3006. >>> updates = Tensor(np.ones([2, 2, 3]), mindspore.float32)
  3007. >>> scatter_add = ops.ScatterAdd()
  3008. >>> output = scatter_add(input_x, indices, updates)
  3009. >>> print(output)
  3010. [[1. 1. 1.]
  3011. [3. 3. 3.]]
  3012. """
  3013. @prim_attr_register
  3014. def __init__(self, use_locking=False):
  3015. """Initialize ScatterAdd"""
  3016. validator.check_value_type('use_locking', use_locking, [bool], self.name)
  3017. self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y'])
  3018. self.add_prim_attr('side_effect_mem', True)
  3019. class ScatterSub(_ScatterOp):
  3020. r"""
  3021. Updates the value of the input tensor through the subtraction operation.
  3022. Using given values to update tensor value through the subtraction operation, along with the input indices.
  3023. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  3024. for each `i, ..., j` in `indices.shape`:
  3025. .. math::
  3026. \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{-}= \text{updates}[i, ..., j, :]
  3027. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  3028. If they have different data types, lower priority data type will be converted to
  3029. relatively highest priority data type.
  3030. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  3031. Args:
  3032. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  3033. Inputs:
  3034. - **input_x** (Parameter) - The target parameter.
  3035. - **indices** (Tensor) - The index to perform the subtraction operation
  3036. whose data type must be mindspore.int32.
  3037. - **updates** (Tensor) - The tensor that performs the subtraction operation with `input_x`,
  3038. the data type is the same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  3039. Outputs:
  3040. Parameter, the updated `input_x`.
  3041. Raises:
  3042. TypeError: If `use_locking` is not a bool.
  3043. Supported Platforms:
  3044. ``Ascend`` ``CPU``
  3045. Examples:
  3046. >>> input_x = Parameter(Tensor(np.array([[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]), mindspore.float32), name="x")
  3047. >>> indices = Tensor(np.array([[0, 1]]), mindspore.int32)
  3048. >>> updates = Tensor(np.array([[[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]]), mindspore.float32)
  3049. >>> scatter_sub = ops.ScatterSub()
  3050. >>> output = scatter_sub(input_x, indices, updates)
  3051. >>> print(output)
  3052. [[-1. -1. -1.]
  3053. [-1. -1. -1.]]
  3054. """
  3055. class ScatterMul(_ScatterOp):
  3056. r"""
  3057. Updates the value of the input tensor through the multiply operation.
  3058. Using given values to update tensor value through the mul operation, along with the input indices.
  3059. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  3060. for each `i, ..., j` in `indices.shape`:
  3061. .. math::
  3062. \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{*}= \text{updates}[i, ..., j, :]
  3063. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  3064. If they have different data types, lower priority data type will be converted to
  3065. relatively highest priority data type.
  3066. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  3067. Args:
  3068. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  3069. Inputs:
  3070. - **input_x** (Parameter) - The target parameter.
  3071. - **indices** (Tensor) - The index to do mul operation whose data type must be mindspore.int32.
  3072. - **updates** (Tensor) - The tensor doing the mul operation with `input_x`,
  3073. the data type is same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  3074. Outputs:
  3075. Parameter, the updated `input_x`.
  3076. Raises:
  3077. TypeError: If `use_locking` is not a bool.
  3078. Supported Platforms:
  3079. ``Ascend`` ``CPU``
  3080. Examples:
  3081. >>> input_x = Parameter(Tensor(np.array([[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x")
  3082. >>> indices = Tensor(np.array([0, 1]), mindspore.int32)
  3083. >>> updates = Tensor(np.array([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]), mindspore.float32)
  3084. >>> scatter_mul = ops.ScatterMul()
  3085. >>> output = scatter_mul(input_x, indices, updates)
  3086. >>> print(output)
  3087. [[2. 2. 2.]
  3088. [4. 4. 4.]]
  3089. """
  3090. class ScatterDiv(_ScatterOp):
  3091. r"""
  3092. Updates the value of the input tensor through the divide operation.
  3093. Using given values to update tensor value through the div operation, along with the input indices.
  3094. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  3095. for each `i, ..., j` in `indices.shape`:
  3096. .. math::
  3097. \text{input_x}[\text{indices}[i, ..., j], :] \mathrel{/}= \text{updates}[i, ..., j, :]
  3098. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  3099. If they have different data types, lower priority data type will be converted to
  3100. relatively highest priority data type.
  3101. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  3102. Args:
  3103. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  3104. Inputs:
  3105. - **input_x** (Parameter) - The target parameter.
  3106. - **indices** (Tensor) - The index to do div operation whose data type must be mindspore.int32.
  3107. - **updates** (Tensor) - The tensor that performs the div operation with `input_x`,
  3108. the data type is the same as `input_x`, the shape is `indices_shape + x_shape[1:]`.
  3109. Outputs:
  3110. Parameter, the updated `input_x`.
  3111. Raises:
  3112. TypeError: If `use_locking` is not a bool.
  3113. Supported Platforms:
  3114. ``Ascend`` ``CPU``
  3115. Examples:
  3116. >>> input_x = Parameter(Tensor(np.array([[6.0, 6.0, 6.0], [2.0, 2.0, 2.0]]), mindspore.float32), name="x")
  3117. >>> indices = Tensor(np.array([0, 1]), mindspore.int32)
  3118. >>> updates = Tensor(np.array([[2.0, 2.0, 2.0], [2.0, 2.0, 2.0]]), mindspore.float32)
  3119. >>> scatter_div = ops.ScatterDiv()
  3120. >>> output = scatter_div(input_x, indices, updates)
  3121. >>> print(output)
  3122. [[3. 3. 3.]
  3123. [1. 1. 1.]]
  3124. """
  3125. class ScatterNdAdd(_ScatterNdOp):
  3126. r"""
  3127. Applies sparse addition to individual values or slices in a tensor.
  3128. Using given values to update tensor value through the add operation, along with the input indices.
  3129. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  3130. `input_x` has rank P and `indices` has rank Q where `Q >= 2`.
  3131. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`.
  3132. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of `input_x`.
  3133. `updates` is a tensor of rank `Q-1+P-N`. Its shape is:
  3134. :math:`(i_0, i_1, ..., i_{Q-2}, x\_shape_N, ..., x\_shape_{P-1})`.
  3135. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  3136. If they have different data types, lower priority data type will be converted to
  3137. relatively highest priority data type.
  3138. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  3139. Args:
  3140. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  3141. Inputs:
  3142. - **input_x** (Parameter) - The target parameter.
  3143. - **indices** (Tensor) - The index to do add operation whose data type must be mindspore.int32.
  3144. The rank of indices must be at least 2 and `indices_shape[-1] <= len(shape)`.
  3145. - **updates** (Tensor) - The tensor doing the add operation with `input_x`,
  3146. the data type is same as `input_x`, the shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`.
  3147. Outputs:
  3148. Parameter, the updated `input_x`.
  3149. Raises:
  3150. TypeError: If `use_locking` is not a bool.
  3151. Supported Platforms:
  3152. ``Ascend``
  3153. Examples:
  3154. >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x")
  3155. >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32)
  3156. >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32)
  3157. >>> scatter_nd_add = ops.ScatterNdAdd()
  3158. >>> output = scatter_nd_add(input_x, indices, updates)
  3159. >>> print(output)
  3160. [ 1. 10. 9. 4. 12. 6. 7. 17.]
  3161. """
  3162. class ScatterNdSub(_ScatterNdOp):
  3163. r"""
  3164. Applies sparse subtraction to individual values or slices in a tensor.
  3165. Using given values to update tensor value through the subtraction operation, along with the input indices.
  3166. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  3167. `input_x` has rank P and `indices` has rank Q where `Q >= 2`.
  3168. `indices` has shape :math:`(i_0, i_1, ..., i_{Q-2}, N)` where `N <= P`.
  3169. The last dimension of `indices` (with length `N` ) indicates slices along the `N` th dimension of `input_x`.
  3170. `updates` is a tensor of rank `Q-1+P-N`. Its shape is:
  3171. :math:`(i_0, i_1, ..., i_{Q-2}, x\_shape_N, ..., x\_shape_{P-1})`.
  3172. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  3173. If they have different data types, lower priority data type will be converted to
  3174. relatively highest priority data type.
  3175. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  3176. Args:
  3177. use_locking (bool): Whether protect the assignment by a lock. Default: False.
  3178. Inputs:
  3179. - **input_x** (Parameter) - The target parameter.
  3180. - **indices** (Tensor) - The index to do add operation whose data type must be mindspore.int32.
  3181. The rank of indices must be at least 2 and `indices_shape[-1] <= len(shape)`.
  3182. - **updates** (Tensor) - The tensor that performs the subtraction operation with `input_x`,
  3183. the data type is the same as `input_x`, the shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`.
  3184. Outputs:
  3185. Parameter, the updated `input_x`.
  3186. Raises:
  3187. TypeError: If `use_locking` is not a bool.
  3188. Supported Platforms:
  3189. ``Ascend``
  3190. Examples:
  3191. >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x")
  3192. >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32)
  3193. >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32)
  3194. >>> scatter_nd_sub = ops.ScatterNdSub()
  3195. >>> output = scatter_nd_sub(input_x, indices, updates)
  3196. >>> print(output)
  3197. [ 1. -6. -3. 4. -2. 6. 7. -1.]
  3198. """
  3199. class ScatterNonAliasingAdd(_ScatterNdOp):
  3200. """
  3201. Applies sparse addition to the input using individual values or slices.
  3202. Using given values to update tensor value through the add operation, along with the input indices.
  3203. This operation outputs the `input_x` after the update is done, which makes it convenient to use the updated value.
  3204. Inputs of `input_x` and `updates` comply with the implicit type conversion rules to make the data types consistent.
  3205. If they have different data types, lower priority data type will be converted to
  3206. relatively highest priority data type.
  3207. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  3208. Inputs:
  3209. - **input_x** (Parameter) - The target parameter. The data type must be float16, float32 or int32.
  3210. - **indices** (Tensor) - The index to perform the addition operation whose data type must be mindspore.int32.
  3211. - **updates** (Tensor) - The tensor that performs the addition operation with `input_x`,
  3212. the data type is the same as `input_x`, the shape is `indices_shape[:-1] + x_shape[indices_shape[-1]:]`.
  3213. Outputs:
  3214. Parameter, the updated `input_x`.
  3215. Raises:
  3216. TypeError: If dtype of `indices` is not int32.
  3217. TypeError: If dtype of `input_x` is not one of float16, float32, int32.
  3218. Supported Platforms:
  3219. ``Ascend``
  3220. Examples:
  3221. >>> input_x = Parameter(Tensor(np.array([1, 2, 3, 4, 5, 6, 7, 8]), mindspore.float32), name="x")
  3222. >>> indices = Tensor(np.array([[2], [4], [1], [7]]), mindspore.int32)
  3223. >>> updates = Tensor(np.array([6, 7, 8, 9]), mindspore.float32)
  3224. >>> scatter_non_aliasing_add = ops.ScatterNonAliasingAdd()
  3225. >>> output = scatter_non_aliasing_add(input_x, indices, updates)
  3226. >>> print(output)
  3227. [ 1. 10. 9. 4. 12. 6. 7. 17.]
  3228. """
  3229. @prim_attr_register
  3230. def __init__(self):
  3231. """Initialize ScatterNonAliasingAdd"""
  3232. self.init_prim_io_names(inputs=['x', 'indices', 'updates'], outputs=['y'])
  3233. self.add_prim_attr('side_effect_mem', True)
  3234. def infer_dtype(self, x_dtype, indices_dtype, updates_dtype):
  3235. validator.check_tensor_dtype_valid('indices', indices_dtype, [mstype.int32], self.name)
  3236. args = {"x": x_dtype, "updates": updates_dtype}
  3237. validator.check_tensors_dtypes_same_and_valid(args, [mstype.float16, mstype.float32, mstype.int32], self.name)
  3238. return x_dtype
  3239. class SpaceToDepth(PrimitiveWithInfer):
  3240. r"""
  3241. Rearranges blocks of spatial data into depth.
  3242. The output tensor's `height` dimension is :math:`height / block\_size`.
  3243. The output tensor's `weight` dimension is :math:`weight / block\_size`.
  3244. The depth of output tensor is :math:`block\_size * block\_size * input\_depth`.
  3245. The input tensor's height and width must be divisible by `block_size`.
  3246. The data format is "NCHW".
  3247. Args:
  3248. block_size (int): The block size used to divide spatial data. It must be >= 2.
  3249. Inputs:
  3250. - **x** (Tensor) - The target tensor.
  3251. Outputs:
  3252. Tensor, the same data type as `x`. It must be a 4-D tensor.
  3253. Raises:
  3254. TypeError: If `block_size` is not an int.
  3255. ValueError: If `block_size` is less than 2.
  3256. ValueError: If length of shape of `x` is not equal to 4.
  3257. Supported Platforms:
  3258. ``Ascend`` ``GPU``
  3259. Examples:
  3260. >>> x = Tensor(np.random.rand(1,3,2,2), mindspore.float32)
  3261. >>> block_size = 2
  3262. >>> space_to_depth = ops.SpaceToDepth(block_size)
  3263. >>> output = space_to_depth(x)
  3264. >>> print(output.shape)
  3265. (1, 12, 1, 1)
  3266. """
  3267. @prim_attr_register
  3268. def __init__(self, block_size):
  3269. """Initialize SpaceToDepth"""
  3270. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  3271. validator.check_value_type('block_size', block_size, [int], self.name)
  3272. validator.check('block_size', block_size, '', 2, Rel.GE)
  3273. self.block_size = block_size
  3274. self.add_prim_attr("data_format", "NCHW")
  3275. def infer_shape(self, x_shape):
  3276. validator.check('x dimension', len(x_shape), '', 4, Rel.EQ)
  3277. out_shape = copy.deepcopy(x_shape)
  3278. for i in range(2):
  3279. if out_shape[i + 2] % self.block_size != 0:
  3280. raise ValueError(f'For \'{self.name}\' input shape[{i + 2}] {out_shape[i + 2]} should be '
  3281. f'fully divided by block_size {self.block_size}')
  3282. out_shape[i + 2] //= self.block_size
  3283. out_shape[1] *= self.block_size * self.block_size
  3284. return out_shape
  3285. def infer_dtype(self, x_dtype):
  3286. validator.check_subclass("x_dtype", x_dtype, mstype.tensor, self.name)
  3287. return x_dtype
  3288. class DepthToSpace(PrimitiveWithInfer):
  3289. r"""
  3290. Rearranges blocks of depth data into spatial dimensions.
  3291. This is the reverse operation of SpaceToDepth.
  3292. The depth of output tensor is :math:`input\_depth / (block\_size * block\_size)`.
  3293. The output tensor's `height` dimension is :math:`height * block\_size`.
  3294. The output tensor's `weight` dimension is :math:`weight * block\_size`.
  3295. The input tensor's depth must be divisible by `block_size * block_size`.
  3296. The data format is "NCHW".
  3297. Args:
  3298. block_size (int): The block size used to divide depth data. It must be >= 2.
  3299. Inputs:
  3300. - **x** (Tensor) - The target tensor. It must be a 4-D tensor with shape :math:`(N, C_{in}, H_{in}, W_{in})`.
  3301. Outputs:
  3302. Tensor of shape :math:`(N, C_{in} / \text{block_size}, H_{in} * \text{block_size}, W_{in} * \text{block_size})`.
  3303. Raises:
  3304. TypeError: If `block_size` is not an int.
  3305. ValueError: If `block_size` is less than 2.
  3306. ValueError: If length of shape of `x` is not equal to 4.
  3307. Supported Platforms:
  3308. ``Ascend`` ``GPU``
  3309. Examples:
  3310. >>> x = Tensor(np.random.rand(1, 12, 1, 1), mindspore.float32)
  3311. >>> block_size = 2
  3312. >>> depth_to_space = ops.DepthToSpace(block_size)
  3313. >>> output = depth_to_space(x)
  3314. >>> print(output.shape)
  3315. (1, 3, 2, 2)
  3316. """
  3317. @prim_attr_register
  3318. def __init__(self, block_size):
  3319. """Initialize DepthToSpace"""
  3320. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  3321. validator.check_value_type('block_size', block_size, [int], self.name)
  3322. validator.check('block_size', block_size, '', 2, Rel.GE, self.name)
  3323. self.block_size = block_size
  3324. self.add_prim_attr("data_format", "NCHW")
  3325. def infer_shape(self, x_shape):
  3326. validator.check('x dimension', len(x_shape), '', 4, Rel.EQ)
  3327. out_shape = copy.deepcopy(x_shape)
  3328. for i in range(2):
  3329. out_shape[i + 2] *= self.block_size
  3330. validator.check_int(x_shape[1] % (self.block_size * self.block_size),
  3331. 0, Rel.EQ, 'x_shape[1] % (block_size*block_size)', self.name)
  3332. out_shape[1] //= self.block_size * self.block_size
  3333. return out_shape
  3334. def infer_dtype(self, x_dtype):
  3335. validator.check_subclass("x_dtype", x_dtype, mstype.tensor, self.name)
  3336. return x_dtype
  3337. class SpaceToBatch(PrimitiveWithInfer):
  3338. r"""
  3339. Divides spatial dimensions into blocks and combines the block size with the original batch.
  3340. This operation will divide spatial dimensions (H, W) into blocks with `block_size`, the output tensor's H and W
  3341. dimension is the corresponding number of blocks after division. The output tensor's batch dimension is the
  3342. product of the original batch and the square of block_size. Before division, the spatial dimensions
  3343. of the input are zero padded according to paddings if necessary.
  3344. Args:
  3345. block_size (int): The block size of dividing blocks with value greater than or euqual to 2.
  3346. paddings (Union[tuple, list]): The padding values for H and W dimension, containing 2 subtraction lists.
  3347. Each subtraction list contains 2 integer value. All values must be greater than 0.
  3348. paddings[i] specifies the paddings for the spatial dimension i, which corresponds to the
  3349. input dimension i+2. It is required that input_shape[i+2]+paddings[i][0]+paddings[i][1]
  3350. is divisible by block_size.
  3351. Inputs:
  3352. - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor.
  3353. Outputs:
  3354. Tensor, the output tensor with the same data type as input. Assume input shape is :math:`(n, c, h, w)` with
  3355. :math:`block\_size` and :math:`paddings`. The shape of the output tensor will be :math:`(n', c', h', w')`,
  3356. where
  3357. :math:`n' = n*(block\_size*block\_size)`
  3358. :math:`c' = c`
  3359. :math:`h' = (h+paddings[0][0]+paddings[0][1])//block\_size`
  3360. :math:`w' = (w+paddings[1][0]+paddings[1][1])//block\_size`
  3361. Raises:
  3362. TypeError: If `block_size` is not an int.
  3363. ValueError: If `block_size` is less than 2.
  3364. Supported Platforms:
  3365. ``Ascend``
  3366. Examples:
  3367. >>> block_size = 2
  3368. >>> paddings = [[0, 0], [0, 0]]
  3369. >>> space_to_batch = ops.SpaceToBatch(block_size, paddings)
  3370. >>> input_x = Tensor(np.array([[[[1, 2], [3, 4]]]]), mindspore.float32)
  3371. >>> output = space_to_batch(input_x)
  3372. >>> print(output)
  3373. [[[[1.]]]
  3374. [[[2.]]]
  3375. [[[3.]]]
  3376. [[[4.]]]]
  3377. """
  3378. @prim_attr_register
  3379. def __init__(self, block_size, paddings):
  3380. """Initialize SpaceToBatch"""
  3381. logger.warning("WARN_DEPRECATED: The usage of SpaceToBatch is deprecated."
  3382. " Please use SpaceToBatchND.")
  3383. validator.check_value_type('block_size', block_size, [int], self.name)
  3384. validator.check('block_size', block_size, '', 2, Rel.GE, self.name)
  3385. self.block_size = block_size
  3386. validator.check('paddings shape', np.array(paddings).shape, '', (2, 2), Rel.EQ, self.name)
  3387. for elem in itertools.chain(*paddings):
  3388. validator.check_non_negative_int(elem, 'paddings element', self.name)
  3389. validator.check_value_type('paddings element', elem, [int], self.name)
  3390. self.paddings = paddings
  3391. def infer_dtype(self, x_dtype):
  3392. validator.check_tensor_dtype_valid('input_x', x_dtype, mstype.number_type, self.name)
  3393. return x_dtype
  3394. def infer_shape(self, x_shape):
  3395. validator.check_equal_int(len(x_shape), 4, 'rank of input_x', self.name)
  3396. out_shape = copy.deepcopy(x_shape)
  3397. for i in range(2):
  3398. padded = out_shape[i + 2] + self.paddings[i][0] + self.paddings[i][1]
  3399. if padded % self.block_size != 0:
  3400. raise ValueError(f'For \'{self.name}\' padded[{i}] {padded} should be divisible by '
  3401. f'block_size {self.block_size}')
  3402. out_shape[i + 2] = padded // self.block_size
  3403. out_shape[0] *= self.block_size * self.block_size
  3404. return out_shape
  3405. class BatchToSpace(PrimitiveWithInfer):
  3406. r"""
  3407. Divides batch dimension with blocks and interleaves these blocks back into spatial dimensions.
  3408. This operation will divide batch dimension N into blocks with block_size, the output tensor's N dimension
  3409. is the corresponding number of blocks after division. The output tensor's H, W dimension is product of original H, W
  3410. dimension and block_size with given amount to crop from dimension, respectively.
  3411. Args:
  3412. block_size (int): The block size of division, has the value not less than 2.
  3413. crops (Union[list(int), tuple(int)]): The crop value for H and W dimension, containing 2 subtraction lists.
  3414. Each list contains 2 integers.
  3415. All values must be not less than 0. crops[i] specifies the crop values for the spatial dimension i, which
  3416. corresponds to the input dimension i+2. It is required that
  3417. input_shape[i+2]*block_size >= crops[i][0]+crops[i][1].
  3418. Inputs:
  3419. - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor, dimension 0 must be divisible by
  3420. product of `block_shape`.
  3421. Outputs:
  3422. Tensor, the output tensor with the same type as input. Assume input shape is (n, c, h, w) with block_size
  3423. and crops. The output shape will be (n', c', h', w'), where
  3424. :math:`n' = n//(block\_size*block\_size)`
  3425. :math:`c' = c`
  3426. :math:`h' = h*block\_size-crops[0][0]-crops[0][1]`
  3427. :math:`w' = w*block\_size-crops[1][0]-crops[1][1]`
  3428. Raises:
  3429. TypeError: If `block_size` or element of `crops` is not an int.
  3430. TypeError: If `crops` is neither list nor tuple.
  3431. ValueError: If `block_size` is less than 2.
  3432. Supported Platforms:
  3433. ``Ascend``
  3434. Examples:
  3435. >>> block_size = 2
  3436. >>> crops = [[0, 0], [0, 0]]
  3437. >>> batch_to_space = ops.BatchToSpace(block_size, crops)
  3438. >>> input_x = Tensor(np.array([[[[1]]], [[[2]]], [[[3]]], [[[4]]]]), mindspore.float32)
  3439. >>> output = batch_to_space(input_x)
  3440. >>> print(output)
  3441. [[[[1. 2.]
  3442. [3. 4.]]]]
  3443. """
  3444. @prim_attr_register
  3445. def __init__(self, block_size, crops):
  3446. """Initialize BatchToSpace"""
  3447. logger.warning("WARN_DEPRECATED: The usage of BatchToSpace is deprecated."
  3448. " Please use BatchToSpaceND.")
  3449. validator.check_value_type('block_size', block_size, [int], self.name)
  3450. validator.check('block_size', block_size, '', 2, Rel.GE, self.name)
  3451. self.block_size = block_size
  3452. validator.check_value_type('crops type', crops, [list, tuple], self.name)
  3453. validator.check('crops shape', np.array(crops).shape, '', (2, 2))
  3454. for elem in itertools.chain(*crops):
  3455. validator.check_non_negative_int(elem, 'crops element', self.name)
  3456. validator.check_value_type('crops element', elem, [int], self.name)
  3457. self.crops = crops
  3458. def infer_dtype(self, x_dtype):
  3459. validator.check_tensor_dtype_valid('input_x', x_dtype, mstype.number_type, self.name)
  3460. return x_dtype
  3461. def infer_shape(self, x_shape):
  3462. validator.check('rank of input_x', len(x_shape), '', 4)
  3463. out_shape = copy.deepcopy(x_shape)
  3464. for i in range(2):
  3465. x_block_prod = out_shape[i + 2] * self.block_size
  3466. crops_sum = self.crops[i][0] + self.crops[i][1]
  3467. validator.check("x block shape prod", x_block_prod, 'crops sum', crops_sum, Rel.GT, self.name)
  3468. out_shape[i + 2] = x_block_prod - crops_sum
  3469. block_size_prod = self.block_size * self.block_size
  3470. if out_shape[0] % block_size_prod != 0:
  3471. raise ValueError(f'For \'{self.name}\' input_x dimension 0 {out_shape[0]} should be divisible by '
  3472. f'block_size_prod {block_size_prod}')
  3473. out_shape[0] = out_shape[0] // block_size_prod
  3474. return out_shape
  3475. class SpaceToBatchND(PrimitiveWithInfer):
  3476. r"""
  3477. Divides spatial dimensions into blocks and combines the block size with the original batch.
  3478. This operation will divide spatial dimensions (H, W) into blocks with block_shape, the output tensor's H and W
  3479. dimension is the corresponding number of blocks after division. The output tensor's batch dimension is the
  3480. product of the original batch and the product of `block_shape`. Before division,
  3481. the spatial dimensions of the input are zero padded according to paddings if necessary.
  3482. Args:
  3483. block_shape (Union[list(int), tuple(int), int]): The block shape of dividing block with all value greater
  3484. than 1. If `block_shape` is a tuple or list, the length of `block_shape` is M corresponding to the
  3485. number of spatial dimensions. If `block_shape` is a int, the block size of M dimendions are the same,
  3486. equal to `block_shape`. M must be 2.
  3487. paddings (Union[tuple, list]): The padding values for H and W dimension, containing 2 subtraction list.
  3488. Each contains 2 integer value. All values must be greater than 0.
  3489. `paddings[i]` specifies the paddings for the spatial dimension i,
  3490. which corresponds to the input dimension i+2.
  3491. It is required that input_shape[i+2]+paddings[i][0]+paddings[i][1] is divisible by block_shape[i].
  3492. Inputs:
  3493. - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor.
  3494. Outputs:
  3495. Tensor, the output tensor with the same data type as input. Assume input shape is :math:`(n, c, h, w)` with
  3496. :math:`block\_shape` and :math:`padddings`. The shape of the output tensor will be :math:`(n', c', h', w')`,
  3497. where
  3498. :math:`n' = n*(block\_shape[0]*block\_shape[1])`
  3499. :math:`c' = c`
  3500. :math:`h' = (h+paddings[0][0]+paddings[0][1])//block\_shape[0]`
  3501. :math:`w' = (w+paddings[1][0]+paddings[1][1])//block\_shape[1]`
  3502. Raises:
  3503. TypeError: If `block_shape` is not one of list, tuple, int.
  3504. TypeError: If `paddings` is neither list nor tuple.
  3505. ValueError: If length of shape of `block_shape` is not equal to 1.
  3506. ValueError: If length of `block_shape` or `paddings` is not equal to 2.
  3507. Supported Platforms:
  3508. ``Ascend``
  3509. Examples:
  3510. >>> block_shape = [2, 2]
  3511. >>> paddings = [[0, 0], [0, 0]]
  3512. >>> space_to_batch_nd = ops.SpaceToBatchND(block_shape, paddings)
  3513. >>> input_x = Tensor(np.array([[[[1, 2], [3, 4]]]]), mindspore.float32)
  3514. >>> output = space_to_batch_nd(input_x)
  3515. >>> print(output)
  3516. [[[[1.]]]
  3517. [[[2.]]]
  3518. [[[3.]]]
  3519. [[[4.]]]]
  3520. """
  3521. @prim_attr_register
  3522. def __init__(self, block_shape, paddings):
  3523. """Initialize SpaceToBatchND"""
  3524. if isinstance(block_shape, int):
  3525. block_shape = (block_shape,) * 2
  3526. self.add_prim_attr("block_shape", block_shape)
  3527. validator.check_value_type('block_shape type', block_shape, [list, tuple], self.name)
  3528. validator.check('block_shape shape', len(np.array(block_shape).shape), '', 1, Rel.EQ, self.name)
  3529. block_rank = len(block_shape)
  3530. validator.check('block_shape length', block_rank, '', 2, Rel.EQ, self.name)
  3531. for elem in block_shape:
  3532. validator.check('block_shape element', elem, '', 1, Rel.GE, self.name)
  3533. validator.check_value_type('block_shape element', elem, [int], self.name)
  3534. self.block_shape = block_shape
  3535. validator.check_value_type('paddings type', paddings, [list, tuple], self.name)
  3536. validator.check('paddings length', len(paddings), '', 2, Rel.EQ, self.name)
  3537. validator.check('paddings shape', np.array(paddings).shape, '', (block_rank, 2), Rel.EQ, self.name)
  3538. for elem in itertools.chain(*paddings):
  3539. validator.check_non_negative_int(elem, 'paddings element', self.name)
  3540. validator.check_value_type('paddings element', elem, [int], self.name)
  3541. self.paddings = paddings
  3542. def infer_dtype(self, x_dtype):
  3543. validator.check_tensor_dtype_valid('input_x', x_dtype, mstype.number_type, self.name)
  3544. return x_dtype
  3545. def infer_shape(self, x_shape):
  3546. x_rank = len(x_shape)
  3547. validator.check_equal_int(x_rank, 4, 'x_shape rank', self.name)
  3548. out_shape = copy.deepcopy(x_shape)
  3549. block_shape_prod = 1
  3550. offset = 2
  3551. for i in range(len(self.block_shape)):
  3552. padded = out_shape[i + offset] + self.paddings[i][0] + \
  3553. self.paddings[i][1]
  3554. if padded % self.block_shape[i] != 0:
  3555. raise ValueError(f'For \'{self.name}\' padded[{i}] {padded} should be divisible by '
  3556. f'block_shape[{i}] {self.block_shape[i]}')
  3557. out_shape[i + offset] = padded // self.block_shape[i]
  3558. block_shape_prod = block_shape_prod * self.block_shape[i]
  3559. out_shape[0] *= block_shape_prod
  3560. return out_shape
  3561. class BatchToSpaceND(PrimitiveWithInfer):
  3562. r"""
  3563. Divides batch dimension with blocks and interleaves these blocks back into spatial dimensions.
  3564. This operation will divide batch dimension N into blocks with block_shape, the output tensor's N dimension
  3565. is the corresponding number of blocks after division. The output tensor's H, W dimension is product of original H, W
  3566. dimension and block_shape with given amount to crop from dimension, respectively.
  3567. Args:
  3568. block_shape (Union[list(int), tuple(int), int]): The block shape of dividing block with all value greater
  3569. than 1. If `block_shape` is a tuple or list, the length of `block_shape` is M corresponding to the
  3570. number of spatial dimensions. If `block_shape` is a int, the block size of M dimendions are the same,
  3571. equal to `block_shape`. M must be 2.
  3572. crops (Union[list(int), tuple(int)]): The crop value for H and W dimension, containing 2 subtraction list,
  3573. each containing 2 int value.
  3574. All values must be >= 0. crops[i] specifies the crop values for spatial dimension i, which corresponds to
  3575. input dimension i+2. It is required that input_shape[i+2]*block_shape[i] > crops[i][0]+crops[i][1].
  3576. Inputs:
  3577. - **input_x** (Tensor) - The input tensor. It must be a 4-D tensor, dimension 0 must be divisible by
  3578. product of `block_shape`.
  3579. Outputs:
  3580. Tensor, the output tensor with the same type as input. Assume input shape is (n, c, h, w) with block_shape
  3581. and crops. The output shape will be (n', c', h', w'), where
  3582. :math:`n' = n//(block\_shape[0]*block\_shape[1])`
  3583. :math:`c' = c`
  3584. :math:`h' = h*block\_shape[0]-crops[0][0]-crops[0][1]`
  3585. :math:`w' = w*block\_shape[1]-crops[1][0]-crops[1][1]`
  3586. Raises:
  3587. TypeError: If `block_shape` is not one of list, tuple, int.
  3588. TypeError: If `crops` is neither list nor tuple.
  3589. ValueError: If length of `block_shape` or `crops` is not equal to 2.
  3590. Supported Platforms:
  3591. ``Ascend``
  3592. Examples:
  3593. >>> block_shape = [2, 2]
  3594. >>> crops = [[0, 0], [0, 0]]
  3595. >>> batch_to_space_nd = ops.BatchToSpaceND(block_shape, crops)
  3596. >>> input_x = Tensor(np.array([[[[1]]], [[[2]]], [[[3]]], [[[4]]]]), mindspore.float32)
  3597. >>> output = batch_to_space_nd(input_x)
  3598. >>> print(output)
  3599. [[[[1. 2.]
  3600. [3. 4.]]]]
  3601. """
  3602. @prim_attr_register
  3603. def __init__(self, block_shape, crops):
  3604. """Initialize BatchToSpaceND"""
  3605. if isinstance(block_shape, int):
  3606. block_shape = (block_shape,) * 2
  3607. self.add_prim_attr("block_shape", block_shape)
  3608. validator.check_value_type('block_shape type', block_shape, [list, tuple], self.name)
  3609. validator.check('block_shape shape', len(np.array(block_shape).shape), '', 1, Rel.EQ, self.name)
  3610. block_rank = len(block_shape)
  3611. validator.check('block_shape length', block_rank, '', 2, Rel.EQ, self.name)
  3612. for elem in block_shape:
  3613. validator.check('block_shape element', elem, '', 1, Rel.GE, self.name)
  3614. validator.check_value_type('block_shape element', elem, [int], self.name)
  3615. self.block_shape = block_shape
  3616. validator.check_value_type('crops type', crops, [list, tuple], self.name)
  3617. validator.check('crops length', len(crops), '', 2, Rel.EQ, self.name)
  3618. validator.check('crops shape', np.array(crops).shape, '', (block_rank, 2), Rel.EQ, self.name)
  3619. for elem in itertools.chain(*crops):
  3620. validator.check_non_negative_int(elem, 'crops element', self.name)
  3621. validator.check_value_type('crops element', elem, [int], self.name)
  3622. self.crops = crops
  3623. def infer_dtype(self, x_dtype):
  3624. validator.check_tensor_dtype_valid('input_x', x_dtype, mstype.number_type, self.name)
  3625. return x_dtype
  3626. def infer_shape(self, x_shape):
  3627. x_rank = len(x_shape)
  3628. validator.check_int(x_rank, 4, Rel.EQ, 'x_shape rank', self.name)
  3629. out_shape = copy.deepcopy(x_shape)
  3630. block_shape_prod = 1
  3631. offset = 2
  3632. for i in range(len(self.block_shape)):
  3633. block_shape_prod = block_shape_prod * self.block_shape[i]
  3634. x_block_prod = out_shape[i + offset] * self.block_shape[i]
  3635. crops_sum = self.crops[i][0] + self.crops[i][1]
  3636. validator.check("x block shape prod", x_block_prod, 'crops sum', crops_sum, Rel.GT, self.name)
  3637. out_shape[i + offset] = x_block_prod - crops_sum
  3638. if out_shape[0] % block_shape_prod != 0:
  3639. raise ValueError(f'For \'{self.name}\' input_x dimension 0 {out_shape[0]} should be divisible by '
  3640. f'block_shape_prod {block_shape_prod}')
  3641. out_shape[0] = out_shape[0] // block_shape_prod
  3642. return out_shape
  3643. class BroadcastTo(Primitive):
  3644. """
  3645. Broadcasts input tensor to a given shape.
  3646. Input shape can be broadcast to target shape if for each dimension pair they are either equal or input is one or
  3647. the target dimension is -1. In case of -1 in target shape, it will be replaced by the input shape's value
  3648. in that dimension.
  3649. When input shape is broadcast to target shape, it starts with the trailing
  3650. dimensions. If there is a -1 in the target shape, the -1 cannot be in a leading,
  3651. non-existing dimension.
  3652. Args:
  3653. shape (tuple): The target shape to broadcast. Can be fully specified, or have -1 in one position
  3654. where it will be substituted by the input tensor's shape in that position, see example.
  3655. Inputs:
  3656. - **input_x** (Tensor) - The input tensor. The data type should be one of the following types: float16, float32,
  3657. int32, int8, uint8.
  3658. Outputs:
  3659. Tensor, with the given `shape` and the same data type as `input_x`.
  3660. Raises:
  3661. TypeError: If `shape` is not a tuple.
  3662. ValueError: if the target and input shapes are incompatible, or if a - 1 in the target shape is in an invalid
  3663. location.
  3664. Supported Platforms:
  3665. ``Ascend`` ``GPU`` ``CPU``
  3666. Examples:
  3667. >>> shape = (2, 3)
  3668. >>> input_x = Tensor(np.array([1, 2, 3]).astype(np.float32))
  3669. >>> broadcast_to = ops.BroadcastTo(shape)
  3670. >>> output = broadcast_to(input_x)
  3671. >>> print(output)
  3672. [[1. 2. 3.]
  3673. [1. 2. 3.]]
  3674. >>> shape = (-1, 2)
  3675. >>> input_x = Tensor(np.array([[1], [2]]).astype(np.float32))
  3676. >>> broadcast_to = ops.BroadcastTo(shape)
  3677. >>> output = broadcast_to(input_x)
  3678. >>> print(output)
  3679. [[1. 1.]
  3680. [2. 2.]]
  3681. """
  3682. @prim_attr_register
  3683. def __init__(self, shape):
  3684. """Initialize BroadcastTo"""
  3685. validator.check_value_type("shape", shape, (tuple), self.name)
  3686. validator.check("shape length", len(shape), "", 0, Rel.GT, self.name)
  3687. for ix, i in enumerate(shape):
  3688. validator.check_value_type('target shape index -> ' + str(ix), i, [int], self.name)
  3689. validator.check("shape element", i, "shape element min limit", -1, Rel.GE, self.name)
  3690. self.shape = shape
  3691. class Meshgrid(PrimitiveWithInfer):
  3692. """
  3693. Generates coordinate matrices from given coordinate tensors.
  3694. Given N one-dimensional coordinate tensors, returns a tuple outputs of N N-D
  3695. coordinate tensors for evaluating expressions on an N-D grid.
  3696. Args:
  3697. indexing (str): Either 'xy' or 'ij'. Default: 'xy'.
  3698. When the indexing argument is set to 'xy' (the default), the broadcasting
  3699. instructions for the first two dimensions are swapped.
  3700. Inputs:
  3701. - **input** (Union[tuple]) - A Tuple of N 1-D Tensor objects.
  3702. The length of input should be greater than 1
  3703. Outputs:
  3704. Tensors, A Tuple of N N-D Tensor objects.
  3705. Raises:
  3706. TypeError: If `indexing` is not a str or `input` is not a tuple.
  3707. ValueError: If `indexing` is neither 'xy' nor 'ij'.
  3708. Supported Platforms:
  3709. ``Ascend``
  3710. Examples:
  3711. >>> x = Tensor(np.array([1, 2, 3, 4]).astype(np.int32))
  3712. >>> y = Tensor(np.array([5, 6, 7]).astype(np.int32))
  3713. >>> z = Tensor(np.array([8, 9, 0, 1, 2]).astype(np.int32))
  3714. >>> inputs = (x, y, z)
  3715. >>> meshgrid = ops.Meshgrid(indexing="xy")
  3716. >>> output = meshgrid(inputs)
  3717. >>> print(output)
  3718. (Tensor(shape=[3, 4, 5], dtype=Int32, value=
  3719. [[[1, 1, 1, 1, 1],
  3720. [2, 2, 2, 2, 2],
  3721. [3, 3, 3, 3, 3],
  3722. [4, 4, 4, 4, 4]],
  3723. [[1, 1, 1, 1, 1],
  3724. [2, 2, 2, 2, 2],
  3725. [3, 3, 3, 3, 3],
  3726. [4, 4, 4, 4, 4]],
  3727. [[1, 1, 1, 1, 1],
  3728. [2, 2, 2, 2, 2],
  3729. [3, 3, 3, 3, 3],
  3730. [4, 4, 4, 4, 4]]]),
  3731. Tensor(shape=[3, 4, 5], dtype=Int32, value=
  3732. [[[5, 5, 5, 5, 5],
  3733. [5, 5, 5, 5, 5],
  3734. [5, 5, 5, 5, 5],
  3735. [5, 5, 5, 5, 5]],
  3736. [[6, 6, 6, 6, 6],
  3737. [6, 6, 6, 6, 6],
  3738. [6, 6, 6, 6, 6],
  3739. [6, 6, 6, 6, 6]],
  3740. [[7, 7, 7, 7, 7],
  3741. [7, 7, 7, 7, 7],
  3742. [7, 7, 7, 7, 7],
  3743. [7, 7, 7, 7, 7]]]),
  3744. Tensor(shape=[3, 4, 5], dtype=Int32, value=
  3745. [[[8, 9, 0, 1, 2],
  3746. [8, 9, 0, 1, 2],
  3747. [8, 9, 0, 1, 2],
  3748. [8, 9, 0, 1, 2]],
  3749. [[8, 9, 0, 1, 2],
  3750. [8, 9, 0, 1, 2],
  3751. [8, 9, 0, 1, 2],
  3752. [8, 9, 0, 1, 2]],
  3753. [[8, 9, 0, 1, 2],
  3754. [8, 9, 0, 1, 2],
  3755. [8, 9, 0, 1, 2],
  3756. [8, 9, 0, 1, 2]]]))
  3757. """
  3758. @prim_attr_register
  3759. def __init__(self, indexing="xy"):
  3760. """Init Meshgrid"""
  3761. validator.check_value_type("indexing", indexing, (str), self.name)
  3762. if indexing not in ("xy", "ij"):
  3763. raise ValueError("indexing parameter must be either 'xy' or 'ij'")
  3764. self.indexing = indexing
  3765. def infer_shape(self, x_shape):
  3766. validator.check_value_type("shape", x_shape, [tuple], self.name)
  3767. validator.check_int(len(x_shape), 2, Rel.GE, "len of input", self.name)
  3768. n = len(x_shape)
  3769. shape_0 = []
  3770. for s in x_shape:
  3771. validator.check_int(len(s), 1, Rel.EQ, 'each input rank', self.name)
  3772. shape_0.append(s[0])
  3773. if self.indexing == "xy":
  3774. shape_0[0], shape_0[1] = shape_0[1], shape_0[0]
  3775. out_shape = tuple(tuple(shape_0) for _ in range(n))
  3776. return out_shape
  3777. def infer_dtype(self, x_type):
  3778. validator.check_subclass("input[0]", x_type[0], mstype.tensor, self.name)
  3779. n = len(x_type)
  3780. for i in range(1, n):
  3781. validator.check('x_type[%d]' % i, x_type[i], 'base', x_type[0], Rel.EQ, self.name, TypeError)
  3782. return x_type
  3783. class InplaceUpdate(PrimitiveWithInfer):
  3784. r"""
  3785. Updates specified rows with values in `v`.
  3786. Args:
  3787. indices (Union[int, tuple]): Indices into the left-most dimension of `x`, and determines which rows of x
  3788. to update with v. It is a int or tuple, whose value is in [0, the first dimension size of x).
  3789. Inputs:
  3790. - **x** (Tensor) - A tensor which to be inplace updated. It can be one of the following data types:
  3791. float32, float16 and int32.
  3792. - **v** (Tensor) - A tensor with the same type as `x` and the same dimension size as `x` except
  3793. the first dimension, which must be the same as the size of `indices`.
  3794. Outputs:
  3795. Tensor, with the same type and shape as the input `x`.
  3796. Raises:
  3797. TypeError: If `indices` is neither int nor tuple.
  3798. TypeError: If `indices` is a tuple and its element is not an int.
  3799. Supported Platforms:
  3800. ``Ascend``
  3801. Examples:
  3802. >>> indices = (0, 1)
  3803. >>> x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32)
  3804. >>> v = Tensor(np.array([[0.5, 1.0], [1.0, 1.5]]), mindspore.float32)
  3805. >>> inplace_update = ops.InplaceUpdate(indices)
  3806. >>> output = inplace_update(x, v)
  3807. >>> print(output)
  3808. [[0.5 1. ]
  3809. [1. 1.5]
  3810. [5. 6. ]]
  3811. """
  3812. @prim_attr_register
  3813. def __init__(self, indices):
  3814. """Initialize InplaceUpdate"""
  3815. self.init_prim_io_names(inputs=['x', 'v'], outputs=['y'])
  3816. self.indices = indices
  3817. validator.check_value_type("indices", indices, [int, tuple], self.name)
  3818. if isinstance(indices, int):
  3819. self.indices = (indices,)
  3820. for item in self.indices:
  3821. validator.check_value_type("item of indices", item, [int], self.name)
  3822. def infer_dtype(self, x_dtype, v_dtype):
  3823. args = {'x': x_dtype, 'v': v_dtype}
  3824. valid_type = [mstype.int32, mstype.float16, mstype.float32]
  3825. validator.check_tensors_dtypes_same_and_valid(args, valid_type, self.name)
  3826. return x_dtype
  3827. def infer_shape(self, x_shape, v_shape):
  3828. validator.check("x", len(x_shape), "v", len(v_shape), Rel.EQ, self.name)
  3829. validator.check("size of indices", len(self.indices), "v's first dimension", v_shape[0],
  3830. Rel.EQ, self.name)
  3831. for i in self.indices:
  3832. if i < 0 or i >= x_shape[0]:
  3833. raise ValueError(f'The value of indices must be in [0, {x_shape[0]}), but got {i}.')
  3834. x_rank = len(x_shape)
  3835. for idx in range(x_rank)[1:]:
  3836. validator.check('v dim %d' % idx, v_shape[idx], "x dim %d" % idx, x_shape[idx], Rel.EQ, self.name)
  3837. return x_shape
  3838. class ReverseSequence(PrimitiveWithInfer):
  3839. """
  3840. Reverses variable length slices.
  3841. Args:
  3842. seq_dim (int): The dimension where reversal is performed. Required.
  3843. batch_dim (int): The input is sliced in this dimension. Default: 0.
  3844. Inputs:
  3845. - **x** (Tensor) - The input to reverse, supporting all number types including bool.
  3846. - **seq_lengths** (Tensor) - Must be a 1-D vector with int32 or int64 types.
  3847. Outputs:
  3848. Reversed tensor with the same shape and data type as input.
  3849. Raises:
  3850. TypeError: If `seq_dim` or `batch_dim` is not an int.
  3851. Supported Platforms:
  3852. ``Ascend``
  3853. Examples:
  3854. >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32)
  3855. >>> seq_lengths = Tensor(np.array([1, 2, 3]))
  3856. >>> reverse_sequence = ops.ReverseSequence(seq_dim=1)
  3857. >>> output = reverse_sequence(x, seq_lengths)
  3858. >>> print(output)
  3859. [[1. 2. 3.]
  3860. [5. 4. 6.]
  3861. [9. 8. 7.]]
  3862. """
  3863. @prim_attr_register
  3864. def __init__(self, seq_dim, batch_dim=0):
  3865. """Initialize ReverseSequence"""
  3866. self.init_prim_io_names(inputs=['x', 'seq_lengths'], outputs=['y'])
  3867. validator.check_value_type("seq_dim", seq_dim, [int], self.name)
  3868. self.seq_dim_ = seq_dim
  3869. validator.check_value_type("batch_dim", batch_dim, [int], self.name)
  3870. self.batch_dim_ = batch_dim
  3871. def infer_shape(self, x, seq_lengths):
  3872. validator.check("seq_dim", self.seq_dim_, "x rank", len(x), Rel.LE, self.name)
  3873. validator.check("batch_dim", self.batch_dim_, "x rank", len(x), Rel.LE, self.name)
  3874. validator.check("batch_dim", self.batch_dim_, "seq_dim", self.seq_dim_, Rel.NE, self.name)
  3875. validator.check("seq_lengths rank", len(seq_lengths), "expected", 1, Rel.EQ, self.name)
  3876. validator.check("seq_lengths vector size", seq_lengths[0],
  3877. "input size along batch_dim", x[self.batch_dim_], Rel.EQ, self.name)
  3878. return x
  3879. def infer_dtype(self, x, seq_lengths):
  3880. validator.check_tensor_dtype_valid("x_dtype", x, mstype.number_type + (mstype.bool_,), self.name)
  3881. validator.check_tensor_dtype_valid("seq_lengths_dtype", seq_lengths, [mstype.int32, mstype.int64], self.name)
  3882. return x
  3883. class EditDistance(PrimitiveWithInfer):
  3884. """
  3885. Computes the Levenshtein Edit Distance. It is used to measure the similarity of two sequences. The inputs are
  3886. variable-length sequences provided by SparseTensors (hypothesis_indices, hypothesis_values, hypothesis_shape)
  3887. and (truth_indices, truth_values, truth_shape).
  3888. Args:
  3889. normalize (bool): If true, edit distances are normalized by length of truth. Default: True.
  3890. Inputs:
  3891. - **hypothesis_indices** (Tensor) - The indices of the hypothesis list SparseTensor. With int64 data type.
  3892. The shape of tensor is :math:`(N, R)`.
  3893. - **hypothesis_values** (Tensor) - The values of the hypothesis list SparseTensor.
  3894. Must be 1-D vector with length of N.
  3895. - **hypothesis_shape** (Tensor) - The shape of the hypothesis list SparseTensor.
  3896. Must be R-length vector with int64 data type. Only constant value is allowed.
  3897. - **truth_indices** (Tensor) - The indices of the truth list SparseTensor. With int64 data type.
  3898. The shape of tensor is :math:`(M, R)`.
  3899. - **truth_values** (Tensor) - The values of the truth list SparseTensor. Must be 1-D vector with length of M.
  3900. - **truth_shape** (Tensor) - The shape of the truth list SparseTensor.
  3901. Must be R-length vector with int64 data type. Only constant value is allowed.
  3902. Outputs:
  3903. Tensor, a dense tensor with rank `R-1` and float32 data type.
  3904. Raises:
  3905. TypeError: If `normalize` is not a bool.
  3906. Supported Platforms:
  3907. ``Ascend``
  3908. Examples:
  3909. >>> import numpy as np
  3910. >>> from mindspore import context
  3911. >>> from mindspore import Tensor
  3912. >>> import mindspore.nn as nn
  3913. >>> import mindspore.ops.operations as ops
  3914. >>> class EditDistance(nn.Cell):
  3915. ... def __init__(self, hypothesis_shape, truth_shape, normalize=True):
  3916. ... super(EditDistance, self).__init__()
  3917. ... self.edit_distance = ops.EditDistance(normalize)
  3918. ... self.hypothesis_shape = hypothesis_shape
  3919. ... self.truth_shape = truth_shape
  3920. ...
  3921. ... def construct(self, hypothesis_indices, hypothesis_values, truth_indices, truth_values):
  3922. ... return self.edit_distance(hypothesis_indices, hypothesis_values, self.hypothesis_shape,
  3923. ... truth_indices, truth_values, self.truth_shape)
  3924. ...
  3925. >>> hypothesis_indices = Tensor(np.array([[0, 0, 0], [1, 0, 1], [1, 1, 1]]).astype(np.int64))
  3926. >>> hypothesis_values = Tensor(np.array([1, 2, 3]).astype(np.float32))
  3927. >>> hypothesis_shape = Tensor(np.array([1, 1, 2]).astype(np.int64))
  3928. >>> truth_indices = Tensor(np.array([[0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1]]).astype(np.int64))
  3929. >>> truth_values = Tensor(np.array([1, 3, 2, 1]).astype(np.float32))
  3930. >>> truth_shape = Tensor(np.array([2, 2, 2]).astype(np.int64))
  3931. >>> edit_distance = EditDistance(hypothesis_shape, truth_shape)
  3932. >>> output = edit_distance(hypothesis_indices, hypothesis_values, truth_indices, truth_values)
  3933. >>> print(output)
  3934. [[1. 1.]
  3935. [1. 1.]]
  3936. """
  3937. @prim_attr_register
  3938. def __init__(self, normalize=True):
  3939. """Initialize EditDistance"""
  3940. self.normalize = validator.check_value_type("normalize", normalize, [bool], self.name)
  3941. self.set_const_input_indexes([2, 5])
  3942. def __infer__(self, h_indices, h_values, h_shape, truth_indices, truth_values, truth_shape):
  3943. validator.check_const_input('hypothesis_shape', h_shape['value'], self.name)
  3944. validator.check_const_input('truth_shape', truth_shape['value'], self.name)
  3945. args_int = {"hypothesis_indices": h_indices['dtype'], "hypothesis_shape": h_shape['dtype'],
  3946. "truth_indices": truth_indices['dtype'], "truth_shape": truth_shape['dtype']}
  3947. validator.check_tensors_dtypes_same_and_valid(args_int, [mstype.int64], self.name)
  3948. args = {"hypothesis_values": h_values['dtype'], "truth_values": truth_values['dtype']}
  3949. validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type, self.name)
  3950. hypothesis_indices_shp, truth_indices_shp = h_indices['shape'], truth_indices['shape']
  3951. validator.check("hypothesis_indices rank", len(hypothesis_indices_shp), "expected", 2, Rel.EQ, self.name)
  3952. validator.check("truth_indices rank", len(truth_indices_shp), "expected", 2, Rel.EQ, self.name)
  3953. validator.check("hypothesis_values rank", len(h_values['shape']), "expected", 1, Rel.EQ, self.name)
  3954. validator.check("hypothesis_shape rank", len(h_shape['shape']), "expected", 1, Rel.EQ, self.name)
  3955. validator.check("truth_values rank", len(truth_values['shape']), "expected", 1, Rel.EQ, self.name)
  3956. validator.check("truth_shape rank", len(truth_shape['shape']), "expected", 1, Rel.EQ, self.name)
  3957. validator.check("hypothesis_values shape", h_values['shape'][0],
  3958. "hypothesis_indices shape[0]", hypothesis_indices_shp[0], Rel.EQ, self.name)
  3959. validator.check("hypothesis_shape", h_shape['shape'][0],
  3960. "hypothesis_indices shape[1]", hypothesis_indices_shp[1], Rel.EQ, self.name)
  3961. validator.check("truth_values shape", truth_values['shape'][0],
  3962. "truth_indices shape[0]", truth_indices_shp[0], Rel.EQ, self.name)
  3963. validator.check("hypothesis_shape", h_shape['shape'][0],
  3964. "truth_shape", truth_shape['shape'][0], Rel.EQ, self.name)
  3965. hypothesis_shape_v = h_shape['value'].asnumpy()
  3966. truth_shape_v = truth_shape['value'].asnumpy()
  3967. out_shape_rank = len(hypothesis_shape_v) - 1
  3968. out_shape = []
  3969. for i in range(out_shape_rank):
  3970. out_shape.append(max(hypothesis_shape_v[i], truth_shape_v[i]))
  3971. return {'shape': tuple(out_shape),
  3972. 'dtype': mstype.tensor_type(mstype.float32),
  3973. 'value': None}
  3974. class TransShape(PrimitiveWithInfer):
  3975. """
  3976. Transforms the shape of input tensor to target shape.
  3977. Inputs:
  3978. - **input_x** (Tensor) - A input tensor.
  3979. - **out_shape** (tuple[int]) - The shape of output data.
  3980. Outputs:
  3981. Tensor, a tensor whose data type is same as 'input_x', and the shape is the same as the `out_shape`.
  3982. """
  3983. @prim_attr_register
  3984. def __init__(self):
  3985. self.__setattr_flag__ = True
  3986. def __infer__(self, x, shape):
  3987. shp = shape['value']
  3988. dtype = x['dtype']
  3989. validator.check_tensor_dtype_valid('x', dtype, mstype.number_type + (mstype.bool_,), self.name)
  3990. self.add_prim_attr('out_shape', tuple(shp))
  3991. return {'shape': shp,
  3992. 'dtype': dtype,
  3993. 'value': None}
  3994. class Sort(PrimitiveWithInfer):
  3995. """
  3996. Sorts the elements of the input tensor along a given dimension in ascending order by value.
  3997. Args:
  3998. axis (int): The dimension to sort along. Default: -1.
  3999. descending (bool): Controls the sorting order. If descending is True then the elements
  4000. are sorted in descending order by value. Default: False.
  4001. Inputs:
  4002. - **x** (Tensor) - The input to sort, with float16 or float32 data type.
  4003. Outputs:
  4004. - **y1** (Tensor) - A tensor whose values are the sorted values, with the same shape and data type as input.
  4005. - **y2** (Tensor) - The indices of the elements in the original input tensor. Data type is int32.
  4006. Raises:
  4007. TypeError: If `axis` is not an int.
  4008. TypeError: If `descending` is not a bool.
  4009. TypeError: If dtype of `x` is neither float16 nor float32.
  4010. Supported Platforms:
  4011. ``Ascend``
  4012. Examples:
  4013. >>> x = Tensor(np.array([[8, 2, 1], [5, 9, 3], [4, 6, 7]]), mindspore.float16)
  4014. >>> sort = ops.Sort()
  4015. >>> output = sort(x)
  4016. >>> print(output)
  4017. (Tensor(shape=[3, 3], dtype=Float16, value=
  4018. [[ 1.0000e+00, 2.0000e+00, 8.0000e+00],
  4019. [ 3.0000e+00, 5.0000e+00, 9.0000e+00],
  4020. [ 4.0000e+00, 6.0000e+00, 7.0000e+00]]), Tensor(shape=[3, 3], dtype=Int32, value=
  4021. [[2, 1, 0],
  4022. [2, 0, 1],
  4023. [0, 1, 2]]))
  4024. """
  4025. @prim_attr_register
  4026. def __init__(self, axis=-1, descending=False):
  4027. """Initialize Sort"""
  4028. self.axis = validator.check_value_type("axis", axis, [int], self.name)
  4029. self.descending = validator.check_value_type("descending", descending, [bool], self.name)
  4030. def infer_shape(self, x_shape):
  4031. return x_shape, x_shape
  4032. def infer_dtype(self, x_dtype):
  4033. validator.check_tensor_dtype_valid("x_dtype", x_dtype, [mstype.float32, mstype.float16], self.name)
  4034. return x_dtype, mstype.tensor_type(mstype.int32)
  4035. class EmbeddingLookup(PrimitiveWithCheck):
  4036. """
  4037. Returns a slice of input tensor based on the specified indices.
  4038. This Primitive has the similar functionality as GatherV2 operating on `axis = 0`, but has one more inputs:
  4039. `offset`.
  4040. Inputs:
  4041. - **input_params** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  4042. This represents a Tensor slice, instead of the entire Tensor. Currently, the dimension is restricted to be 2.
  4043. - **input_indices** (Tensor) - The shape of tensor is :math:`(y_1, y_2, ..., y_S)`.
  4044. Specifies the indices of elements of the original Tensor. Values can be out of range of `input_params`,
  4045. and the exceeding part will be filled with 0 in the output. Values does not support negative and the result
  4046. is undefined if values are negative.
  4047. - **offset** (int) - Specifies the offset value of this `input_params` slice. Thus the real indices
  4048. are equal to `input_indices` minus `offset`.
  4049. Outputs:
  4050. Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`.
  4051. Raises:
  4052. TypeError: If dtype of `input_indices` is not int.
  4053. ValueError: If length of shape of `input_params` is greater than 2.
  4054. Supported Platforms:
  4055. ``Ascend`` ``CPU``
  4056. Examples:
  4057. >>> input_params = Tensor(np.array([[8, 9], [10, 11], [12, 13], [14, 15]]), mindspore.float32)
  4058. >>> input_indices = Tensor(np.array([[5, 2], [8, 5]]), mindspore.int32)
  4059. >>> offset = 4
  4060. >>> output = ops.EmbeddingLookup()(input_params, input_indices, offset)
  4061. >>> print(output)
  4062. [[[10. 11.]
  4063. [ 0. 0.]]
  4064. [[ 0. 0.]
  4065. [10. 11.]]]
  4066. """
  4067. @prim_attr_register
  4068. def __init__(self):
  4069. """Initialize index_select"""
  4070. self.__setattr_flag__ = True
  4071. self.init_prim_io_names(inputs=['params', 'indices', 'offset'],
  4072. outputs=['output'])
  4073. def __check__(self, params, indices, offset):
  4074. validator.check_subclass("params", params['dtype'], mstype.tensor, self.name)
  4075. validator.check_tensor_dtype_valid("indices", indices['dtype'], mstype.int_type, self.name)
  4076. validator.check_subclass("offset", offset['dtype'], mstype.int_, self.name)
  4077. params_shp = params['shape']
  4078. if len(params_shp) > 2:
  4079. raise ValueError("The dimension of 'params' in EmbeddingLookup must <= 2, but got %d." % len(params_shp))
  4080. class GatherD(Primitive):
  4081. """
  4082. Gathers values along an axis specified by dim.
  4083. For a 3-D tensor, the output is:
  4084. .. code-block::
  4085. output[i][j][k] = x[index[i][j][k]][j][k] # if dim == 0
  4086. output[i][j][k] = x[i][index[i][j][k]][k] # if dim == 1
  4087. output[i][j][k] = x[i][j][index[i][j][k]] # if dim == 2
  4088. If `x` is an n-D tensor with shape :math:`(z_0, z_1, ..., z_i, ..., z_{n-1})` and `dim` = i,
  4089. the `index` must be an n-D tensor with shape :math:`(z_0, z_1, ..., y, ..., z_{n-1})`
  4090. where `y`>=1 and the output will have the same shape as `index`.
  4091. Inputs:
  4092. - **x** (Tensor) - The source tensor.
  4093. - **dim** (int) - The axis along which to index. It must be int32 or int64. Only constant value is allowed.
  4094. - **index** (Tensor) - The indices of elements to gather. It can be one of the following data types:
  4095. int32, int64. The value range of each index element is [-x_rank[dim], x_rank[dim]).
  4096. Outputs:
  4097. Tensor, the shape of tensor is :math:`(z_1, z_2, ..., z_N)`.
  4098. Raises:
  4099. TypeError: If dtype of `dim` or `index` is neither int32 nor int64.
  4100. ValueError: If length of shape of `x` is not equal to length of shape of `index`.
  4101. Supported Platforms:
  4102. ``Ascend`` ``GPU`` ``CPU``
  4103. Examples:
  4104. >>> x = Tensor(np.array([[1, 2], [3, 4]]), mindspore.int32)
  4105. >>> index = Tensor(np.array([[0, 0], [1, 0]]), mindspore.int32)
  4106. >>> dim = 1
  4107. >>> output = ops.GatherD()(x, dim, index)
  4108. >>> print(output)
  4109. [[1 1]
  4110. [4 3]]
  4111. """
  4112. @prim_attr_register
  4113. def __init__(self):
  4114. """Initialize GatherD"""
  4115. self.init_prim_io_names(inputs=['x', 'dim', 'index'], outputs=['output'])
  4116. class Identity(PrimitiveWithInfer):
  4117. """
  4118. Returns a Tensor with the same shape and contents as input.
  4119. Inputs:
  4120. - **x** (Tensor) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  4121. Outputs:
  4122. Tensor, the shape of tensor is the same as `input_x`, :math:`(x_1, x_2, ..., x_R)`.
  4123. Raises:
  4124. TypeError: If `x` is not a Tensor.
  4125. Supported Platforms:
  4126. ``Ascend``
  4127. Examples:
  4128. >>> x = Tensor(np.array([1, 2, 3, 4]), mindspore.int64)
  4129. >>> output = ops.Identity()(x)
  4130. >>> print(output)
  4131. [1 2 3 4]
  4132. """
  4133. # Side effect is identity with input.
  4134. side_effect_propagate = 1
  4135. @prim_attr_register
  4136. def __init__(self):
  4137. """Initialize identity"""
  4138. self.add_prim_attr('side_effect_propagate', 1)
  4139. def __infer__(self, x):
  4140. validator.check_subclass("x", x['dtype'], mstype.tensor, self.name)
  4141. validator.check_tensor_dtype_valid('x', x['dtype'], mstype.number_type + (mstype.bool_,), self.name)
  4142. out = {'shape': x['shape'],
  4143. 'dtype': x['dtype'],
  4144. 'value': None}
  4145. return out
  4146. class Range(PrimitiveWithCheck):
  4147. r"""
  4148. Creates a sequence of numbers that begins at `start` and extends by increments of
  4149. `delta` up to but not including `limit`.
  4150. The types of all 3 inputs must be the same. The type of the resulting tensor is
  4151. the same as the type of the inputs.
  4152. Args:
  4153. maxlen (int): Memory that can fit `maxlen` many elements
  4154. will be allocated for the output. Optional, must be positive, defaults to 1000000.
  4155. If the output has more than `maxlen` elements, a runtime error
  4156. will occur.
  4157. Inputs:
  4158. - **start** (Tensor) - A scalar Tensor. The first number in the sequence. Must have
  4159. type: int32 or float32
  4160. - **limit** (Tensor) - A scalar Tensor. Upper limit of the sequence, exclusive. Must
  4161. have type: int32 or float32
  4162. - **delta** (Tensor) - A scalar Tensor. Number that increments `start`. Must have
  4163. type: int32 or float32
  4164. Outputs:
  4165. A 1-D Tensor, with the same type as the inputs.
  4166. Supported Platforms:
  4167. ``GPU``
  4168. Examples:
  4169. >>> start = Tensor(0, mstype.int32)
  4170. >>> limit = Tensor(10, mstype.int32)
  4171. >>> delta = Tensor(4, mstype.int32)
  4172. >>> output = ops.Range()(start, limit, delta)
  4173. >>> print(output)
  4174. [0, 4, 8]
  4175. """
  4176. @prim_attr_register
  4177. def __init__(self, maxlen=1000000):
  4178. self.init_prim_io_names(inputs=['start', 'limit', 'delta'], outputs=['output'])
  4179. validator.check_value_type("maxlen", maxlen, [int], self.name)
  4180. validator.check_positive_int(maxlen, "maxlen", self.name)
  4181. self.maxlen = maxlen
  4182. self.add_prim_attr('maxlen', maxlen)
  4183. def check_shape(self, start_shape, limit_shape, delta_shape):
  4184. validator.check("start_shape", len(start_shape), "", 0, Rel.EQ, self.name)
  4185. validator.check("limit_shape", len(limit_shape), "", 0, Rel.EQ, self.name)
  4186. validator.check("delta_shape", len(delta_shape), "", 0, Rel.EQ, self.name)
  4187. def check_dtype(self, start_dtype, limit_dtype, delta_dtype):
  4188. valid_dtypes = [mstype.int32, mstype.float32]
  4189. inputs = {"start": start_dtype, "limit": limit_dtype, "delta": delta_dtype}
  4190. validator.check_tensors_dtypes_same_and_valid(inputs, valid_dtypes, self.name)
  4191. def infer_value(self, start_value, limit_value, delat_value):
  4192. if start_value is not None and limit_value is not None and delat_value is not None:
  4193. start = np.asscalar(start_value.asnumpy())
  4194. limit = np.asscalar(limit_value.asnumpy())
  4195. delat = np.asscalar(delat_value.asnumpy())
  4196. return Tensor(np.arange(start, limit, delat), dtype=start_value.dtype)
  4197. return None