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