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

math_ops.py 180 kB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
6 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
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
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273
  1. # Copyright 2020-2021 Huawei Technologies Co., Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ============================================================================
  15. """Operators for math."""
  16. import numpy as np
  17. from ... import context
  18. from .. import signature as sig
  19. from ..._checkparam import Validator as validator
  20. from ..._checkparam import Rel
  21. from ...common import dtype as mstype
  22. from ...common.tensor import Tensor
  23. from ...common._decorator import deprecated
  24. from .._utils import get_broadcast_shape
  25. from ..primitive import Primitive, PrimitiveWithInfer, PrimitiveWithCheck, prim_attr_register, _run_op
  26. def _infer_shape_reduce(x, axis, keep_dims, prim_name):
  27. """Common infer for reduce operator"""
  28. def reduce_one_axis(one_axis):
  29. validator.check_int_range(one_axis, -dim, dim, Rel.INC_LEFT, 'axis', prim_name)
  30. if one_axis < 0:
  31. one_axis += dim
  32. axis_reduce.add(one_axis)
  33. validator.check_value_type('axis', axis, [int, tuple, list], prim_name)
  34. dim = len(x)
  35. axis_reduce = set()
  36. if isinstance(axis, int):
  37. reduce_one_axis(axis)
  38. else:
  39. if not axis:
  40. if keep_dims:
  41. return [1] * dim
  42. return []
  43. for index, one_axis in enumerate(axis):
  44. validator.check_value_type('axis[%d]' % index, one_axis, [int], prim_name)
  45. reduce_one_axis(one_axis)
  46. out_shape = []
  47. for i in range(dim):
  48. if i in axis_reduce:
  49. if keep_dims:
  50. out_shape.append(1)
  51. else:
  52. out_shape.append(x[i])
  53. return out_shape
  54. class _BinaryOp(PrimitiveWithInfer):
  55. """
  56. Define binary operators.
  57. """
  58. __mindspore_signature__ = (sig.sig_dtype.T, sig.sig_dtype.T)
  59. @prim_attr_register
  60. def __init__(self):
  61. """Initialize _BinaryOp"""
  62. self.init_prim_io_names(inputs=['x', 'y'], outputs=['output'])
  63. def infer_shape(self, x_shape, y_shape):
  64. return get_broadcast_shape(x_shape, y_shape, self.name)
  65. class _MathBinaryOp(_BinaryOp):
  66. """
  67. Define math binary operators.
  68. """
  69. @staticmethod
  70. def do_infer_dtype(x_dtype, y_dtype, valid_dtype=mstype.number_type, prim_name=None):
  71. """Staticmethod of infer dtype for _MathBinaryOp."""
  72. args_type = {"x": x_dtype, "y": y_dtype}
  73. validator.check_tensors_dtypes_same_and_valid(args_type, valid_dtype, prim_name)
  74. return x_dtype
  75. def infer_dtype(self, x_dtype, y_dtype):
  76. return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, mstype.number_type, self.name)
  77. class _BitwiseBinaryOp(_MathBinaryOp):
  78. """
  79. Define bitwise binary operators.
  80. """
  81. @prim_attr_register
  82. def __init__(self):
  83. """Initialize _BitwiseBinaryOp"""
  84. self.init_prim_io_names(inputs=['x1', 'x2'], outputs=['y'])
  85. @staticmethod
  86. def _check_bitwise_op_input_type(x1_type, x2_type, prim):
  87. args = {'x1': x1_type, 'x2': x2_type}
  88. valid_dtypes = mstype.int_type + mstype.uint_type
  89. validator.check_tensors_dtypes_same_and_valid(args, valid_dtypes, prim)
  90. return x1_type
  91. def infer_dtype(self, x1_type, x2_type):
  92. return _BitwiseBinaryOp._check_bitwise_op_input_type(x1_type, x2_type, self.name)
  93. class Add(_MathBinaryOp):
  94. r"""
  95. Adds two input tensors element-wise.
  96. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  97. The inputs must be two tensors or one tensor and one scalar.
  98. When the inputs are two tensors,
  99. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  100. When the inputs are one tensor and one scalar,
  101. the scalar could only be a constant.
  102. .. math::
  103. out_{i} = x_{i} + y_{i}
  104. Inputs:
  105. - **x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  106. or a tensor whose data type is number or bool.
  107. - **y** (Union[Tensor, Number, bool]) - The second input is a number, or a bool when the first input
  108. is a tensor, or a tensor whose data type is number or bool.
  109. Outputs:
  110. Tensor, the shape is the same as the one after broadcasting,
  111. and the data type is the one with higher precision or higher digits among the two inputs.
  112. Raises:
  113. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  114. Supported Platforms:
  115. ``Ascend`` ``GPU`` ``CPU``
  116. Examples:
  117. >>> # case 1: x and y are both Tensor.
  118. >>> add = ops.Add()
  119. >>> x = Tensor(np.array([1, 2, 3]).astype(np.float32))
  120. >>> y = Tensor(np.array([4, 5, 6]).astype(np.float32))
  121. >>> output = add(x, y)
  122. >>> print(output)
  123. [5. 7. 9.]
  124. >>> # case 2: x is a scalar and y is a Tensor
  125. >>> add = ops.Add()
  126. >>> x = Tensor(1, mindspore.int32)
  127. >>> y = Tensor(np.array([4, 5, 6]).astype(np.float32))
  128. >>> output = add(x, y)
  129. >>> print(output)
  130. [5. 6. 7.]
  131. >>> # the data type of x is int32, the data type of y is float32,
  132. >>> # and the output is the data format of higher precision flost32.
  133. >>> print(output.dtype)
  134. Float32
  135. """
  136. def infer_value(self, x, y):
  137. if x is not None and y is not None:
  138. x = x.asnumpy()
  139. y = y.asnumpy()
  140. out = x + y
  141. out = np.array(out, x.dtype)
  142. return Tensor(out)
  143. return None
  144. class TensorAdd(_MathBinaryOp):
  145. """
  146. Same as operator Add. TensorAdd will be deprecated in the future.
  147. Please use Add instead.
  148. """
  149. @deprecated("1.1", "Add", True)
  150. @prim_attr_register
  151. def __init__(self):
  152. """Initialize TensorAdd."""
  153. _MathBinaryOp.__init__(self)
  154. def infer_value(self, x, y):
  155. if x is not None and y is not None:
  156. x = x.asnumpy()
  157. y = y.asnumpy()
  158. out = x + y
  159. out = np.array(out, x.dtype)
  160. return Tensor(out)
  161. return None
  162. class AssignAdd(PrimitiveWithInfer):
  163. """
  164. Updates a `Parameter` by adding a value to it.
  165. Inputs of `variable` and `value` comply with the implicit type conversion rules to make the data types consistent.
  166. If they have different data types, lower priority data type will be converted to
  167. relatively highest priority data type.
  168. If `value` is a number, the number is automatically converted to Tensor,
  169. and the data type is consistent with the Tensor data type involved in the operation.
  170. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  171. Note:
  172. Since `variable` is a data type Parameter, the data type cannot be changed,
  173. so only the type of `value` is allowed to be promoted to the type of `variable`.
  174. And the conversion type supported by different devices will be different,
  175. it is recommended to use the same data type when using this operator.
  176. Inputs:
  177. - **variable** (Parameter) - The `Parameter`.
  178. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  179. - **value** (Union[numbers.Number, Tensor]) - The value to be added to the `variable`.
  180. It must have the same shape as `variable` if it is a Tensor.
  181. it is recommended to use the same data type when using this operator.
  182. Outputs:
  183. Tensor, has the same data type and shape as original `variable`.
  184. Raises:
  185. TypeError: If `value` is neither Number nor Tensor.
  186. Supported Platforms:
  187. ``Ascend`` ``GPU`` ``CPU``
  188. Examples:
  189. >>> class Net(nn.Cell):
  190. ... def __init__(self):
  191. ... super(Net, self).__init__()
  192. ... self.AssignAdd = ops.AssignAdd()
  193. ... self.variable = mindspore.Parameter(initializer(1, [1], mindspore.int64), name="global_step")
  194. ...
  195. ... def construct(self, x):
  196. ... self.AssignAdd(self.variable, x)
  197. ... return self.variable
  198. ...
  199. >>> net = Net()
  200. >>> value = Tensor(np.ones([1]).astype(np.int64)*100)
  201. >>> output = net(value)
  202. >>> print(output)
  203. [101]
  204. """
  205. __mindspore_signature__ = (
  206. sig.make_sig('x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
  207. sig.make_sig('value', dtype=sig.sig_dtype.T)
  208. )
  209. @prim_attr_register
  210. def __init__(self):
  211. """Initialize AssignAdd"""
  212. self.init_prim_io_names(inputs=['ref', 'value'], outputs=['output'])
  213. self.add_prim_attr('side_effect_mem', True)
  214. def infer_shape(self, variable, value):
  215. return value
  216. def infer_dtype(self, variable, value):
  217. args = {"variable": variable, "value": value}
  218. validator.check_scalar_or_tensor_types_same(args, mstype.number_type, self.name)
  219. return value
  220. class AssignSub(PrimitiveWithInfer):
  221. """
  222. Updates a `Parameter` by subtracting a value from it.
  223. Inputs of `variable` and `value` comply with the implicit type conversion rules to make the data types consistent.
  224. If they have different data types, lower priority data type will be converted to
  225. relatively highest priority data type.
  226. If `value` is a number, the number is automatically converted to Tensor,
  227. and the data type is consistent with the Tensor data type involved in the operation.
  228. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  229. Note:
  230. Since `variable` is a data type Parameter, the data type cannot be changed,
  231. so only the type of `value` is allowed to be promoted to the type of `variable`.
  232. And the conversion type supported by different devices will be different,
  233. it is recommended to use the same data type when using this operator.
  234. Inputs:
  235. - **variable** (Parameter) - The `Parameter`.
  236. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  237. - **value** (Union[numbers.Number, Tensor]) - The value to be subtracted from the `variable`.
  238. It must have the same shape as `variable` if it is a Tensor.
  239. it is recommended to use the same data type when using this operator.
  240. Outputs:
  241. Tensor, has the same data type and shape as original `variable`.
  242. Raises:
  243. TypeError: If `value` is neither Number nor Tensor.
  244. Supported Platforms:
  245. ``Ascend``
  246. Examples:
  247. >>> class Net(nn.Cell):
  248. ... def __init__(self):
  249. ... super(Net, self).__init__()
  250. ... self.AssignSub = ops.AssignSub()
  251. ... self.variable = mindspore.Parameter(initializer(1, [1], mindspore.int32), name="global_step")
  252. ...
  253. ... def construct(self, x):
  254. ... self.AssignSub(self.variable, x)
  255. ... return self.variable
  256. ...
  257. >>> net = Net()
  258. >>> value = Tensor(np.ones([1]).astype(np.int32)*100)
  259. >>> output = net(value)
  260. >>> print(output)
  261. [-99]
  262. """
  263. __mindspore_signature__ = (
  264. sig.make_sig('variable', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
  265. sig.make_sig('value', dtype=sig.sig_dtype.T)
  266. )
  267. @prim_attr_register
  268. def __init__(self):
  269. """Initialize AssignSub"""
  270. self.init_prim_io_names(inputs=['ref', 'value'], outputs=['output'])
  271. self.add_prim_attr('side_effect_mem', True)
  272. def infer_shape(self, variable, value):
  273. return value
  274. def infer_dtype(self, variable, value):
  275. args = {"variable": variable, "value": value}
  276. validator.check_scalar_or_tensor_types_same(args, mstype.number_type, self.name)
  277. return value
  278. class _Reduce(PrimitiveWithInfer):
  279. """
  280. Definition of base class of reduction class operators.
  281. Args:
  282. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  283. If false, don't keep these dimensions. Default: False.
  284. """
  285. __mindspore_signature__ = (
  286. sig.make_sig('input_x'),
  287. sig.make_sig('axis', default=())
  288. )
  289. @prim_attr_register
  290. def __init__(self, keep_dims=False):
  291. """Initialize Reduce"""
  292. validator.check_value_type('keep_dims', keep_dims, [bool], self.name)
  293. self.init_prim_io_names(inputs=['input_x', 'axis'], outputs=['y'])
  294. def __call__(self, x, axis=()):
  295. args = [x, axis]
  296. output = _run_op(self, self.name, args)
  297. return output
  298. def do_infer(self, input_x, axis, valid_dtype=mstype.number_type):
  299. """ return meta infos of input parameters """
  300. axis_v = axis['value']
  301. input_shp = input_x['shape']
  302. args = {'input_x': input_x['dtype']}
  303. validator.check_tensors_dtypes_same_and_valid(args, valid_dtype, self.name)
  304. if not isinstance(axis, mstype.tensor_type) and axis_v is None:
  305. raise ValueError(f"For {self.name}, axis must be const.")
  306. out_shape = _infer_shape_reduce(input_shp, axis_v, self.keep_dims, self.name)
  307. if -1 in input_shp:
  308. if axis_v is None:
  309. max_v = max(input_shp)
  310. if 'max_shape' and 'min_shape' in input_x:
  311. input_max_shp = input_x['max_shape']
  312. max_v = max(input_max_shp)
  313. axis_shape_list = axis['shape']
  314. if len(axis_shape_list) != 1:
  315. raise ValueError("axis_shape must be 1-D, but got ", len(axis_shape_list))
  316. axis_shape = axis_shape_list[0]
  317. if len(axis_shape) == 1 and axis_shape[0] == -1 and not self.keep_dims:
  318. out_shape = np.array([-2]).tolist()
  319. output_min_shape = np.ones_like(input_shp).tolist()
  320. output_max_shape = max_v * np.ones_like(input_shp)
  321. output_max_shape = output_max_shape.tolist()
  322. elif not self.keep_dims:
  323. out_shape = -1 * np.ones_like(input_shp[:-axis_shape])
  324. out_shape = out_shape.tolist()
  325. output_min_shape = np.ones_like(out_shape).tolist()
  326. output_max_shape = max_v * np.ones_like(out_shape)
  327. output_max_shape = output_max_shape.tolist()
  328. else:
  329. out_shape = -1 * np.ones_like(input_shp)
  330. out_shape = out_shape.tolist()
  331. output_min_shape = np.ones_like(input_shp).tolist()
  332. output_max_shape = max_v * np.ones_like(input_shp)
  333. output_max_shape = output_max_shape.tolist()
  334. else:
  335. output_max_shape = _infer_shape_reduce(input_x['max_shape'], axis_v, self.keep_dims, self.name)
  336. output_min_shape = _infer_shape_reduce(input_x['min_shape'], axis_v, self.keep_dims, self.name)
  337. else:
  338. output_max_shape = out_shape
  339. output_min_shape = out_shape
  340. value = None
  341. if input_x['value'] is not None:
  342. prim_map = {
  343. 'ReduceSum': np.sum,
  344. 'ReduceMax': np.max,
  345. 'ReduceMin': np.min,
  346. }
  347. np_reduce_func = prim_map.get(self.name, None)
  348. if np_reduce_func is not None:
  349. value = input_x['value'].asnumpy()
  350. if not axis_v:
  351. axis_v = [i for i in range(len(input_x['shape']))]
  352. axis_v = tuple(axis_v)
  353. value = np_reduce_func(value, axis_v, keepdims=self.keep_dims)
  354. value = np.array(value)
  355. value = Tensor(value)
  356. return {'shape': out_shape,
  357. 'min_shape': output_min_shape,
  358. 'max_shape': output_max_shape,
  359. 'dtype': input_x['dtype'],
  360. 'value': value}
  361. def __infer__(self, input_x, axis):
  362. return self.do_infer(input_x, axis)
  363. class ReduceMean(_Reduce):
  364. """
  365. Reduces a dimension of a tensor by averaging all elements in the dimension, by Default. And also can reduces
  366. a dimension of `x` along the axis. Determine whether the dimensions of the output and input are the same by
  367. controlling `keep_dims`.
  368. Args:
  369. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  370. If false, don't keep these dimensions. Default: False.
  371. Inputs:
  372. - **x** (Tensor[Number]) - The input tensor. The dtype of the tensor to be reduced is number.
  373. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  374. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  375. Only constant value is allowed. Must be in the range [-rank(`x`), rank(`x`)).
  376. Outputs:
  377. Tensor, has the same dtype as the `x`.
  378. - If axis is (), and keep_dims is False,
  379. the output is a 0-D tensor representing the mean of all elements in the input tensor.
  380. - If axis is int, set as 2, and keep_dims is False,
  381. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  382. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  383. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  384. Raises:
  385. TypeError: If `keep_dims` is not a bool.
  386. TypeError: If `x` is not a Tensor.
  387. ValueError: If `axis` is not one of the following: int, tuple or list.
  388. Supported Platforms:
  389. ``Ascend`` ``GPU`` ``CPU``
  390. Examples:
  391. >>> x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  392. >>> op = ops.ReduceMean(keep_dims=True)
  393. >>> output = op(x, 1)
  394. >>> result = output.shape
  395. >>> print(result)
  396. (3, 1, 5, 6)
  397. >>> # case 1: Reduces a dimension by averaging all elements in the dimension.
  398. >>> x = Tensor(np.array([[[1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3]],
  399. ... [[4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5], [6, 6, 6, 6, 6, 6]],
  400. ... [[7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8], [9, 9, 9, 9, 9, 9]]]), mindspore.float32)
  401. >>> output = op(x)
  402. >>> print(output)
  403. [[[5.]]]
  404. >>> print(output.shape)
  405. (1, 1, 1)
  406. >>> # case 2: Reduces a dimension along the axis 0
  407. >>> output = op(x, 0)
  408. >>> print(output)
  409. [[[4. 4. 4. 4. 4. 4.]
  410. [5. 5. 5. 5. 5. 5.]
  411. [6. 6. 6. 6. 6. 6.]]]
  412. >>> # case 3: Reduces a dimension along the axis 1
  413. >>> output = op(x, 1)
  414. >>> print(output)
  415. [[[2. 2. 2. 2. 2. 2.]]
  416. [[5. 5. 5. 5. 5. 5.]]
  417. [[8. 8. 8. 8. 8. 8.]]]
  418. >>> # case 4: Reduces a dimension along the axis 2
  419. >>> output = op(x, 2)
  420. >>> print(output)
  421. [[[1. ]
  422. [2. ]
  423. [3. ]]
  424. [[4. ]
  425. [5. ]
  426. [6. ]]
  427. [[7.0000005]
  428. [8. ]
  429. [9. ]]]
  430. """
  431. class ReduceSum(_Reduce):
  432. """
  433. Reduces a dimension of a tensor by summing all elements in the dimension, by Default. And also can reduces
  434. a dimension of `x` along the axis. Determine whether the dimensions of the output and input are the same by
  435. controlling `keep_dims`.
  436. Args:
  437. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  438. If false, don't keep these dimensions. Default: False.
  439. Inputs:
  440. - **x** (Tensor[Number]) - The input tensor. The dtype of the tensor to be reduced is number.
  441. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  442. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  443. Only constant value is allowed. Must be in the range [-rank(`x`), rank(`x`)).
  444. Outputs:
  445. Tensor, has the same dtype as the `x`.
  446. - If axis is (), and keep_dims is False,
  447. the output is a 0-D tensor representing the sum of all elements in the input tensor.
  448. - If axis is int, set as 2, and keep_dims is False,
  449. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  450. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  451. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  452. Raises:
  453. TypeError: If `keep_dims` is not a bool.
  454. TypeError: If `x` is not a Tensor.
  455. ValueError: If `axis` is None.
  456. Supported Platforms:
  457. ``Ascend`` ``GPU`` ``CPU``
  458. Examples:
  459. >>> x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  460. >>> op = ops.ReduceSum(keep_dims=True)
  461. >>> output = op(x, 1)
  462. >>> output.shape
  463. (3, 1, 5, 6)
  464. >>> # case 1: Reduces a dimension by averaging all elements in the dimension.
  465. >>> x = Tensor(np.array([[[1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3]],
  466. ... [[4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5], [6, 6, 6, 6, 6, 6]],
  467. ... [[7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8], [9, 9, 9, 9, 9, 9]]]), mindspore.float32)
  468. >>> output = op(x)
  469. >>> print(output)
  470. [[[270.]]]
  471. >>> print(output.shape)
  472. (1, 1, 1)
  473. >>> # case 2: Reduces a dimension along axis 0.
  474. >>> output = op(x, 0)
  475. >>> print(output)
  476. [[[12. 12. 12. 12. 12. 12.]
  477. [15. 15. 15. 15. 15. 15.]
  478. [18. 18. 18. 18. 18. 18.]]]
  479. >>> # case 3: Reduces a dimension along axis 1.
  480. >>> output = op(x, 1)
  481. >>> print(output)
  482. [[[ 6. 6. 6. 6. 6. 6.]]
  483. [[15. 15. 15. 15. 15. 15.]]
  484. [[24. 24. 24. 24. 24. 24.]]]
  485. >>> # case 4: Reduces a dimension along axis 2.
  486. >>> output = op(x, 2)
  487. >>> print(output)
  488. [[[ 6.]
  489. [12.]
  490. [18.]]
  491. [[24.]
  492. [30.]
  493. [36.]]
  494. [[42.]
  495. [48.]
  496. [54.]]]
  497. """
  498. @prim_attr_register
  499. def __init__(self, keep_dims=False):
  500. """Initialize ReduceSum"""
  501. super(ReduceSum, self).__init__(keep_dims)
  502. self.__setattr_flag__ = True
  503. class ReduceAll(_Reduce):
  504. """
  505. Reduces a dimension of a tensor by the "logicalAND" of all elements in the dimension, by Default. And also can
  506. reduces a dimension of `x` along the axis. Determine whether the dimensions of the output and input are the same by
  507. controlling `keep_dims`.
  508. Args:
  509. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  510. If false, don't keep these dimensions.
  511. Default : False, don't keep these reduced dimensions.
  512. Inputs:
  513. - **x** (Tensor[bool]) - The input tensor. The dtype of the tensor to be reduced is bool.
  514. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  515. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  516. Only constant value is allowed. Must be in the range [-rank(x), rank(x)).
  517. Outputs:
  518. Tensor, the dtype is bool.
  519. - If axis is (), and keep_dims is False,
  520. the output is a 0-D tensor representing the "logical and" of all elements in the input tensor.
  521. - If axis is int, set as 2, and keep_dims is False,
  522. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  523. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  524. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  525. Raises:
  526. TypeError: If `keep_dims` is not a bool.
  527. TypeError: If `x` is not a Tensor.
  528. ValueError: If `axis` is not one of the following: int, tuple or list.
  529. Supported Platforms:
  530. ``Ascend`` ``GPU`` ``CPU``
  531. Examples:
  532. >>> x = Tensor(np.array([[True, False], [True, True]]))
  533. >>> op = ops.ReduceAll(keep_dims=True)
  534. >>> # case 1: Reduces a dimension by averaging all elements in the dimension.
  535. >>> output = op(x)
  536. >>> print(output)
  537. [[False]]
  538. >>> print(output.shape)
  539. (1, 1)
  540. >>> # case 2: Reduces a dimension along axis 0.
  541. >>> output = op(x, 0)
  542. >>> print(output)
  543. [[ True False]]
  544. >>> # case 3: Reduces a dimension along axis 1.
  545. >>> output = op(x, 1)
  546. >>> print(output)
  547. [[False]
  548. [ True]]
  549. """
  550. def __infer__(self, input_x, axis):
  551. return self.do_infer(input_x, axis, (mstype.bool_,))
  552. class ReduceAny(_Reduce):
  553. """
  554. Reduces a dimension of a tensor by the "logical OR" of all elements in the dimension, by Default. And also can
  555. reduces a dimension of `x` along the axis. Determine whether the dimensions of the output and input are the same by
  556. controlling `keep_dims`.
  557. Args:
  558. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  559. If false, don't keep these dimensions.
  560. Default : False, don't keep these reduced dimensions.
  561. Inputs:
  562. - **x** (Tensor[bool]) - The input tensor. The dtype of the tensor to be reduced is bool.
  563. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  564. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  565. Only constant value is allowed. Must be in the range [-rank(x), rank(x)).
  566. Outputs:
  567. Tensor, the dtype is bool.
  568. - If axis is (), and keep_dims is False,
  569. the output is a 0-D tensor representing the "logical or" of all elements in the input tensor.
  570. - If axis is int, set as 2, and keep_dims is False,
  571. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  572. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  573. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  574. Raises:
  575. TypeError: If `keep_dims` is not a bool.
  576. TypeError: If `x` is not a Tensor.
  577. ValueError: If `axis` is not one of the following: int, tuple or list.
  578. Supported Platforms:
  579. ``Ascend`` ``GPU`` ``CPU``
  580. Examples:
  581. >>> x = Tensor(np.array([[True, False], [True, True]]))
  582. >>> op = ops.ReduceAny(keep_dims=True)
  583. >>> # case 1: Reduces a dimension by averaging all elements in the dimension.
  584. >>> output = op(x)
  585. >>> print(output)
  586. [[ True]]
  587. >>> print(output.shape)
  588. (1, 1)
  589. >>> # case 2: Reduces a dimension along axis 0.
  590. >>> output = op(x, 0)
  591. >>> print(output)
  592. [[ True True]]
  593. >>> # case 3: Reduces a dimension along axis 1.
  594. >>> output = op(x, 1)
  595. >>> print(output)
  596. [[True]
  597. [ True]]
  598. """
  599. def __infer__(self, input_x, axis):
  600. return self.do_infer(input_x, axis, (mstype.bool_,))
  601. class ReduceMax(_Reduce):
  602. """
  603. Reduces a dimension of a tensor by the maximum value in this dimension, by Default. And also can
  604. reduces a dimension of `x` along the axis. Determine whether the dimensions of the output and input are the same by
  605. controlling `keep_dims`.
  606. Args:
  607. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  608. If false, don't keep these dimensions.
  609. Default : False, don't keep these reduced dimensions.
  610. Inputs:
  611. - **x** (Tensor[Number]) - The input tensor. The dtype of the tensor to be reduced is number.
  612. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  613. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  614. Only constant value is allowed. Must be in the range [-rank(x), rank(x)).
  615. Outputs:
  616. Tensor, has the same dtype as the `x`.
  617. - If axis is (), and keep_dims is False,
  618. the output is a 0-D tensor representing the maximum of all elements in the input tensor.
  619. - If axis is int, set as 2, and keep_dims is False,
  620. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  621. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  622. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  623. Raises:
  624. TypeError: If `keep_dims` is not a bool.
  625. TypeError: If `x` is not a Tensor.
  626. ValueError: If `axis` is not one of the following: int, tuple or list.
  627. Supported Platforms:
  628. ``Ascend`` ``GPU`` ``CPU``
  629. Examples:
  630. >>> x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  631. >>> op = ops.ReduceMax(keep_dims=True)
  632. >>> output = op(x, 1)
  633. >>> result = output.shape
  634. >>> print(result)
  635. (3, 1, 5, 6)
  636. >>> # case 1: Reduces a dimension by averaging all elements in the dimension.
  637. >>> x = Tensor(np.array([[[1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3]],
  638. ... [[4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5], [6, 6, 6, 6, 6, 6]],
  639. ... [[7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8], [9, 9, 9, 9, 9, 9]]]), mindspore.float32)
  640. >>> output = op(x)
  641. >>> print(output)
  642. [[[9.]]]
  643. >>> print(output.shape)
  644. (1, 1, 1)
  645. >>> # case 2: Reduces a dimension along axis 0.
  646. >>> output = op(x, 0)
  647. >>> print(output)
  648. [[[7. 7. 7. 7. 7. 7.]
  649. [8. 8. 8. 8. 8. 8.]
  650. [9. 9. 9. 9. 9. 9.]]]
  651. >>> # case 3: Reduces a dimension along axis 1.
  652. >>> output = op(x, 1)
  653. >>> print(output)
  654. [[[3. 3. 3. 3. 3. 3.]]
  655. [[6. 6. 6. 6. 6. 6.]]
  656. [[9. 9. 9. 9. 9. 9.]]]
  657. >>> # case 4: Reduces a dimension along axis 2.
  658. >>> output = op(x, 2)
  659. >>> print(output)
  660. [[[1.]
  661. [2.]
  662. [3.]]
  663. [[4.]
  664. [5.]
  665. [6.]]
  666. [[7.]
  667. [8.]
  668. [9.]]]
  669. """
  670. @prim_attr_register
  671. def __init__(self, keep_dims=False):
  672. """Initialize ReduceMax."""
  673. super(ReduceMax, self).__init__(keep_dims)
  674. self.__setattr_flag__ = True
  675. def __infer__(self, input_x, axis):
  676. return self.do_infer(input_x, axis, mstype.number_type + (mstype.bool_,))
  677. class ReduceMin(_Reduce):
  678. """
  679. Reduces a dimension of a tensor by the minimum value in the dimension, by Default. And also can
  680. reduces a dimension of `x` along the axis. Determine whether the dimensions of the output and input are the same by
  681. controlling `keep_dims`.
  682. Args:
  683. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  684. If false, don't keep these dimensions.
  685. Default : False, don't keep these reduced dimensions.
  686. Inputs:
  687. - **x** (Tensor[Number]) - The input tensor. The dtype of the tensor to be reduced is number.
  688. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  689. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  690. Only constant value is allowed. Must be in the range [-rank(x), rank(x)).
  691. Outputs:
  692. Tensor, has the same dtype as the `x`.
  693. - If axis is (), and keep_dims is False,
  694. the output is a 0-D tensor representing the minimum of all elements in the input tensor.
  695. - If axis is int, set as 2, and keep_dims is False,
  696. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  697. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  698. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  699. Raises:
  700. TypeError: If `keep_dims` is not a bool.
  701. TypeError: If `x` is not a Tensor.
  702. ValueError: If `axis` is not one of the following: int, tuple or list.
  703. Supported Platforms:
  704. ``Ascend`` ``GPU`` ``CPU``
  705. Examples:
  706. >>> x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  707. >>> op = ops.ReduceMin(keep_dims=True)
  708. >>> output = op(x, 1)
  709. >>> result = output.shape
  710. >>> print(result)
  711. (3, 1, 5, 6)
  712. >>> # case 1: Reduces a dimension by averaging all elements in the dimension.
  713. >>> x = Tensor(np.array([[[1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3]],
  714. ... [[4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5], [6, 6, 6, 6, 6, 6]],
  715. ... [[7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8], [9, 9, 9, 9, 9, 9]]]), mindspore.float32)
  716. >>> output = op(x)
  717. >>> print(output)
  718. [[[1.]]]
  719. >>> print(output.shape)
  720. (1, 1, 1)
  721. >>> # case 2: Reduces a dimension along axis 0.
  722. >>> output = op(x, 0)
  723. >>> print(output)
  724. [[[1. 1. 1. 1. 1. 1.]
  725. [2. 2. 2. 2. 2. 2.]
  726. [3. 3. 3. 3. 3. 3.]]]
  727. >>> # case 3: Reduces a dimension along axis 1.
  728. >>> output = op(x, 1)
  729. >>> print(output)
  730. [[[1. 1. 1. 1. 1. 1.]]
  731. [[4. 4. 4. 4. 4. 4.]]
  732. [[7. 7. 7. 7. 7. 7.]]]
  733. >>> # case 4: Reduces a dimension along axis 2.
  734. >>> output = op(x, 2)
  735. >>> print(output)
  736. [[[1.]
  737. [2.]
  738. [3.]]
  739. [[4.]
  740. [5.]
  741. [6.]]
  742. [[7.]
  743. [8.]
  744. [9.]]]
  745. """
  746. class ReduceProd(_Reduce):
  747. """
  748. Reduces a dimension of a tensor by multiplying all elements in the dimension, by Default. And also can
  749. reduces a dimension of `x` along the axis. Determine whether the dimensions of the output and input are the same by
  750. controlling `keep_dims`.
  751. Args:
  752. keep_dims (bool): If true, keep these reduced dimensions and the length is 1.
  753. If false, don't keep these dimensions.
  754. Default : False, don't keep these reduced dimensions.
  755. Inputs:
  756. - **x** (Tensor[Number]) - The input tensor. The dtype of the tensor to be reduced is number.
  757. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  758. - **axis** (Union[int, tuple(int), list(int)]) - The dimensions to reduce. Default: (), reduce all dimensions.
  759. Only constant value is allowed. Must be in the range [-rank(x), rank(x)).
  760. Outputs:
  761. Tensor, has the same dtype as the `x`.
  762. - If axis is (), and keep_dims is False,
  763. the output is a 0-D tensor representing the product of all elements in the input tensor.
  764. - If axis is int, set as 2, and keep_dims is False,
  765. the shape of output is :math:`(x_1, x_3, ..., x_R)`.
  766. - If axis is tuple(int), set as (2, 3), and keep_dims is False,
  767. the shape of output is :math:`(x_1, x_4, ..., x_R)`.
  768. Raises:
  769. TypeError: If `keep_dims` is not a bool.
  770. TypeError: If `x` is not a Tensor.
  771. ValueError: If `axis` is not one of the following: int, tuple or list.
  772. Supported Platforms:
  773. ``Ascend``
  774. Examples:
  775. >>> x = Tensor(np.random.randn(3, 4, 5, 6).astype(np.float32))
  776. >>> op = ops.ReduceProd(keep_dims=True)
  777. >>> output = op(x, 1)
  778. >>> result = output.shape
  779. >>> print(result)
  780. (3, 1, 5, 6)
  781. >>> # case 1: Reduces a dimension by averaging all elements in the dimension.
  782. >>> x = Tensor(np.array([[[1, 1, 1, 1, 1, 1], [2, 2, 2, 2, 2, 2], [3, 3, 3, 3, 3, 3]],
  783. ... [[4, 4, 4, 4, 4, 4], [5, 5, 5, 5, 5, 5], [6, 6, 6, 6, 6, 6]],
  784. ... [[7, 7, 7, 7, 7, 7], [8, 8, 8, 8, 8, 8], [9, 9, 9, 9, 9, 9]]]), mindspore.float32)
  785. >>> output = op(x)
  786. >>> print(output)
  787. [[[2.2833798e+33]]]
  788. >>> print(output.shape)
  789. (1, 1, 1)
  790. >>> # case 2: Reduces a dimension along axis 0.
  791. >>> output = op(x, 0)
  792. >>> print(output)
  793. [[[ 28. 28. 28. 28. 28. 28.]
  794. [ 80. 80. 80. 80. 80. 80.]
  795. [162. 162. 162. 162. 162. 162.]]]
  796. >>> # case 3: Reduces a dimension along axis 1.
  797. >>> output = op(x, 1)
  798. >>> print(output)
  799. [[[ 6. 6. 6. 6. 6. 6.]]
  800. [[120. 120. 120. 120. 120. 120.]]
  801. [[504. 504. 504. 504. 504. 504.]]]
  802. >>> # case 4: Reduces a dimension along axis 2.
  803. >>> output = op(x, 2)
  804. >>> print(output)
  805. [[[1.00000e+00]
  806. [6.40000e+01]
  807. [7.29000e+02]]
  808. [[4.09600e+03]
  809. [1.56250e+04]
  810. [4.66560e+04]]
  811. [[1.17649e+05]
  812. [2.62144e+05]
  813. [5.31441e+05]]]
  814. """
  815. class CumProd(PrimitiveWithInfer):
  816. """
  817. Computes the cumulative product of the tensor x along axis.
  818. Args:
  819. exclusive (bool): If true, perform exclusive cumulative product. Default: False.
  820. reverse (bool): If true, reverse the result along axis. Default: False
  821. Inputs:
  822. - **x** (Tensor[Number]) - The input tensor.
  823. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  824. - **axis** (int) - The dimensions to compute the cumulative product.
  825. Only constant value is allowed.
  826. Outputs:
  827. Tensor, has the same shape and dtype as the `x`.
  828. Raises:
  829. TypeError: If `exclusive` or `reverse` is not a bool.
  830. ValueError: If `axis` is None.
  831. Supported Platforms:
  832. ``Ascend`` ``GPU``
  833. Examples:
  834. >>> a, b, c, = 1, 2, 3
  835. >>> x = Tensor(np.array([a, b, c]).astype(np.float32))
  836. >>> op0 = ops.CumProd()
  837. >>> output0 = op0(x, 0) # output=[a, a * b, a * b * c]
  838. >>> op1 = ops.CumProd(exclusive=True)
  839. >>> output1 = op1(x, 0) # output=[1, a, a * b]
  840. >>> op2 = ops.CumProd(reverse=True)
  841. >>> output2 = op2(x, 0) # output=[a * b * c, b * c, c]
  842. >>> op3 = ops.CumProd(exclusive=True, reverse=True)
  843. >>> output3 = op3(x, 0) # output=[b * c, c, 1]
  844. >>> print(output0)
  845. [1. 2. 6.]
  846. >>> print(output1)
  847. [1. 1. 2.]
  848. >>> print(output2)
  849. [6. 6. 3.]
  850. >>> print(output3)
  851. [6. 3. 1.]
  852. >>> x = Tensor(np.array([[1, 2, 3], [4, 5, 6], [5, 3, 5]]).astype(np.float32))
  853. >>> output4 = op0(x, 0)
  854. >>> output5 = op0(x, 1)
  855. >>> print(output4)
  856. [[ 1. 2. 3.]
  857. [ 4. 10. 18.]
  858. [20. 30. 90.]]
  859. >>> print(output5)
  860. [[1. 2. 6.]
  861. [4. 20. 120.]
  862. [5. 15. 75.]]
  863. """
  864. @prim_attr_register
  865. def __init__(self, exclusive=False, reverse=False):
  866. """Initialize CumProd."""
  867. cls_name = self.name
  868. self.exclusive = validator.check_value_type("exclusive", exclusive, [bool], cls_name)
  869. self.reverse = validator.check_value_type("reverse", reverse, [bool], cls_name)
  870. self.init_prim_io_names(inputs=['x', 'axis'], outputs=['y'])
  871. def infer_shape(self, x_shape, axis_shape):
  872. return x_shape
  873. def infer_dtype(self, x_type, axis_type):
  874. cls_name = self.name
  875. validator.check_tensor_dtype_valid('x', x_type, mstype.number_type, cls_name)
  876. validator.check_subclass("axis", axis_type, mstype.int_, cls_name)
  877. return x_type
  878. def infer_value(self, x, axis):
  879. if axis is None:
  880. raise ValueError(f"For {self.name}, axis must be const.")
  881. class MatMul(PrimitiveWithCheck):
  882. r"""
  883. Multiplies matrix `x` and matrix `y`.
  884. .. math::
  885. (Output)_{i j}=\sum_{k=1}^{p} a_{i k} b_{k j}=a_{i 1} b_{1 j}+a_{i 2} b_{2 j}+\cdots+a_{i p} b_{p j}, p\in N
  886. where the :math:`i,j` indicates the output of the i-th row and j-th column element.
  887. Args:
  888. transpose_x (bool): If true, `x` is transposed before multiplication. Default: False.
  889. transpose_y (bool): If true, `y` is transposed before multiplication. Default: False.
  890. Inputs:
  891. - **x** (Tensor) - The first tensor to be multiplied. The shape of the tensor is :math:`(N, C)`. If
  892. `transpose_x` is True, its shape must be :math:`(N, C)` after transpose.
  893. - **y** (Tensor) - The second tensor to be multiplied. The shape of the tensor is :math:`(C, M)`. If
  894. `transpose_y` is True, its shape must be :math:`(C, M)` after transpose.
  895. Outputs:
  896. Tensor, the shape of the output tensor is :math:`(N, M)`.
  897. Raises:
  898. TypeError: If `transpose_a` or `transpose_b` is not a bool.
  899. ValueError: If the column of matrix dimensions of `x` is not equal to
  900. the row of matrix dimensions of `y`.
  901. ValueError: If length of shape of `x` or `y` is not equal to 2.
  902. Supported Platforms:
  903. ``Ascend`` ``GPU`` ``CPU``
  904. Examples:
  905. >>> x = Tensor(np.ones(shape=[1, 3]), mindspore.float32)
  906. >>> y = Tensor(np.ones(shape=[3, 4]), mindspore.float32)
  907. >>> matmul = ops.MatMul()
  908. >>> output = matmul(x, y)
  909. >>> print(output)
  910. [[3. 3. 3. 3.]]
  911. """
  912. @prim_attr_register
  913. def __init__(self, transpose_a=False, transpose_b=False):
  914. """Initialize MatMul."""
  915. self.init_prim_io_names(inputs=['x1', 'x2'], outputs=['output'])
  916. cls_name = self.name
  917. validator.check_value_type("transpose_a", transpose_a, [bool], cls_name)
  918. validator.check_value_type("transpose_b", transpose_b, [bool], cls_name)
  919. def check_shape_size(self, x1, x2):
  920. """Check the shape size of inputs for MatMul."""
  921. if len(x1) != 2 or len(x2) != 2:
  922. raise ValueError('P.MatMul inputs x1, x2 should have the same dimension size and '
  923. + f'equal to 2, while x1 size is ({len(x1)}) and x2 size is ({len(x2)}).')
  924. def check_shape(self, x1, x2):
  925. self.check_shape_size(x1, x2)
  926. cls_name = self.name
  927. # expected dimension of x, y, x:[...,a,b] y:[..., c,d], the dim size should be the same except the last two
  928. for i in range(len(x1) - 2):
  929. if x1[i] != x2[i]:
  930. raise ValueError(f'For \'{cls_name}\' shape in dim[{i}] not the same, '
  931. + f'while x1 is {x1[i]}, x2 is {x2[i]}')
  932. # validate whether last two dims satisfying matrix multiply
  933. x1_last = x1[-2:]
  934. x2_last = x2[-2:]
  935. x1_col = x1_last[not self.transpose_a]
  936. x2_row = x2_last[self.transpose_b]
  937. if np.all(np.array(x1) != -1) and np.all(np.array(x2) != -1):
  938. if x1_col != x2_row:
  939. raise ValueError(f'For \'{cls_name}\' evaluator shapes of inputs can not do this operator,'
  940. f' dimensions must be equal,'
  941. + f' got {x1_col} and {x2_row}, with x1 shape {x1}(transpose_a={self.transpose_a})'
  942. + f', x2 shape {x2}(transpose_b={self.transpose_b}).')
  943. # set attribute
  944. self.add_prim_attr('transpose_x1', self.transpose_a)
  945. self.add_prim_attr('transpose_x2', self.transpose_b)
  946. def check_dtype(self, x1, x2):
  947. args = {"x1": x1, "x2": x2}
  948. validator.check_tensors_dtypes_same_and_valid(args, mstype.float_type + mstype.int_type, self.name)
  949. class BatchMatMul(MatMul):
  950. r"""
  951. Computes matrix multiplication between two tensors by batch.
  952. .. math::
  953. \\text{output}[..., :, :] = \\text{matrix}(x[..., :, :]) * \\text{matrix}(y[..., :, :])
  954. The two input tensors must have the same rank and the rank must be not less than `3`.
  955. Args:
  956. transpose_x (bool): If true, the last two dimensions of `x` is transposed before multiplication.
  957. Default: False.
  958. transpose_y (bool): If true, the last two dimensions of `y` is transposed before multiplication.
  959. Default: False.
  960. Inputs:
  961. - **x** (Tensor) - The first tensor to be multiplied. The shape of the tensor is :math:`(*B, N, C)`,
  962. where :math:`*B` represents the batch size which can be multidimensional, :math:`N` and :math:`C` are the
  963. size of the last two dimensions. If `transpose_a` is True, its shape must be :math:`(*B, C, N)`.
  964. - **y** (Tensor) - The second tensor to be multiplied. The shape of the tensor is :math:`(*B, C, M)`. If
  965. `transpose_b` is True, its shape must be :math:`(*B, M, C)`.
  966. Outputs:
  967. Tensor, the shape of the output tensor is :math:`(*B, N, M)`.
  968. Raises:
  969. TypeError: If `transpose_x` or `transpose_y` is not a bool.
  970. ValueError: If length of shape of `x` is not equal to length of shape of `y` or
  971. length of shape of `x` is less than 3.
  972. Supported Platforms:
  973. ``Ascend`` ``GPU`` ``CPU``
  974. Examples:
  975. >>> x = Tensor(np.ones(shape=[2, 4, 1, 3]), mindspore.float32)
  976. >>> y = Tensor(np.ones(shape=[2, 4, 3, 4]), mindspore.float32)
  977. >>> batmatmul = ops.BatchMatMul()
  978. >>> output = batmatmul(x, y)
  979. >>> print(output)
  980. [[[[3. 3. 3. 3.]]
  981. [[3. 3. 3. 3.]]
  982. [[3. 3. 3. 3.]]
  983. [[3. 3. 3. 3.]]]
  984. [[[3. 3. 3. 3.]]
  985. [[3. 3. 3. 3.]]
  986. [[3. 3. 3. 3.]]
  987. [[3. 3. 3. 3.]]]]
  988. >>> x = Tensor(np.ones(shape=[2, 4, 3, 1]), mindspore.float32)
  989. >>> y = Tensor(np.ones(shape=[2, 4, 3, 4]), mindspore.float32)
  990. >>> batmatmul = ops.BatchMatMul(transpose_a=True)
  991. >>> output = batmatmul(x, y)
  992. >>> print(output)
  993. [[[[3. 3. 3. 3.]]
  994. [[3. 3. 3. 3.]]
  995. [[3. 3. 3. 3.]]
  996. [[3. 3. 3. 3.]]]
  997. [[[3. 3. 3. 3.]]
  998. [[3. 3. 3. 3.]]
  999. [[3. 3. 3. 3.]]
  1000. [[3. 3. 3. 3.]]]]
  1001. """
  1002. @prim_attr_register
  1003. def __init__(self, transpose_a=False, transpose_b=False):
  1004. """Initialize BatchMatMul."""
  1005. self.init_prim_io_names(inputs=['x1', 'x2'], outputs=['output'])
  1006. cls_name = self.name
  1007. validator.check_value_type("transpose_a", transpose_a, [bool], cls_name)
  1008. validator.check_value_type("transpose_b", transpose_b, [bool], cls_name)
  1009. def check_shape_size(self, x, y):
  1010. if len(x) != len(y) or len(x) < 3:
  1011. raise ValueError('For \'BatchMatMul\' input x, y should be the same dimension size and should be '
  1012. 'greater or equal to 3,' + f' while x size = {len(x)}, y size= {len(y)}')
  1013. class CumSum(PrimitiveWithInfer):
  1014. """
  1015. Computes the cumulative sum of input tensor along axis.
  1016. .. math::
  1017. y_i = x_1 + x_2 + x_3 + ... + x_i
  1018. Args:
  1019. exclusive (bool): If true, perform exclusive mode. Default: False.
  1020. reverse (bool): If true, perform inverse cumulative sum. Default: False.
  1021. Inputs:
  1022. - **input** (Tensor) - The input tensor to accumulate.
  1023. - **axis** (int) - The axis to accumulate the tensor's value. Only constant value is allowed.
  1024. Must be in the range [-rank(input), rank(input)).
  1025. Outputs:
  1026. Tensor, the shape of the output tensor is consistent with the input tensor's.
  1027. Raises:
  1028. TypeError: If `exclusive` or `reverse` is not a bool.
  1029. TypeError: If `axis` is not an int.
  1030. Supported Platforms:
  1031. ``Ascend`` ``GPU`` ``CPU``
  1032. Examples:
  1033. >>> x = Tensor(np.array([[3, 4, 6, 10], [1, 6, 7, 9], [4, 3, 8, 7], [1, 3, 7, 9]]).astype(np.float32))
  1034. >>> cumsum = ops.CumSum()
  1035. >>> # case 1: along the axis 0
  1036. >>> y = cumsum(x, 0)
  1037. >>> print(y)
  1038. [[ 3. 4. 6. 10.]
  1039. [ 4. 10. 13. 19.]
  1040. [ 8. 13. 21. 26.]
  1041. [ 9. 16. 28. 35.]]
  1042. >>> # case 2: along the axis 1
  1043. >>> y = cumsum(x, 1)
  1044. >>> print(y)
  1045. [[ 3. 7. 13. 23.]
  1046. [ 1. 7. 14. 23.]
  1047. [ 4. 7. 15. 22.]
  1048. [ 1. 4. 11. 20.]]
  1049. >>> # Next demonstrate exclusive and reverse, along axis 1
  1050. >>> # case 3: exclusive = True
  1051. >>> cumsum = ops.CumSum(exclusive=True)
  1052. >>> y = cumsum(x, 1)
  1053. >>> print(y)
  1054. [[ 0. 3. 7. 13.]
  1055. [ 0. 1. 7. 14.]
  1056. [ 0. 4. 7. 15.]
  1057. [ 0. 1. 4. 11.]]
  1058. >>> # case 4: reverse = True
  1059. >>> cumsum = ops.CumSum(reverse=True)
  1060. >>> y = cumsum(x, 1)
  1061. >>> print(y)
  1062. [[23. 20. 16. 10.]
  1063. [23. 22. 16. 9.]
  1064. [22. 18. 15. 7.]
  1065. [20. 19. 16. 9.]]
  1066. """
  1067. @prim_attr_register
  1068. def __init__(self, exclusive=False, reverse=False):
  1069. """Initialize cumsum"""
  1070. cls_name = self.name
  1071. validator.check_value_type('exclusive', exclusive, [bool], cls_name)
  1072. validator.check_value_type('reverse', reverse, [bool], cls_name)
  1073. self.init_prim_io_names(inputs=['x', 'axis'], outputs=['y'])
  1074. def __infer__(self, x, axis):
  1075. cls_name = self.name
  1076. x_shp = x['shape']
  1077. if axis['value'] is None:
  1078. raise ValueError(f"For {self.name}, axis must be const.")
  1079. validator.check_value_type('axis', axis['value'], [int], cls_name)
  1080. valid_dtypes = [mstype.uint8, mstype.int8, mstype.int32, mstype.float16, mstype.float32, mstype.float64]
  1081. validator.check_tensor_dtype_valid('x', x['dtype'], valid_dtypes, cls_name)
  1082. return {'shape': x_shp,
  1083. 'dtype': x['dtype'],
  1084. 'value': None}
  1085. class AddN(Primitive):
  1086. """
  1087. Computes addition of all input tensors element-wise.
  1088. All input tensors must have the same shape.
  1089. Inputs:
  1090. - **x** (Union(tuple[Tensor], list[Tensor])) - The input tuple or list
  1091. is made up of multiple tensors whose dtype is number or bool to be added together.
  1092. Outputs:
  1093. Tensor, has the same shape and dtype as each entry of the `x`.
  1094. Raises:
  1095. TypeError: If `x` is neither tuple nor list.
  1096. Supported Platforms:
  1097. ``Ascend`` ``GPU`` ``CPU``
  1098. Examples:
  1099. >>> class NetAddN(nn.Cell):
  1100. ... def __init__(self):
  1101. ... super(NetAddN, self).__init__()
  1102. ... self.addN = ops.AddN()
  1103. ...
  1104. ... def construct(self, *z):
  1105. ... return self.addN(z)
  1106. ...
  1107. >>> net = NetAddN()
  1108. >>> x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  1109. >>> y = Tensor(np.array([4, 5, 6]), mindspore.float32)
  1110. >>> output = net(x, y, x, y)
  1111. >>> print(output)
  1112. [10. 14. 18.]
  1113. """
  1114. @prim_attr_register
  1115. def __init__(self):
  1116. """Initialize AddN."""
  1117. self.init_prim_io_names(inputs=["inputs"], outputs=["sum"])
  1118. def check_elim(self, inputs):
  1119. if len(inputs) != 1:
  1120. return False, None
  1121. if isinstance(inputs[0], Tensor):
  1122. return True, inputs[0]
  1123. raise TypeError("Expecting Tensor, got : {}".format(type(inputs[0])))
  1124. class AccumulateNV2(PrimitiveWithInfer):
  1125. """
  1126. Computes accumulation of all input tensors element-wise.
  1127. AccumulateNV2 is similar to AddN, but there is a significant difference
  1128. among them: AccumulateNV2 will not wait for all of its inputs to be ready
  1129. before summing. That is to say, AccumulateNV2 is able to save
  1130. memory when inputs are ready at different time since the minimum temporary
  1131. storage is proportional to the output size rather than the input size.
  1132. Inputs:
  1133. - **x** (Union(tuple[Tensor], list[Tensor])) - The input tuple or list
  1134. is made up of multiple tensors whose dtype is number to be added together.
  1135. Outputs:
  1136. Tensor, has the same shape and dtype as each entry of the `x`.
  1137. Raises:
  1138. TypeError: If `x` is neither tuple nor list.
  1139. Supported Platforms:
  1140. ``Ascend``
  1141. Examples:
  1142. >>> class NetAccumulateNV2(nn.Cell):
  1143. ... def __init__(self):
  1144. ... super(NetAccumulateNV2, self).__init__()
  1145. ... self.accumulateNV2 = ops.AccumulateNV2()
  1146. ...
  1147. ... def construct(self, *z):
  1148. ... return self.accumulateNV2(z)
  1149. ...
  1150. >>> net = NetAccumulateNV2()
  1151. >>> x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  1152. >>> y = Tensor(np.array([4, 5, 6]), mindspore.float32)
  1153. >>> output = net(x, y, x, y)
  1154. >>> print(output)
  1155. [10. 14. 18.]
  1156. """
  1157. @prim_attr_register
  1158. def __init__(self):
  1159. """Initialize AccumulateNV2."""
  1160. self.__setattr_flag__ = True
  1161. self.init_prim_io_names(inputs=["inputs"], outputs=["sum"])
  1162. def check_elim(self, inputs):
  1163. if len(inputs) != 1:
  1164. return False, None
  1165. if isinstance(inputs[0], Tensor):
  1166. return True, inputs[0]
  1167. raise TypeError("Expecting Tensor, got : {}".format(type(inputs[0])))
  1168. def infer_shape(self, inputs):
  1169. cls_name = self.name
  1170. validator.check_int(len(inputs), 1, Rel.GE, "inputs", cls_name)
  1171. self.add_prim_attr('n', len(inputs))
  1172. shp0 = inputs[0]
  1173. for i, shp in enumerate(inputs):
  1174. validator.check(f"shape of inputs[{i}]", shp, 'shape of inputs[0]', shp0, Rel.EQ, cls_name)
  1175. return shp0
  1176. def infer_dtype(self, inputs):
  1177. cls_name = self.name
  1178. validator.check_value_type("inputs", inputs, [tuple, list], cls_name)
  1179. validator.check_int(len(inputs), 1, Rel.GE, "inputs", cls_name)
  1180. args = {}
  1181. for i, dtype in enumerate(inputs):
  1182. args[f"inputs[{i}]"] = dtype
  1183. validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type + (mstype.bool_,), cls_name)
  1184. return inputs[0]
  1185. class Neg(PrimitiveWithInfer):
  1186. """
  1187. Returns a tensor with negative values of the input tensor element-wise.
  1188. .. math::
  1189. out_{i} = - x_{i}
  1190. Inputs:
  1191. - **x** (Tensor) - The input tensor whose dtype is number.
  1192. :math:`(N,*)` where :math:`*` means ,any number of additional dimensions, its rank should less than 8.
  1193. Outputs:
  1194. Tensor, has the same shape and dtype as input.
  1195. Raises:
  1196. TypeError: If `x` is not a Tensor.
  1197. Supported Platforms:
  1198. ``Ascend`` ``GPU`` ``CPU``
  1199. Examples:
  1200. >>> neg = ops.Neg()
  1201. >>> x = Tensor(np.array([1, 2, -1, 2, 0, -3.5]), mindspore.float32)
  1202. >>> output = neg(x)
  1203. >>> print(output)
  1204. [-1. -2. 1. -2. 0. 3.5]
  1205. """
  1206. @prim_attr_register
  1207. def __init__(self):
  1208. """Initialize Neg"""
  1209. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1210. def infer_shape(self, x_shape):
  1211. return x_shape
  1212. def infer_dtype(self, x_dtype):
  1213. validator.check_tensor_dtype_valid("x", x_dtype, mstype.number_type, self.name)
  1214. return x_dtype
  1215. def infer_value(self, input_x):
  1216. if input_x is not None:
  1217. input_x = input_x.asnumpy()
  1218. out = np.array(-input_x, input_x.dtype)
  1219. return Tensor(out)
  1220. return None
  1221. class InplaceAdd(PrimitiveWithInfer):
  1222. """
  1223. Adds v into specified rows of x. Computes y = x; y[i,] += v.
  1224. Args:
  1225. indices (Union[int, tuple]): Indices into the left-most dimension of x, and determines which rows of x
  1226. to add with v. It is an integer or a tuple, whose value is in [0, the first dimension size of x).
  1227. Inputs:
  1228. - **x** (Tensor) - The first input is a tensor whose data type is float16, float32 or int32.
  1229. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  1230. - **input_v** (Tensor) - The second input is a tensor that has the same dimension sizes as x except
  1231. the first dimension, which must be the same as indices's size. It has the same data type with `x`.
  1232. Outputs:
  1233. Tensor, has the same shape and dtype as x.
  1234. Raises:
  1235. TypeError: If `indices` is neither int nor tuple.
  1236. TypeError: If `indices` is a tuple whose elements are not all int.
  1237. ValueError: If length of shape of `x` is not equal to length of shape of `input_v`.
  1238. Supported Platforms:
  1239. ``Ascend``
  1240. Examples:
  1241. >>> indices = (0, 1)
  1242. >>> x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32)
  1243. >>> input_v = Tensor(np.array([[0.5, 1.0], [1.0, 1.5]]), mindspore.float32)
  1244. >>> inplaceAdd = ops.InplaceAdd(indices)
  1245. >>> output = inplaceAdd(x, input_v)
  1246. >>> print(output)
  1247. [[1.5 3. ]
  1248. [4. 5.5]
  1249. [5. 6. ]]
  1250. """
  1251. @prim_attr_register
  1252. def __init__(self, indices):
  1253. """Initialize InplaceAdd"""
  1254. self.init_prim_io_names(inputs=['x', 'v'], outputs=['y'])
  1255. self.indices = indices
  1256. validator.check_value_type('indices', indices, [tuple, int], self.name)
  1257. if isinstance(indices, int):
  1258. self.indices = (indices,)
  1259. for item in self.indices:
  1260. validator.check_value_type("item of indices", item, [int], self.name)
  1261. def infer_dtype(self, x_dtype, v_dtype):
  1262. args = {'x': x_dtype, 'v': v_dtype}
  1263. valid_type = [mstype.int32, mstype.float16, mstype.float32]
  1264. validator.check_tensors_dtypes_same_and_valid(args, valid_type, self.name)
  1265. return x_dtype
  1266. def infer_shape(self, x_shape, v_shape):
  1267. validator.check("x", len(x_shape), "v", len(v_shape), Rel.EQ, self.name)
  1268. validator.check("size of indices", len(self.indices), "v's first dimension", v_shape[0],
  1269. Rel.EQ, self.name)
  1270. for i in self.indices:
  1271. if i < 0 or i >= x_shape[0]:
  1272. raise ValueError(f'The value of indices must be in [0, {x_shape[0]}), but got {i}.')
  1273. x_rank = len(x_shape)
  1274. for idx in range(x_rank)[1:]:
  1275. validator.check('v dim %d' % idx, v_shape[idx], "x dim %d" % idx, x_shape[idx], Rel.EQ, self.name)
  1276. return x_shape
  1277. class InplaceSub(PrimitiveWithInfer):
  1278. """
  1279. Subtracts v into specified rows of x. Computes y = x; y[i, :] -= v.
  1280. Args:
  1281. indices (Union[int, tuple]): Indices into the left-most dimension of x, and determines which rows of x
  1282. to subtract with v. It is a int or tuple, whose value is in [0, the first dimension size of x).
  1283. Inputs:
  1284. - **x** (Tensor) - The first input is a tensor whose data type is float16, float32 or int32.
  1285. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  1286. - **input_v** (Tensor) - The second input is a tensor who has the same dimension sizes as x except
  1287. the first dimension, which must be the same as indices's size. It has the same data type with `x`.
  1288. Outputs:
  1289. Tensor, has the same shape and dtype as x.
  1290. Raises:
  1291. TypeError: If `indices` is neither int nor tuple.
  1292. TypeError: If `indices` is a tuple whose elements are not all int.
  1293. ValueError: If length of shape of `x` is not equal to length of shape of `input_v`.
  1294. Supported Platforms:
  1295. ``Ascend``
  1296. Examples:
  1297. >>> indices = (0, 1)
  1298. >>> x = Tensor(np.array([[1, 2], [3, 4], [5, 6]]), mindspore.float32)
  1299. >>> input_v = Tensor(np.array([[0.5, 1.0], [1.0, 1.5]]), mindspore.float32)
  1300. >>> inplaceSub = ops.InplaceSub(indices)
  1301. >>> output = inplaceSub(x, input_v)
  1302. >>> print(output)
  1303. [[0.5 1. ]
  1304. [2. 2.5]
  1305. [5. 6. ]]
  1306. """
  1307. @prim_attr_register
  1308. def __init__(self, indices):
  1309. """Initialize InplaceSub"""
  1310. self.init_prim_io_names(inputs=['x', 'v'], outputs=['y'])
  1311. self.indices = indices
  1312. validator.check_value_type('indices', indices, [tuple, int], self.name)
  1313. if isinstance(indices, int):
  1314. self.indices = (indices,)
  1315. for item in self.indices:
  1316. validator.check_value_type("item of indices", item, [int], self.name)
  1317. def infer_dtype(self, x_dtype, v_dtype):
  1318. args = {'x': x_dtype, 'v': v_dtype}
  1319. valid_type = [mstype.int32, mstype.float16, mstype.float32]
  1320. validator.check_tensors_dtypes_same_and_valid(args, valid_type, self.name)
  1321. return x_dtype
  1322. def infer_shape(self, x_shape, v_shape):
  1323. validator.check("x", len(x_shape), "v", len(v_shape), Rel.EQ, self.name)
  1324. validator.check("size of indices", len(self.indices), "v's first dimension", v_shape[0],
  1325. Rel.EQ, self.name)
  1326. for i in self.indices:
  1327. if i < 0 or i >= x_shape[0]:
  1328. raise ValueError(f'The value of indices must be in [0, {x_shape[0]}), but got {i}.')
  1329. x_rank = len(x_shape)
  1330. for idx in range(x_rank)[1:]:
  1331. validator.check('v dim %d' % idx, v_shape[idx], "x dim %d" % idx, x_shape[idx], Rel.EQ, self.name)
  1332. return x_shape
  1333. class Sub(_MathBinaryOp):
  1334. """
  1335. Subtracts the second input tensor from the first input tensor element-wise.
  1336. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  1337. The inputs must be two tensors or one tensor and one scalar.
  1338. When the inputs are two tensors,
  1339. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1340. When the inputs are one tensor and one scalar,
  1341. the scalar could only be a constant.
  1342. .. math::
  1343. out_{i} = x_{i} - y_{i}
  1344. Inputs:
  1345. - **x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  1346. or a tensor whose data type is number or bool.
  1347. - **y** (Union[Tensor, Number, bool]) - The second input is a number, or a bool when the first input
  1348. is a tensor, or a tensor whose data type is number or bool.
  1349. Outputs:
  1350. Tensor, the shape is the same as the one after broadcasting,
  1351. and the data type is the one with higher precision or higher digits among the two inputs.
  1352. Raises:
  1353. TypeError: If `x` and `y` is not a Number or a bool or a Tensor.
  1354. Supported Platforms:
  1355. ``Ascend`` ``GPU`` ``CPU``
  1356. Examples:
  1357. >>> x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  1358. >>> y = Tensor(np.array([4, 5, 6]), mindspore.int32)
  1359. >>> sub = ops.Sub()
  1360. >>> output = sub(x, y)
  1361. >>> print(output)
  1362. [-3 -3 -3]
  1363. """
  1364. def infer_value(self, x, y):
  1365. if x is not None and y is not None:
  1366. x = x.asnumpy()
  1367. y = y.asnumpy()
  1368. out = x - y
  1369. out = np.array(out, x.dtype)
  1370. return Tensor(out)
  1371. return None
  1372. class Mul(_MathBinaryOp):
  1373. """
  1374. Multiplies two tensors element-wise.
  1375. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  1376. The inputs must be two tensors or one tensor and one scalar.
  1377. When the inputs are two tensors,
  1378. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1379. When the inputs are one tensor and one scalar,
  1380. the scalar could only be a constant.
  1381. .. math::
  1382. out_{i} = x_{i} * y_{i}
  1383. Inputs:
  1384. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  1385. a bool or a tensor whose data type is number or bool.
  1386. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  1387. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1388. Outputs:
  1389. Tensor, the shape is the same as the one after broadcasting,
  1390. and the data type is the one with higher precision or higher digits among the two inputs.
  1391. Raises:
  1392. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  1393. ValueError: If `x` and `y` are not the same shape.
  1394. Supported Platforms:
  1395. ``Ascend`` ``GPU`` ``CPU``
  1396. Examples:
  1397. >>> x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  1398. >>> y = Tensor(np.array([4.0, 5.0, 6.0]), mindspore.float32)
  1399. >>> mul = ops.Mul()
  1400. >>> output = mul(x, y)
  1401. >>> print(output)
  1402. [ 4. 10. 18.]
  1403. """
  1404. def infer_value(self, x, y):
  1405. if x is not None and y is not None:
  1406. x = x.asnumpy()
  1407. y = y.asnumpy()
  1408. out = x * y
  1409. out = np.array(out, x.dtype)
  1410. return Tensor(out)
  1411. return None
  1412. class SquaredDifference(_MathBinaryOp):
  1413. """
  1414. Subtracts the second input tensor from the first input tensor element-wise and returns square of it.
  1415. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  1416. The inputs must be two tensors or one tensor and one scalar.
  1417. When the inputs are two tensors,
  1418. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1419. When the inputs are one tensor and one scalar,
  1420. the scalar could only be a constant.
  1421. .. math::
  1422. out_{i} = (x_{i} - y_{i}) * (x_{i} - y_{i}) = (x_{i} - y_{i})^2
  1423. Inputs:
  1424. - **x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  1425. or a tensor whose data type is float16, float32, int32 or bool.
  1426. - **y** (Union[Tensor, Number, bool]) - The second input is a number, or a bool when the first input
  1427. is a tensor or a tensor whose data type is float16, float32, int32 or bool.
  1428. Outputs:
  1429. Tensor, the shape is the same as the one after broadcasting,
  1430. and the data type is the one with higher precision or higher digits among the two inputs.
  1431. Raises:
  1432. TypeError: if `x` and `y` is not a Number or a bool or a Tensor.
  1433. Supported Platforms:
  1434. ``Ascend`` ``GPU`` ``CPU``
  1435. Examples:
  1436. >>> x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  1437. >>> y = Tensor(np.array([2.0, 4.0, 6.0]), mindspore.float32)
  1438. >>> squared_difference = ops.SquaredDifference()
  1439. >>> output = squared_difference(x, y)
  1440. >>> print(output)
  1441. [1. 4. 9.]
  1442. """
  1443. def infer_dtype(self, x_dtype, y_dtype):
  1444. valid_type = [mstype.float16, mstype.float32, mstype.int32]
  1445. return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, valid_type, self.name)
  1446. class Square(PrimitiveWithCheck):
  1447. """
  1448. Returns square of a tensor element-wise.
  1449. .. math::
  1450. out_{i} = (x_{i})^2
  1451. Inputs:
  1452. - **x** (Tensor) - The input tensor whose dtype is number.
  1453. :math:`(N,*)` where :math:`*` means ,any number of additional dimensions, its rank should less than 8.
  1454. Outputs:
  1455. Tensor, has the same shape and dtype as the `x`.
  1456. Raises:
  1457. TypeError: If `x` is not a Tensor.
  1458. Supported Platforms:
  1459. ``Ascend`` ``GPU`` ``CPU``
  1460. Examples:
  1461. >>> x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  1462. >>> square = ops.Square()
  1463. >>> output = square(x)
  1464. >>> print(output)
  1465. [1. 4. 9.]
  1466. """
  1467. @prim_attr_register
  1468. def __init__(self):
  1469. """Initialize Square"""
  1470. self.init_prim_io_names(inputs=['input_x'], outputs=['output'])
  1471. def __check__(self, x):
  1472. x_dtype = x["dtype"]
  1473. validator.check_tensor_dtype_valid("x", x_dtype, mstype.number_type, self.name)
  1474. def infer_value(self, x):
  1475. """Infer the value of input for Square."""
  1476. if x is not None:
  1477. x = x.asnumpy()
  1478. out = x * x
  1479. out = np.array(out, x.dtype)
  1480. return Tensor(out)
  1481. return None
  1482. class Rsqrt(PrimitiveWithInfer):
  1483. r"""
  1484. Computes reciprocal of square root of input tensor element-wise.
  1485. .. math::
  1486. out_{i} = \frac{1}{\sqrt{x_{i}}}
  1487. Inputs:
  1488. - **x** (Tensor) - The input of Rsqrt. Each element must be a non-negative number.
  1489. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  1490. Outputs:
  1491. Tensor, has the same type and shape as `x`.
  1492. Raises:
  1493. TypeError: If dtype of `x` is neither float16 nor float32.
  1494. Supported Platforms:
  1495. ``Ascend`` ``GPU``
  1496. Examples:
  1497. >>> input_tensor = Tensor([[4, 4], [9, 9]], mindspore.float32)
  1498. >>> rsqrt = ops.Rsqrt()
  1499. >>> output = rsqrt(input_tensor)
  1500. >>> print(output)
  1501. [[0.5 0.5 ]
  1502. [0.33333334 0.33333334]]
  1503. """
  1504. @prim_attr_register
  1505. def __init__(self):
  1506. """Initialize Rsqrt"""
  1507. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  1508. def infer_shape(self, x_shape):
  1509. return x_shape
  1510. def infer_dtype(self, x_dtype):
  1511. validator.check_tensor_dtype_valid("x", x_dtype, mstype.number_type, self.name)
  1512. return x_dtype
  1513. def infer_value(self, x):
  1514. if x is not None:
  1515. x = x.asnumpy()
  1516. out = 1.0 / np.sqrt(x)
  1517. out = np.array(out, x.dtype)
  1518. return Tensor(out)
  1519. return None
  1520. class Sqrt(PrimitiveWithCheck):
  1521. r"""
  1522. Returns square root of a tensor element-wise.
  1523. .. math::
  1524. out_{i} = \sqrt{x_{i}}
  1525. Inputs:
  1526. - **x** (Tensor) - The input tensor whose dtype is number.
  1527. :math:`(N,*)` where :math:`*` means ,any number of additional dimensions, its rank should less than 8.
  1528. Outputs:
  1529. Tensor, has the same shape and data type as the `x`.
  1530. Raises:
  1531. TypeError: If `x` is not a Tensor.
  1532. Supported Platforms:
  1533. ``Ascend`` ``GPU`` ``CPU``
  1534. Examples:
  1535. >>> x = Tensor(np.array([1.0, 4.0, 9.0]), mindspore.float32)
  1536. >>> sqrt = ops.Sqrt()
  1537. >>> output = sqrt(x)
  1538. >>> print(output)
  1539. [1. 2. 3.]
  1540. """
  1541. @prim_attr_register
  1542. def __init__(self):
  1543. """Initialize Sqrt"""
  1544. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  1545. def check_dtype(self, x_type):
  1546. validator.check_tensor_dtype_valid("x", x_type, mstype.number_type, self.name)
  1547. def infer_value(self, x):
  1548. """Infer the value of input for Sqrt."""
  1549. if x is not None:
  1550. x = x.asnumpy()
  1551. out = np.sqrt(x)
  1552. out = np.array(out, x.dtype)
  1553. return Tensor(out)
  1554. return None
  1555. class Reciprocal(PrimitiveWithInfer):
  1556. r"""
  1557. Returns reciprocal of a tensor element-wise.
  1558. .. math::
  1559. out_{i} = \frac{1}{x_{i}}
  1560. Inputs:
  1561. - **x** (Tensor) - The input tensor.
  1562. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  1563. Outputs:
  1564. Tensor, has the same shape as the `x`.
  1565. Raises:
  1566. TypeError: If `x` is not a Tensor.
  1567. Supported Platforms:
  1568. ``Ascend`` ``GPU`` ``CPU``
  1569. Examples:
  1570. >>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1571. >>> reciprocal = ops.Reciprocal()
  1572. >>> output = reciprocal(x)
  1573. >>> print(output)
  1574. [1. 0.5 0.25]
  1575. """
  1576. @prim_attr_register
  1577. def __init__(self):
  1578. """Initialize Reciprocal"""
  1579. if context.get_context("device_target") == "GPU":
  1580. self.target = "GPU"
  1581. else:
  1582. self.target = "OTHER"
  1583. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1584. def infer_shape(self, x):
  1585. return x
  1586. def infer_dtype(self, x):
  1587. validator.check_subclass("x", x, mstype.tensor, self.name)
  1588. return x
  1589. def infer_value(self, x):
  1590. if x is not None:
  1591. x = x.asnumpy()
  1592. out = 1.0 / x
  1593. out = np.array(out, x.dtype)
  1594. return Tensor(out)
  1595. return None
  1596. class Pow(_MathBinaryOp):
  1597. """
  1598. Computes a tensor to the power of the second input.
  1599. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  1600. The inputs must be two tensors or one tensor and one scalar.
  1601. When the inputs are two tensors,
  1602. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1603. When the inputs are one tensor and one scalar,
  1604. the scalar could only be a constant.
  1605. .. math::
  1606. out_{i} = x_{i} ^{ y_{i}}
  1607. Inputs:
  1608. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  1609. a bool or a tensor whose data type is number or bool.
  1610. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  1611. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1612. Outputs:
  1613. Tensor, the shape is the same as the one after broadcasting,
  1614. and the data type is the one with higher precision or higher digits among the two inputs.
  1615. Raises:
  1616. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  1617. ValueError: If `x` and `y` are not the same shape.
  1618. Supported Platforms:
  1619. ``Ascend`` ``GPU`` ``CPU``
  1620. Examples:
  1621. >>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1622. >>> y = 3.0
  1623. >>> pow = ops.Pow()
  1624. >>> output = pow(x, y)
  1625. >>> print(output)
  1626. [ 1. 8. 64.]
  1627. >>>
  1628. >>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1629. >>> y = Tensor(np.array([2.0, 4.0, 3.0]), mindspore.float32)
  1630. >>> pow = ops.Pow()
  1631. >>> output = pow(x, y)
  1632. >>> print(output)
  1633. [ 1. 16. 64.]
  1634. """
  1635. def infer_value(self, x, power):
  1636. if x is not None and power is not None:
  1637. x = x.asnumpy()
  1638. power = power.asnumpy()
  1639. out = np.power(x, power)
  1640. out = np.array(out, x.dtype)
  1641. return Tensor(out)
  1642. return None
  1643. class Exp(PrimitiveWithInfer):
  1644. r"""
  1645. Returns exponential of a tensor element-wise.
  1646. .. math::
  1647. out_i = e^{x_i}
  1648. Inputs:
  1649. - **x** (Tensor) - The input tensor.
  1650. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  1651. Outputs:
  1652. Tensor, has the same shape and dtype as the `x`.
  1653. Raises:
  1654. TypeError: If `x` is not a Tensor.
  1655. Supported Platforms:
  1656. ``Ascend`` ``GPU`` ``CPU``
  1657. Examples:
  1658. >>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1659. >>> exp = ops.Exp()
  1660. >>> output = exp(x)
  1661. >>> print(output)
  1662. [ 2.718282 7.389056 54.598152]
  1663. """
  1664. @prim_attr_register
  1665. def __init__(self):
  1666. """Initialize Exp"""
  1667. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1668. def infer_shape(self, x_shape):
  1669. return x_shape
  1670. def infer_dtype(self, x_type):
  1671. validator.check_subclass("x", x_type, mstype.tensor, self.name)
  1672. return x_type
  1673. def infer_value(self, x):
  1674. if x is not None:
  1675. x = x.asnumpy()
  1676. out = np.exp(x)
  1677. out = np.array(out, x.dtype)
  1678. return Tensor(out)
  1679. return None
  1680. class Expm1(PrimitiveWithInfer):
  1681. r"""
  1682. Returns exponential then minus 1 of a tensor element-wise.
  1683. .. math::
  1684. out_i = e^{x_i} - 1
  1685. Inputs:
  1686. - **x** (Tensor) - The input tensor. With float16 or float32 data type.
  1687. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  1688. Outputs:
  1689. Tensor, has the same shape as the `x`.
  1690. Raises:
  1691. TypeError: If dtype of `x` is neither float16 nor float32.
  1692. Supported Platforms:
  1693. ``Ascend`` ``GPU`` ``CPU``
  1694. Examples:
  1695. >>> x = Tensor(np.array([0.0, 1.0, 2.0, 4.0]), mindspore.float32)
  1696. >>> expm1 = ops.Expm1()
  1697. >>> output = expm1(x)
  1698. >>> print(output)
  1699. [ 0. 1.718282 6.389056 53.598152]
  1700. """
  1701. @prim_attr_register
  1702. def __init__(self):
  1703. """Initialize Expm1."""
  1704. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1705. def infer_shape(self, x_shape):
  1706. return x_shape
  1707. def infer_dtype(self, x_type):
  1708. validator.check_tensor_dtype_valid("x", x_type, [mstype.float16, mstype.float32], self.name)
  1709. return x_type
  1710. class HistogramFixedWidth(PrimitiveWithInfer):
  1711. """
  1712. Returns a rank 1 histogram counting the number of entries in values that fall into every bin. The bins are equal
  1713. width and determined by the arguments range and nbins.
  1714. Args:
  1715. dtype (str): An optional attribute. Must be one of the following types: "int32", "int64". Default: "int32".
  1716. nbins (int): The number of histogram bins, the type is a positive integer.
  1717. Inputs:
  1718. - **x** (Tensor) - Numeric Tensor. Must be one of the following types: int32, float32, float16.
  1719. - **range** (Tensor) - Must has the same data type as `x`, and the shape is [2].
  1720. x <= range[0] will be mapped to hist[0], x >= range[1] will be mapped to hist[-1].
  1721. Outputs:
  1722. Tensor, the type is int32.
  1723. Raises:
  1724. TypeError: If `dtype` is not a str or `nbins` is not an int.
  1725. ValueError: If `nbins` is less than 1.
  1726. ValueError: If `dtype` is neither 'int32' nor 'int64'.
  1727. Supported Platforms:
  1728. ``Ascend``
  1729. Examples:
  1730. >>> x = Tensor([-1.0, 0.0, 1.5, 2.0, 5.0, 15], mindspore.float16)
  1731. >>> range_op = Tensor([0.0, 5.0], mindspore.float16)
  1732. >>> hist = ops.HistogramFixedWidth(5)
  1733. >>> output = hist(x, range_op)
  1734. >>> print(output)
  1735. [2 1 1 0 2]
  1736. """
  1737. @prim_attr_register
  1738. def __init__(self, nbins, dtype='int32'):
  1739. """Initialize HistogramFixedWidth."""
  1740. self.nbins = validator.check_value_type("nbins", nbins, [int], self.name)
  1741. validator.check_int(nbins, 1, Rel.GE, "nbins", self.name)
  1742. valid_values = ['int32', 'int64']
  1743. self.dtype = validator.check_string(dtype, valid_values, "dtype", self.name)
  1744. self.init_prim_io_names(inputs=['x', 'range'], outputs=['y'])
  1745. def infer_shape(self, x_shape, range_shape):
  1746. return (self.nbins,)
  1747. def infer_dtype(self, x_dtype, range_dtype):
  1748. valid_dtypes = (mstype.float16, mstype.float32, mstype.int32)
  1749. validator.check_tensor_dtype_valid("x", x_dtype, valid_dtypes, self.name)
  1750. validator.check_tensor_dtype_valid("range", range_dtype, valid_dtypes, self.name)
  1751. y_dtype = mstype.int32
  1752. return y_dtype
  1753. class Log(PrimitiveWithInfer):
  1754. """
  1755. Returns the natural logarithm of a tensor element-wise.
  1756. .. math::
  1757. y_i = log_e(x_i)
  1758. .. warning::
  1759. If the input value of operator Log is within the range (0, 0.01] or [0.95, 1.05], the output accuracy
  1760. is subject to change.
  1761. Inputs:
  1762. - **x** (Tensor) - The input tensor. The value must be greater than 0.
  1763. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  1764. Outputs:
  1765. Tensor, has the same shape as the `x`.
  1766. Raises:
  1767. TypeError: If `x` is not a Tensor.
  1768. Supported Platforms:
  1769. ``Ascend`` ``GPU`` ``CPU``
  1770. Examples:
  1771. >>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1772. >>> log = ops.Log()
  1773. >>> output = log(x)
  1774. >>> print(output)
  1775. [0. 0.6931472 1.3862944]
  1776. """
  1777. @prim_attr_register
  1778. def __init__(self):
  1779. """Initialize Log."""
  1780. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1781. def infer_shape(self, x):
  1782. return x
  1783. def infer_dtype(self, x):
  1784. validator.check_subclass("x", x, mstype.tensor, self.name)
  1785. return x
  1786. def infer_value(self, x):
  1787. if x is not None:
  1788. x = x.asnumpy()
  1789. out = np.log(x)
  1790. out = np.array(out, x.dtype)
  1791. return Tensor(out)
  1792. return None
  1793. class Log1p(Primitive):
  1794. """
  1795. Returns the natural logarithm of one plus the input tensor element-wise.
  1796. Inputs:
  1797. - **x** (Tensor) - The input tensor. With float16 or float32 data type.
  1798. The value must be greater than -1.
  1799. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  1800. Outputs:
  1801. Tensor, has the same shape as the `x`.
  1802. Raises:
  1803. TypeError: If dtype of `x` is neither float16 nor float32.
  1804. Supported Platforms:
  1805. ``Ascend`` ``GPU``
  1806. Examples:
  1807. >>> x = Tensor(np.array([1.0, 2.0, 4.0]), mindspore.float32)
  1808. >>> log1p = ops.Log1p()
  1809. >>> output = log1p(x)
  1810. >>> print(output)
  1811. [0.6931472 1.0986123 1.609438 ]
  1812. """
  1813. @prim_attr_register
  1814. def __init__(self):
  1815. """Initialize Log1p."""
  1816. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1817. class Erf(PrimitiveWithInfer):
  1818. r"""
  1819. Computes the Gauss error function of `x` element-wise.
  1820. .. math::
  1821. erf(x)=\frac{2} {\sqrt{\pi}} \int\limits_0^{x} e^{-t^{2}} dt
  1822. Inputs:
  1823. - **x** (Tensor) - The input tensor. The data type must be float16 or float32.
  1824. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  1825. Outputs:
  1826. Tensor, has the same shape and dtype as the `x`.
  1827. Raises:
  1828. TypeError: If dtype of `x` is neither float16 nor float32.
  1829. Supported Platforms:
  1830. ``Ascend`` ``GPU``
  1831. Examples:
  1832. >>> x = Tensor(np.array([-1, 0, 1, 2, 3]), mindspore.float32)
  1833. >>> erf = ops.Erf()
  1834. >>> output = erf(x)
  1835. >>> print(output)
  1836. [-0.8427168 0. 0.8427168 0.99530876 0.99997765]
  1837. """
  1838. @prim_attr_register
  1839. def __init__(self):
  1840. """Initialize Erf"""
  1841. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1842. def infer_shape(self, x_shape):
  1843. return x_shape
  1844. def infer_dtype(self, x_dtype):
  1845. validator.check_tensor_dtype_valid("x", x_dtype, [mstype.float16, mstype.float32], self.name)
  1846. return x_dtype
  1847. class Erfc(PrimitiveWithInfer):
  1848. r"""
  1849. Computes the complementary error function of `x` element-wise.
  1850. .. math::
  1851. erfc(x) = 1 - \frac{2} {\sqrt{\pi}} \int\limits_0^{x} e^{-t^{2}} dt
  1852. Inputs:
  1853. - **x** (Tensor) - The input tensor. The data type must be float16 or float32.
  1854. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  1855. Outputs:
  1856. Tensor, has the same shap dtype as the `x`.
  1857. Raises:
  1858. TypeError: If dtype of `x` is neither float16 nor float32.
  1859. Supported Platforms:
  1860. ``Ascend`` ``GPU``
  1861. Examples:
  1862. >>> x = Tensor(np.array([-1, 0, 1, 2, 3]), mindspore.float32)
  1863. >>> erfc = ops.Erfc()
  1864. >>> output = erfc(x)
  1865. >>> print(output)
  1866. [1.8427168e+00 1.0000000e+00 1.5728319e-01 4.6912432e-03 2.2351742e-05]
  1867. """
  1868. @prim_attr_register
  1869. def __init__(self):
  1870. """Initialize Erfc"""
  1871. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  1872. def infer_shape(self, x_shape):
  1873. return x_shape
  1874. def infer_dtype(self, x_type):
  1875. validator.check_tensor_dtype_valid("x", x_type, [mstype.float16, mstype.float32], self.name)
  1876. return x_type
  1877. class Minimum(_MathBinaryOp):
  1878. """
  1879. Computes the minimum of input tensors element-wise.
  1880. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  1881. The inputs must be two tensors or one tensor and one scalar.
  1882. When the inputs are two tensors,
  1883. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1884. When the inputs are one tensor and one scalar,
  1885. the scalar could only be a constant.
  1886. Inputs:
  1887. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  1888. a bool or a tensor whose data type is number or bool.
  1889. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  1890. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1891. Outputs:
  1892. Tensor, the shape is the same as the one after broadcasting,
  1893. and the data type is the one with higher precision or higher digits among the two inputs.
  1894. Raises:
  1895. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  1896. ValueError: If `x` and `y` are not the same shape.
  1897. Supported Platforms:
  1898. ``Ascend`` ``GPU`` ``CPU``
  1899. Examples:
  1900. >>> # case 1 : same data type
  1901. >>> x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.float32)
  1902. >>> y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
  1903. >>> minimum = ops.Minimum
  1904. >>> output = minimum(x, y)
  1905. >>> print(output)
  1906. [1. 2. 3.]
  1907. >>> # case 2 : different data type
  1908. >>> x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.int32)
  1909. >>> y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
  1910. >>> output = minimum(x, y)
  1911. >>> print(output.dtype)
  1912. Float32
  1913. """
  1914. def infer_value(self, x, y):
  1915. if x is not None and y is not None:
  1916. x = x.asnumpy()
  1917. y = y.asnumpy()
  1918. out = np.minimum(x, y)
  1919. out = np.array(out, x.dtype)
  1920. return Tensor(out)
  1921. return None
  1922. class Maximum(_MathBinaryOp):
  1923. """
  1924. Computes the maximum of input tensors element-wise.
  1925. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  1926. The inputs must be two tensors or one tensor and one scalar.
  1927. When the inputs are two tensors,
  1928. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1929. When the inputs are one tensor and one scalar,
  1930. the scalar could only be a constant.
  1931. Inputs:
  1932. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  1933. a bool or a tensor whose data type is number or bool.
  1934. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  1935. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1936. Outputs:
  1937. Tensor, the shape is the same as the one after broadcasting,
  1938. and the data type is the one with higher precision or higher digits among the two inputs.
  1939. Raises:
  1940. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  1941. ValueError: If `x` and `y` are not the same shape.
  1942. Supported Platforms:
  1943. ``Ascend`` ``GPU`` ``CPU``
  1944. Examples:
  1945. >>> # case 1 : same data type
  1946. >>> x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.float32)
  1947. >>> y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
  1948. >>> maximum = ops.Maximum()
  1949. >>> output = maximum(x, y)
  1950. >>> print(output)
  1951. [4. 5. 6.]
  1952. >>> # case 2 : different data type
  1953. >>> x = Tensor(np.array([1.0, 5.0, 3.0]), mindspore.int32)
  1954. >>> y = Tensor(np.array([4.0, 2.0, 6.0]), mindspore.float32)
  1955. >>> output = maximum(x, y)
  1956. >>> print(output.dtype)
  1957. Float32
  1958. """
  1959. def infer_value(self, x, y):
  1960. if x is not None and y is not None:
  1961. x = x.asnumpy()
  1962. y = y.asnumpy()
  1963. out = np.maximum(x, y)
  1964. out = np.array(out, x.dtype)
  1965. return Tensor(out)
  1966. return None
  1967. class RealDiv(_MathBinaryOp):
  1968. """
  1969. Divides the first input tensor by the second input tensor in floating-point type element-wise.
  1970. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  1971. The inputs must be two tensors or one tensor and one scalar.
  1972. When the inputs are two tensors,
  1973. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  1974. When the inputs are one tensor and one scalar,
  1975. the scalar could only be a constant.
  1976. .. math::
  1977. out_{i} = x_{i} / y_{i}
  1978. Inputs:
  1979. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  1980. a bool or a tensor whose data type is number or bool.
  1981. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  1982. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  1983. Outputs:
  1984. Tensor, the shape is the same as the one after broadcasting,
  1985. and the data type is the one with higher precision or higher digits among the two inputs.
  1986. Raises:
  1987. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  1988. ValueError: If `x` and `y` are not the same shape.
  1989. Supported Platforms:
  1990. ``Ascend`` ``GPU`` ``CPU``
  1991. Examples:
  1992. >>> x = Tensor(np.array([1.0, 2.0, 3.0]), mindspore.float32)
  1993. >>> y = Tensor(np.array([4.0, 5.0, 6.0]), mindspore.float32)
  1994. >>> realdiv = ops.RealDiv()
  1995. >>> output = realdiv(x, y)
  1996. >>> print(output)
  1997. [0.25 0.4 0.5 ]
  1998. """
  1999. def infer_value(self, x, y):
  2000. if x is not None and y is not None:
  2001. x = x.asnumpy()
  2002. y = y.asnumpy()
  2003. out = x / y
  2004. out = np.array(out, x.dtype)
  2005. return Tensor(out)
  2006. return None
  2007. class Div(_MathBinaryOp):
  2008. r"""
  2009. Computes the quotient of dividing the first input tensor by the second input tensor element-wise.
  2010. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2011. The inputs must be two tensors or one tensor and one scalar.
  2012. When the inputs are two tensors,
  2013. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  2014. When the inputs are one tensor and one scalar,
  2015. the scalar could only be a constant.
  2016. .. math::
  2017. out_{i} = \frac{x_i}{y_i}
  2018. Inputs:
  2019. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  2020. a bool or a tensor whose data type is number or bool.
  2021. - **y** (Union[Tensor, Number, bool]) - When the first input is a tensor, The second input
  2022. could be a number, a bool, or a tensor whose data type is number or bool. When the first input
  2023. is a number or a bool, the second input must be a tensor whose data type is number or bool.
  2024. Outputs:
  2025. Tensor, the shape is the same as the one after broadcasting,
  2026. and the data type is the one with higher precision or higher digits among the two inputs.
  2027. Raises:
  2028. TypeError: If neither `x` nor `y` is a Tensor.
  2029. Supported Platforms:
  2030. ``Ascend`` ``GPU`` ``CPU``
  2031. Examples:
  2032. >>> # case 1 :has same data type and shape of the two inputs
  2033. >>> x = Tensor(np.array([-4.0, 5.0, 6.0]), mindspore.float32)
  2034. >>> y = Tensor(np.array([3.0, 2.0, 3.0]), mindspore.float32)
  2035. >>> div = ops.Div()
  2036. >>> output = div(x, y)
  2037. >>> print(output)
  2038. [-1.3333334 2.5 2. ]
  2039. >>> # case 2 : different data type and shape of the two inputs
  2040. >>> x = Tensor(np.array([-4.0, 5.0, 6.0]), mindspore.int32)
  2041. >>> y = Tensor(2, mindspore.float32)
  2042. >>> output = div(x, y)
  2043. >>> print(output)
  2044. [-2. 2.5 3.]
  2045. >>> print(output.dtype)
  2046. Flaot32
  2047. """
  2048. def infer_value(self, x, y):
  2049. if x is not None and y is not None:
  2050. x = x.asnumpy()
  2051. y = y.asnumpy()
  2052. out = np.array(x / y, x.dtype)
  2053. return Tensor(out)
  2054. return None
  2055. class DivNoNan(_MathBinaryOp):
  2056. """
  2057. Computes a safe divide and returns 0 if the y is zero.
  2058. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2059. The inputs must be two tensors or one tensor and one scalar.
  2060. When the inputs are two tensors,
  2061. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  2062. When the inputs are one tensor and one scalar,
  2063. the scalar could only be a constant.
  2064. Inputs:
  2065. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  2066. a bool or a tensor whose data type is number or bool.
  2067. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  2068. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  2069. Outputs:
  2070. Tensor, the shape is the same as the one after broadcasting,
  2071. and the data type is the one with higher precision or higher digits among the two inputs.
  2072. Raises:
  2073. TypeError: If neither `x` nor `y` is a Tensor.
  2074. Supported Platforms:
  2075. ``Ascend`` ``GPU``
  2076. Examples:
  2077. >>> x = Tensor(np.array([-1.0, 0., 1.0, 5.0, 6.0]), mindspore.float32)
  2078. >>> y = Tensor(np.array([0., 0., 0., 2.0, 3.0]), mindspore.float32)
  2079. >>> div_no_nan = ops.DivNoNan()
  2080. >>> output = div_no_nan(x, y)
  2081. >>> print(output)
  2082. [0. 0. 0. 2.5 2. ]
  2083. """
  2084. @prim_attr_register
  2085. def __init__(self):
  2086. """Initialize _BinaryOp"""
  2087. self.init_prim_io_names(inputs=['x', 'y'], outputs=['output'])
  2088. def infer_value(self, x, y):
  2089. if x is not None and y is not None:
  2090. x = x.asnumpy()
  2091. y = y.asnumpy()
  2092. with np.errstate(divide='ignore', invalid='ignore'):
  2093. out = np.true_divide(x, y)
  2094. out[~np.isfinite(out)] = 0
  2095. return out
  2096. return None
  2097. class MulNoNan(_MathBinaryOp):
  2098. r"""
  2099. Computes `x` * `y` element-wise. If `y` is zero, no matter what `x` is, it will return 0, and also
  2100. If `x` is zero, no matter what `y` is, it will return 0.
  2101. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2102. The inputs must be two tensors or one tensor and one scalar.
  2103. When the inputs are two tensors, the shapes of them could be broadcasted.
  2104. When the inputs are one tensor and one scalar, the scalar could only be a constant.
  2105. Note:
  2106. The shapes of `x` and `y` should be the same or can be broadcasted.
  2107. Inputs:
  2108. - **x** (Union[Tensor]) - The first input is a tensor whose data type is one of
  2109. flota16, float32, int32, int64 currently or scalar.
  2110. - **y** (Union[Tensor]) - The second input is a tensor whose data type is one of
  2111. flota16, float32, int32, int64 currently or scalar.
  2112. Outputs:
  2113. Tensor, the shape is the same as the shape after broadcasting,
  2114. and the data type is the one with higher precision among the two inputs.
  2115. Supported Platforms:
  2116. ``Ascend``
  2117. Raises:
  2118. TypeError: If neither `x` nor `y` is a bool Tensor.
  2119. Examples:
  2120. >>> # case 1 : same data type and shape of two inputs, there are some 0 in y.
  2121. >>> x = Tensor(np.array([[-1.0, 6.0, np.inf], [np.nan, -7.0, 4.0]]), mindspore.float32)
  2122. >>> y = Tensor(np.array([[-1.0, 4.0, 0], [0, -3.0, 1.0]]), mindspore.float32)
  2123. >>> mul_no_nan = ops.MulNoNan()
  2124. >>> output = mul_no_nan(x, y)
  2125. >>> print(output)
  2126. [[ 1. 24. 0.]
  2127. [ 0. 21. 4.]]
  2128. >>> # case 2 : the shape of two inputs is same, there are some 0 in x, y.
  2129. >>> x = Tensor(np.array([[-1.0, 6.0, 0], [0, np.nan, 4.0]]), mindspore.int32)
  2130. >>> y = Tensor(np.array([[-1.0, 4.0, np.inf], [np.nan, 0, 1.0]]), mindspore.float32)
  2131. >>> output = mul_no_nan(x, y)
  2132. >>> print(output)
  2133. [[ 1. 24. 0.]
  2134. [ 0. 0. 4.]]
  2135. >>> print(output.dtype)
  2136. Float32
  2137. >>> # case 3 : the y is a scalar.
  2138. >>> x = Tensor(np.array([[-1.0, 6.0, 0], [0, np.nan, 4.0]]), mindspore.float32)
  2139. >>> y = Tensor(0, mindspore.float32)
  2140. >>> output = mul_no_nan(x, y)
  2141. >>> print(output)
  2142. [[ 0. 0. 0.]
  2143. [ 0. 0. 0.]]
  2144. """
  2145. @prim_attr_register
  2146. def __init__(self):
  2147. """Initialize _BinaryOp"""
  2148. self.init_prim_io_names(inputs=['x', 'y'], outputs=['output'])
  2149. def infer_value(self, x, y):
  2150. if x is not None and y is not None:
  2151. x = x.asnumpy()
  2152. y = y.asnumpy()
  2153. with np.errstate(divide='ignore', invalid='ignore'):
  2154. out = np.multiply(x, y)
  2155. out[y == 0] = 0
  2156. return out
  2157. return None
  2158. class FloorDiv(_MathBinaryOp):
  2159. """
  2160. Divides the first input tensor by the second input tensor element-wise and round down to the closest integer.
  2161. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2162. The inputs must be two tensors or one tensor and one scalar.
  2163. When the inputs are two tensors,
  2164. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  2165. When the inputs are one tensor and one scalar,
  2166. the scalar could only be a constant.
  2167. .. math::
  2168. out_{i} = \\text{floor}( \\frac{x_i}{y_i})
  2169. where the :math:`floor` indicates the Floor operator, for more details, please refer to the Floor operator.
  2170. Inputs:
  2171. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  2172. a bool or a tensor whose data type is number or bool.
  2173. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  2174. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  2175. Outputs:
  2176. Tensor, the shape is the same as the one after broadcasting,
  2177. and the data type is the one with higher precision or higher digits among the two inputs.
  2178. Raises:
  2179. TypeError: If neither `x` nor `y` is a Tensor.
  2180. Supported Platforms:
  2181. ``Ascend`` ``GPU`` ``CPU``
  2182. Examples:
  2183. >>> x = Tensor(np.array([2, 4, -1]), mindspore.int32)
  2184. >>> y = Tensor(np.array([3, 3, 3]), mindspore.int32)
  2185. >>> floor_div = ops.FloorDiv()
  2186. >>> output = floor_div(x, y)
  2187. >>> print(output)
  2188. [ 0 1 -1]
  2189. """
  2190. class TruncateDiv(_MathBinaryOp):
  2191. """
  2192. Divides the first input tensor by the second input tensor element-wise for integer types, negative numbers will
  2193. round fractional quantities towards zero.
  2194. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2195. The inputs must be two tensors or one tensor and one scalar.
  2196. When the inputs are two tensors,
  2197. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  2198. When the inputs are one tensor and one scalar,
  2199. the scalar could only be a constant.
  2200. Note:
  2201. Broadcasting is supported.
  2202. Inputs:
  2203. - **x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  2204. or a tensor whose data type is number or bool.
  2205. - **y** (Union[Tensor, Number, bool]) - The second input is a number, or a bool when the first input
  2206. is a tensor, or a tensor whose data type is number or bool.
  2207. Outputs:
  2208. Tensor, the shape is the same as the one after broadcasting,
  2209. and the data type is the one with higher precision or higher digits among the two inputs.
  2210. Raises:
  2211. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  2212. Supported Platforms:
  2213. ``Ascend``
  2214. Examples:
  2215. >>> x = Tensor(np.array([2, 4, -1]), mindspore.int32)
  2216. >>> y = Tensor(np.array([3, 3, 3]), mindspore.int32)
  2217. >>> truncate_div = ops.TruncateDiv()
  2218. >>> output = truncate_div(x, y)
  2219. >>> print(output)
  2220. [0 1 0]
  2221. """
  2222. class TruncateMod(_MathBinaryOp):
  2223. r"""
  2224. Returns the remainder of division element-wise.
  2225. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2226. The inputs must be two tensors or one tensor and one scalar.
  2227. When the inputs are two tensors,
  2228. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  2229. When the inputs are one tensor and one scalar,
  2230. the scalar could only be a constant.
  2231. .. warning::
  2232. - The input data does not support 0.
  2233. - When NUM exceeds 2048 , the accuracy of operator cannot guarantee the requirement of
  2234. double thousandths in the mini form.
  2235. - Due to different architectures, the calculation results of this operator on NPU and CPU may be inconsistent.
  2236. - If shape is expressed as (D1,D2... ,Dn), then D1\*D2... \*DN<=1000000,n<=8.
  2237. Inputs:
  2238. - **x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  2239. or a tensor whose data type is number or bool.
  2240. - **y** (Union[Tensor, Number, bool]) - The second input is a number, or a bool when the first input
  2241. is a tensor, or a tensor whose data type is number or bool.
  2242. Outputs:
  2243. Tensor, the shape is the same as the one after broadcasting,
  2244. and the data type is the one with higher precision or higher digits among the two inputs.
  2245. Raises:
  2246. TypeError: If neither `x` nor `y` is one of the following: Tensor, Number, bool.
  2247. Supported Platforms:
  2248. ``Ascend``
  2249. Examples:
  2250. >>> x = Tensor(np.array([2, 4, -1]), mindspore.int32)
  2251. >>> y = Tensor(np.array([3, 3, 3]), mindspore.int32)
  2252. >>> truncate_mod = ops.TruncateMod()
  2253. >>> output = truncate_mod(x, y)
  2254. >>> print(output)
  2255. [ 2 1 -1]
  2256. """
  2257. class Mod(_MathBinaryOp):
  2258. r"""
  2259. Computes the remainder of dividing the first input tensor by the second input tensor element-wise.
  2260. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2261. The inputs must be two tensors or one tensor and one scalar. When the inputs are two tensors,
  2262. both dtypes cannot be bool, and the shapes of them could be broadcast. When the inputs are one tensor
  2263. and one scalar, the scalar could only be a constant.
  2264. .. math::
  2265. out_{i} = x_{i} // y_{i}
  2266. .. warning::
  2267. - The input data does not support 0.
  2268. - When NUM exceeds 2048 , the accuracy of operator cannot guarantee the requirement of
  2269. double thousandths in the mini form.
  2270. - Due to different architectures, the calculation results of this operator on NPU and CPU may be inconsistent.
  2271. - If shape is expressed as (D1,D2... ,Dn), then D1\*D2... \*DN<=1000000,n<=8.
  2272. Inputs:
  2273. - **x** (Union[Tensor, Number]) - The first input is a number or a tensor whose data type is number.
  2274. - **y** (Union[Tensor, Number]) - When the first input is a tensor, The second input
  2275. could be a number or a tensor whose data type is number. When the first input is a number,
  2276. the second input must be a tensor whose data type is number.
  2277. Outputs:
  2278. Tensor, the shape is the same as the one after broadcasting,
  2279. and the data type is the one with higher precision or higher digits among the two inputs.
  2280. Raises:
  2281. ValueError: When `x` and `y` are not the same dtype.
  2282. Supported Platforms:
  2283. ``Ascend`` ``GPU`` ``CPU``
  2284. Examples:
  2285. >>> x = Tensor(np.array([-4.0, 5.0, 6.0]), mindspore.float32)
  2286. >>> y = Tensor(np.array([3.0, 2.0, 3.0]), mindspore.float32)
  2287. >>> mod = ops.Mod()
  2288. >>> output = mod(x, y)
  2289. >>> print(output)
  2290. [-1. 1. 0.]
  2291. """
  2292. def infer_value(self, x, y):
  2293. if x is not None and y is not None:
  2294. x = x.asnumpy()
  2295. y = y.asnumpy()
  2296. return Tensor(np.fmod(x, y))
  2297. return None
  2298. class Floor(PrimitiveWithInfer):
  2299. r"""
  2300. Rounds a tensor down to the closest integer element-wise.
  2301. .. math::
  2302. out_i = \lfloor x_i \rfloor
  2303. Inputs:
  2304. - **x** (Tensor) - The input tensor. Its element data type must be float.
  2305. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  2306. Outputs:
  2307. Tensor, has the same shape as `x`.
  2308. Raises:
  2309. TypeError: If dtype of `x` is not float.
  2310. Supported Platforms:
  2311. ``Ascend`` ``GPU`` ``CPU``
  2312. Examples:
  2313. >>> x = Tensor(np.array([1.1, 2.5, -1.5]), mindspore.float32)
  2314. >>> floor = ops.Floor()
  2315. >>> output = floor(x)
  2316. >>> print(output)
  2317. [ 1. 2. -2.]
  2318. """
  2319. @prim_attr_register
  2320. def __init__(self):
  2321. """Initialize Floor."""
  2322. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  2323. def infer_shape(self, x_shape):
  2324. return x_shape
  2325. def infer_dtype(self, x_dtype):
  2326. validator.check_tensor_dtype_valid("x", x_dtype, mstype.float_type, self.name)
  2327. return x_dtype
  2328. class FloorMod(_MathBinaryOp):
  2329. r"""
  2330. Computes the remainder of division element-wise. It's a flooring divide.
  2331. E.g. :math:`floor(x / y) * y + mod(x, y) = x`.
  2332. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2333. The inputs must be two tensors or one tensor and one scalar.
  2334. When the inputs are two tensors,
  2335. dtypes of them cannot be both bool , and the shapes of them could be broadcast.
  2336. When the inputs are one tensor and one scalar,
  2337. the scalar could only be a constant.
  2338. .. math::
  2339. out_{i} =\text{floor}(x_{i} // y_{i})
  2340. where the :math:`floor` indicates the Floor operator, for more details, please refer to the Floor operator.
  2341. .. warning::
  2342. - The input data does not support 0.
  2343. - When NUM exceeds 2048 , the accuracy of operator cannot guarantee the requirement of
  2344. double thousandths in the mini form.
  2345. - Due to different architectures, the calculation results of this operator on NPU and CPU may be inconsistent.
  2346. - If shape is expressed as (D1,D2... ,Dn), then D1\*D2... \*DN<=1000000,n<=8.
  2347. Inputs:
  2348. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  2349. a bool or a tensor whose data type is number or bool.
  2350. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  2351. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  2352. Outputs:
  2353. Tensor, the shape is the same as the one after broadcasting,
  2354. and the data type is the one with higher precision or higher digits among the two inputs.
  2355. Raises:
  2356. TypeError: If neither `x` nor `y` is a Tensor.
  2357. Supported Platforms:
  2358. ``Ascend`` ``GPU`` ``CPU``
  2359. Examples:
  2360. >>> x = Tensor(np.array([2, 4, -1]), mindspore.int32)
  2361. >>> y = Tensor(np.array([3, 3, 3]), mindspore.int32)
  2362. >>> floor_mod = ops.FloorMod()
  2363. >>> output = floor_mod(x, y)
  2364. >>> print(output)
  2365. [2 1 2]
  2366. """
  2367. class Ceil(PrimitiveWithInfer):
  2368. r"""
  2369. Rounds a tensor up to the closest integer element-wise.
  2370. .. math::
  2371. out_i = \lceil x_i \rceil = \lfloor x_i \rfloor + 1
  2372. Inputs:
  2373. - **x** (Tensor) - The input tensor. It's element data type must be float16 or float32.
  2374. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  2375. Outputs:
  2376. Tensor, has the same shape as `x`.
  2377. Raises:
  2378. TypeError: If dtype of `x` is neither float16 nor float32.
  2379. Supported Platforms:
  2380. ``Ascend``
  2381. Examples:
  2382. >>> x = Tensor(np.array([1.1, 2.5, -1.5]), mindspore.float32)
  2383. >>> ceil_op = ops.Ceil()
  2384. >>> output = ceil_op(x)
  2385. >>> print(output)
  2386. [ 2. 3. -1.]
  2387. """
  2388. @prim_attr_register
  2389. def __init__(self):
  2390. """Initialize Ceil."""
  2391. self.init_prim_io_names(inputs=['x'], outputs=['y'])
  2392. def infer_shape(self, x_shape):
  2393. return x_shape
  2394. def infer_dtype(self, x_dtype):
  2395. validator.check_tensor_dtype_valid("x", x_dtype, [mstype.float16, mstype.float32], self.name)
  2396. return x_dtype
  2397. class Xdivy(_MathBinaryOp):
  2398. """
  2399. Divides the first input tensor by the second input tensor element-wise. Returns zero when `x` is zero.
  2400. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2401. The inputs must be two tensors or one tensor and one scalar.
  2402. When the inputs are two tensors,
  2403. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  2404. When the inputs are one tensor and one scalar,
  2405. the scalar could only be a constant.
  2406. Inputs:
  2407. - **x** (Union[Tensor, Number, bool]) - The first input is a number, or a bool,
  2408. or a tensor whose data type is float16, float32 or bool.
  2409. - **y** (Union[Tensor, Number, bool]) - The second input is a number,
  2410. or a bool when the first input is a tensor, or a tensor whose data type is float16, float32 or bool.
  2411. Outputs:
  2412. Tensor, the shape is the same as the one after broadcasting,
  2413. and the data type is the one with higher precision or higher digits among the two inputs.
  2414. Raises:
  2415. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  2416. Supported Platforms:
  2417. ``Ascend``
  2418. Examples:
  2419. >>> x = Tensor(np.array([2, 4, -1]), mindspore.float32)
  2420. >>> y = Tensor(np.array([2, 2, 2]), mindspore.float32)
  2421. >>> xdivy = ops.Xdivy()
  2422. >>> output = xdivy(x, y)
  2423. >>> print(output)
  2424. [ 1. 2. -0.5]
  2425. """
  2426. def infer_dtype(self, x_dtype, y_dtype):
  2427. return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, [mstype.float16, mstype.float32], self.name)
  2428. class Xlogy(_MathBinaryOp):
  2429. r"""
  2430. Computes the first input tensor multiplied by the logarithm of second input tensor element-wise.
  2431. Returns zero when `x` is zero.
  2432. .. math::
  2433. out_i = x_{i}\ln{y_{i}}
  2434. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2435. The inputs must be two tensors or one tensor and one scalar.
  2436. When the inputs are two tensors,
  2437. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  2438. When the inputs are one tensor and one scalar,
  2439. the scalar could only be a constant.
  2440. Inputs:
  2441. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  2442. a bool or a tensor whose data type is float16, float32 or bool.
  2443. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  2444. a bool when the first input is a tensor or a tensor whose data type is float16, float32 or bool.
  2445. The value must be positive.
  2446. Outputs:
  2447. Tensor, the shape is the same as the one after broadcasting,
  2448. and the data type is the one with higher precision or higher digits among the two inputs.
  2449. Raises:
  2450. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  2451. Supported Platforms:
  2452. ``Ascend``
  2453. Examples:
  2454. >>> x = Tensor(np.array([-5, 0, 4]), mindspore.float32)
  2455. >>> y = Tensor(np.array([2, 2, 2]), mindspore.float32)
  2456. >>> xlogy = ops.Xlogy()
  2457. >>> output = xlogy(x, y)
  2458. >>> print(output)
  2459. [-3.465736 0. 2.7725887]
  2460. """
  2461. def infer_dtype(self, x_dtype, y_dtype):
  2462. return _MathBinaryOp.do_infer_dtype(x_dtype, y_dtype, [mstype.float16, mstype.float32], self.name)
  2463. class Acosh(PrimitiveWithInfer):
  2464. r"""
  2465. Computes inverse hyperbolic cosine of the inputs element-wise.
  2466. .. math::
  2467. out_i = \cosh^{-1}(input_i)
  2468. .. warning::
  2469. Given an input tensor x, the function computes inverse hyperbolic cosine of every element.
  2470. Input range is [1, inf].
  2471. Inputs:
  2472. - **x** (Tensor) - The data type should be one of the following types: float16, float32.
  2473. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  2474. Outputs:
  2475. Tensor, has the same shape and type as `x`.
  2476. Raises:
  2477. TypeError: If `x` is not a Tensor.
  2478. Supported Platforms:
  2479. ``Ascend`` ``GPU`` ``CPU``
  2480. Examples:
  2481. >>> import numpy as np
  2482. >>> import mindspore.ops as ops
  2483. >>> from mindspore import Tensor, dtype
  2484. >>> acosh = ops.Acosh()
  2485. >>> x = Tensor(np.array([1.0, 1.5, 3.0, 100.0]), dtype.float32)
  2486. >>> output = acosh(x)
  2487. >>> print(output)
  2488. [0. 0.9624236 1.7627472 5.298292]
  2489. """
  2490. @prim_attr_register
  2491. def __init__(self):
  2492. """Initialize Acosh"""
  2493. def infer_shape(self, x_shape):
  2494. return x_shape
  2495. def infer_dtype(self, x_dtype):
  2496. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name)
  2497. return x_dtype
  2498. class Cosh(PrimitiveWithInfer):
  2499. r"""
  2500. Computes hyperbolic cosine of input element-wise.
  2501. .. math::
  2502. out_i = \cosh(input_i)
  2503. Inputs:
  2504. - **x** (Tensor) - The shape of tensor is
  2505. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  2506. Outputs:
  2507. Tensor, has the same shape as `x`.
  2508. Raises:
  2509. TypeError: If `x` is not a Tensor.
  2510. Supported Platforms:
  2511. ``Ascend`` ``CPU``
  2512. Examples:
  2513. >>> cosh = ops.Cosh()
  2514. >>> x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
  2515. >>> output = cosh(x)
  2516. >>> print(output)
  2517. [1.0289385 1.364684 1.048436 1.0040528]
  2518. """
  2519. @prim_attr_register
  2520. def __init__(self):
  2521. """Initialize Cosh"""
  2522. def infer_shape(self, x_shape):
  2523. return x_shape
  2524. def infer_dtype(self, x_dtype):
  2525. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name)
  2526. return x_dtype
  2527. class Asinh(PrimitiveWithInfer):
  2528. r"""
  2529. Computes inverse hyperbolic sine of the input element-wise.
  2530. .. math::
  2531. out_i = \sinh^{-1}(input_i)
  2532. Inputs:
  2533. - **x** (Tensor) - The shape of tensor is
  2534. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  2535. The data type should be one of the following types: float16, float32.
  2536. Outputs:
  2537. Tensor, has the same shape and type as `x`.
  2538. Raises:
  2539. TypeError: If `x` is not a Tensor.
  2540. Supported Platforms:
  2541. ``Ascend`` ``GPU`` ``CPU``
  2542. Examples:
  2543. >>> asinh = ops.Asinh()
  2544. >>> x = Tensor(np.array([-5.0, 1.5, 3.0, 100.0]), mindspore.float32)
  2545. >>> output = asinh(x)
  2546. >>> print(output)
  2547. [-2.3124385 1.1947632 1.8184465 5.298342 ]
  2548. """
  2549. @prim_attr_register
  2550. def __init__(self):
  2551. """Initialize Asinh"""
  2552. def infer_shape(self, x_shape):
  2553. return x_shape
  2554. def infer_dtype(self, x_dtype):
  2555. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name)
  2556. return x_dtype
  2557. class Sinh(PrimitiveWithInfer):
  2558. r"""
  2559. Computes hyperbolic sine of the input element-wise.
  2560. .. math::
  2561. out_i = \sinh(input_i)
  2562. Inputs:
  2563. - **x** (Tensor) - The shape of tensor is
  2564. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  2565. Outputs:
  2566. Tensor, has the same shape as `x`.
  2567. Raises:
  2568. TypeError: If `x` is not a Tensor.
  2569. Supported Platforms:
  2570. ``Ascend`` ``CPU``
  2571. Examples:
  2572. >>> sinh = ops.Sinh()
  2573. >>> x = Tensor(np.array([0.62, 0.28, 0.43, 0.62]), mindspore.float32)
  2574. >>> output = sinh(x)
  2575. >>> print(output)
  2576. [0.6604918 0.28367308 0.44337422 0.6604918 ]
  2577. """
  2578. @prim_attr_register
  2579. def __init__(self):
  2580. """Initialize Sinh"""
  2581. def infer_shape(self, x_shape):
  2582. return x_shape
  2583. def infer_dtype(self, x_dtype):
  2584. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name)
  2585. return x_dtype
  2586. class _LogicBinaryOp(_BinaryOp):
  2587. """
  2588. Define logic binary operators.
  2589. """
  2590. @staticmethod
  2591. def do_infer_dtype(x_dtype, y_dtype, valid_type=mstype.number_type, prim_name=None):
  2592. """Staticmethod of infer dtype for _LogicBinaryOp."""
  2593. args_dtype = {"x": x_dtype, "y": y_dtype}
  2594. validator.check_tensors_dtypes_same_and_valid(args_dtype, valid_type, prim_name)
  2595. return mstype.tensor_type(mstype.bool_)
  2596. def infer_dtype(self, x_dtype, y_dtype):
  2597. return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, prim_name=self.name)
  2598. class Equal(_LogicBinaryOp):
  2599. r"""
  2600. Computes the equivalence between two tensors element-wise.
  2601. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2602. The inputs must be two tensors or one tensor and one scalar.
  2603. When the inputs are two tensors, the shapes of them could be broadcast.
  2604. When the inputs are one tensor and one scalar, the scalar could only be a constant.
  2605. .. math::
  2606. out_{i} =\begin{cases}
  2607. & \text{True, if } x_{i} = y_{i} \\
  2608. & \text{False, if } x_{i} \ne y_{i}
  2609. \end{cases}
  2610. Inputs:
  2611. - **x** (Union[Tensor, Number]) - The first input is a number or
  2612. a tensor whose data type is number.
  2613. - **y** (Union[Tensor, Number]) - The second input is a number
  2614. when the first input is a tensor or a tensor whose data type is number.
  2615. The data type is the same as the first input.
  2616. Outputs:
  2617. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  2618. Raises:
  2619. TypeError: If neither `x` nor `y` is a Tensor.
  2620. Supported Platforms:
  2621. ``Ascend`` ``GPU`` ``CPU``
  2622. Examples:
  2623. >>> # case 1: The shape of two inputs are different
  2624. >>> x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  2625. >>> equal = ops.Equal()
  2626. >>> output = equal(x, 2.0)
  2627. >>> print(output)
  2628. [False True False]
  2629. >>> # case 2: The shape of two inputs are the same
  2630. >>> x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2631. >>> y = Tensor(np.array([1, 2, 4]), mindspore.int32)
  2632. >>> equal = ops.Equal()
  2633. >>> output = equal(x, y)
  2634. >>> print(output)
  2635. [ True True False]
  2636. """
  2637. def infer_dtype(self, x_dtype, y_dtype):
  2638. return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, mstype.number_type + (mstype.bool_,), self.name)
  2639. def infer_value(self, x, y):
  2640. if x is None or y is None:
  2641. return None
  2642. if isinstance(x, Tensor) and x.has_init:
  2643. x = x.init_data()
  2644. if isinstance(y, Tensor) and y.has_init:
  2645. y = y.init_data()
  2646. return Tensor(x.asnumpy() == y.asnumpy())
  2647. class ApproximateEqual(_LogicBinaryOp):
  2648. r"""
  2649. Returns True if abs(x-y) is smaller than tolerance element-wise, otherwise False.
  2650. .. math::
  2651. out_i = \begin{cases}
  2652. & \text{ if } \left | x_{i} - y_{i} \right | < \text{tolerance},\ \ True \\
  2653. & \text{ if } \left | x_{i} - y_{i} \right | \ge \text{tolerance},\ \ False
  2654. \end{cases}
  2655. where :math:`\text{tolerance}` indicates Acceptable maximum tolerance.
  2656. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2657. If they have different data types, lower priority data type will be converted to
  2658. relatively highest priority data type.
  2659. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  2660. Args:
  2661. tolerance (float): The maximum deviation that two elements can be considered equal. Default: 1e-05.
  2662. Inputs:
  2663. - **x** (Tensor) - A tensor. Must be one of the following types: float32, float16.
  2664. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  2665. - **y** (Tensor) - A tensor of the same type and shape as 'x'.
  2666. Outputs:
  2667. Tensor, the shape is the same as the shape of 'x', and the data type is bool.
  2668. Raises:
  2669. TypeError: If `tolerance` is not a float.
  2670. Supported Platforms:
  2671. ``Ascend``
  2672. Examples:
  2673. >>> x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  2674. >>> y = Tensor(np.array([2, 4, 6]), mindspore.float32)
  2675. >>> approximate_equal = ops.ApproximateEqual(2.)
  2676. >>> output = approximate_equal(x, y)
  2677. >>> print(output)
  2678. [ True True False]
  2679. """
  2680. @prim_attr_register
  2681. def __init__(self, tolerance=1e-05):
  2682. """Initialize ApproximateEqual"""
  2683. validator.check_value_type("tolerance", tolerance, [float], self.name)
  2684. def infer_shape(self, x_shape, y_shape):
  2685. validator.check("x_shape", x_shape, "y_shape", y_shape, Rel.EQ, self.name)
  2686. return x_shape
  2687. def infer_dtype(self, x_dtype, y_dtype):
  2688. args_dtype = {"x": x_dtype, "y": y_dtype}
  2689. valid_type = [mstype.float32, mstype.float16]
  2690. validator.check_tensors_dtypes_same_and_valid(args_dtype, valid_type, prim_name=self.name)
  2691. return mstype.tensor_type(mstype.bool_)
  2692. class EqualCount(PrimitiveWithInfer):
  2693. """
  2694. Computes the number of the same elements of two tensors.
  2695. The two input tensors must have the same data type and shape.
  2696. Inputs:
  2697. - **x** (Tensor) - The first input tensor. If the data type and shape of `y` are determined, then `x`
  2698. must be the same as `y`, and vice versa.
  2699. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  2700. - **y** (Tensor) - The second input tensor. If the data type and shape of `x` are determined, then `y`
  2701. must be the same as `x`, and vice versa.
  2702. Outputs:
  2703. Tensor, with the type same as input tensor and size as (1,).
  2704. Raises:
  2705. TypeError: If `x` or `y` is not a Tensor.
  2706. ValueError: If shape of `x` is not equal to shape of `y`.
  2707. Supported Platforms:
  2708. ``GPU`` ``CPU``
  2709. Examples:
  2710. >>> x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2711. >>> y = Tensor(np.array([1, 2, 4]), mindspore.int32)
  2712. >>> equal_count = ops.EqualCount()
  2713. >>> output = equal_count(x, y)
  2714. >>> print(output)
  2715. [2]
  2716. """
  2717. @prim_attr_register
  2718. def __init__(self):
  2719. """Initialize EqualCount"""
  2720. self.init_prim_io_names(inputs=['x', 'y'], outputs=['output'])
  2721. def infer_shape(self, x_shape, y_shape):
  2722. validator.check("x_shape", x_shape, "y_shape", y_shape, Rel.EQ, self.name)
  2723. output_shape = (1,)
  2724. return output_shape
  2725. def infer_dtype(self, x_dtype, y_dtype):
  2726. args = {'x': x_dtype, 'y': y_dtype}
  2727. validator.check_tensors_dtypes_same_and_valid(args, mstype.number_type + (mstype.bool_,), self.name)
  2728. return x_dtype
  2729. class NotEqual(_LogicBinaryOp):
  2730. r"""
  2731. Computes the non-equivalence of two tensors element-wise.
  2732. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2733. The inputs must be two tensors or one tensor and one scalar.
  2734. When the inputs are two tensors, the shapes of them could be broadcast.
  2735. When the inputs are one tensor and one scalar, the scalar could only be a constant.
  2736. .. math::
  2737. out_{i} =\begin{cases}
  2738. & \text{True, if } x_{i} \ne y_{i} \\
  2739. & \text{False, if } x_{i} = y_{i}
  2740. \end{cases}
  2741. Inputs:
  2742. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  2743. a bool or a tensor whose data type is number or bool.
  2744. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  2745. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  2746. Outputs:
  2747. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  2748. Raises:
  2749. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  2750. TypeError: If neither `x` nor `y` is a Tensor.
  2751. Supported Platforms:
  2752. ``Ascend`` ``GPU`` ``CPU``
  2753. Examples:
  2754. >>> x = Tensor(np.array([1, 2, 3]), mindspore.float32)
  2755. >>> not_equal = ops.NotEqual()
  2756. >>> output = not_equal(x, 2.0)
  2757. >>> print(output)
  2758. [ True False True]
  2759. >>>
  2760. >>> x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2761. >>> y = Tensor(np.array([1, 2, 4]), mindspore.int32)
  2762. >>> not_equal = ops.NotEqual()
  2763. >>> output = not_equal(x, y)
  2764. >>> print(output)
  2765. [False False True]
  2766. """
  2767. def infer_dtype(self, x_dtype, y_dtype):
  2768. return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, mstype.number_type + (mstype.bool_,), self.name)
  2769. class Greater(_LogicBinaryOp):
  2770. r"""
  2771. Computes the boolean value of :math:`x > y` element-wise.
  2772. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2773. The inputs must be two tensors or one tensor and one scalar.
  2774. When the inputs are two tensors,
  2775. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  2776. When the inputs are one tensor and one scalar,
  2777. the scalar could only be a constant.
  2778. .. math::
  2779. out_{i} =\begin{cases}
  2780. & \text{True, if } x_{i}>y_{i} \\
  2781. & \text{False, if } x_{i}<=y_{i}
  2782. \end{cases}
  2783. Note:
  2784. Broadcasting is supported.
  2785. Inputs:
  2786. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  2787. a bool or a tensor whose data type is number or bool.
  2788. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  2789. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  2790. Outputs:
  2791. Tensor, the shape is the same as the one after broadcasting, and the data type is bool.
  2792. Raises:
  2793. TypeError: If neither `x` nor `y` is a Tensor.
  2794. Supported Platforms:
  2795. ``Ascend`` ``GPU`` ``CPU``
  2796. Examples:
  2797. >>> x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2798. >>> y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  2799. >>> greater = ops.Greater()
  2800. >>> output = greater(x, y)
  2801. >>> print(output)
  2802. [False True False]
  2803. """
  2804. def infer_value(self, x, y):
  2805. if x is not None and y is not None:
  2806. x = x.asnumpy()
  2807. y = y.asnumpy()
  2808. out = np.array(np.greater(x, y))
  2809. return Tensor(out)
  2810. return None
  2811. class GreaterEqual(_LogicBinaryOp):
  2812. r"""
  2813. Computes the boolean value of :math:`x >= y` element-wise.
  2814. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2815. The inputs must be two tensors or one tensor and one scalar.
  2816. When the inputs are two tensors,
  2817. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  2818. When the inputs are one tensor and one scalar,
  2819. the scalar could only be a constant.
  2820. .. math::
  2821. out_{i} =\begin{cases}
  2822. & \text{True, if } x_{i}>=y_{i} \\
  2823. & \text{False, if } x_{i}<y_{i}
  2824. \end{cases}
  2825. Inputs:
  2826. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  2827. a bool or a tensor whose data type is number or bool.
  2828. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  2829. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  2830. Outputs:
  2831. Tensor, the shape is the same as the one after broadcasting, and the data type is bool.
  2832. Raises:
  2833. TypeError: If neither `x` nor `y` is a Tensor.
  2834. Supported Platforms:
  2835. ``Ascend`` ``GPU`` ``CPU``
  2836. Examples:
  2837. >>> x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2838. >>> y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  2839. >>> greater_equal = ops.GreaterEqual()
  2840. >>> output = greater_equal(x, y)
  2841. >>> print(output)
  2842. [True True False]
  2843. """
  2844. def infer_value(self, x, y):
  2845. if x is not None and y is not None:
  2846. x = x.asnumpy()
  2847. y = y.asnumpy()
  2848. out = np.array(np.greater_equal(x, y))
  2849. return Tensor(out)
  2850. return None
  2851. class Lerp(Primitive):
  2852. """
  2853. Does a linear interpolation of two tensors start and end based on a float or tensor weight.
  2854. If `weight` is a tensor, the shapes of three inputs need to be broadcast;
  2855. If `weight` is a float, the shapes of `start` and `end` need to be broadcast.
  2856. .. math::
  2857. output_{i} = start_{i} + weight_{i} * (end_{i} - start_{i})
  2858. Inputs:
  2859. - **start** (Tensor) - The tensor with the starting points. Data type must be float16 or float32.
  2860. - **end** (Tensor) - The tensor with the ending points. Data type must be float16 or float32.
  2861. - **weight** (Union[float, Tensor]) – The weight for the interpolation formula. Must be a float
  2862. or a scalar tensor with float16 or float32 data type.
  2863. Outputs:
  2864. Tensor, has the same type and shape as input `start`.
  2865. Raises:
  2866. TypeError: If `start` or `end` is not a tensor.
  2867. TypeError: If `weight` is neither float nor tensor.
  2868. TypeError: If dtype of `start` or `end` is neither float16 nor float32.
  2869. TypeError: If dtype of `weight` is neither float16 nor float32 when it is a tensor.
  2870. TypeError: If `start` and `end` have different data types.
  2871. TypeError: If `start`, `end` and `weight` have different data types when `weight` is a tensor.
  2872. ValueError: If `end` could not be broadcast to a tensor with shape of `start`.
  2873. ValueError: If `weight` could not be broadcast to tensors with shapes of `start` and `end` when it is a tensor.
  2874. Supported Platforms:
  2875. ``Ascend``
  2876. Examples:
  2877. >>> start = Tensor(np.array([1., 2., 3., 4.]), mindspore.float32)
  2878. >>> end = Tensor(np.array([10., 10., 10., 10.]), mindspore.float32)
  2879. >>> lerp = ops.Lerp()
  2880. >>> output = lerp(start, end, 0.5)
  2881. >>> print(output)
  2882. [5.5 6. 6.5 7. ]
  2883. """
  2884. @prim_attr_register
  2885. def __init__(self):
  2886. self.init_prim_io_names(inputs=['start', 'end', 'weight'], outputs=['output'])
  2887. class Less(_LogicBinaryOp):
  2888. r"""
  2889. Computes the boolean value of :math:`x < y` element-wise.
  2890. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2891. The inputs must be two tensors or one tensor and one scalar.
  2892. When the inputs are two tensors,
  2893. dtypes of them cannot be both bool, and the shapes of them could be broadcast.
  2894. When the inputs are one tensor and one scalar,
  2895. the scalar could only be a constant.
  2896. .. math::
  2897. out_{i} =\begin{cases}
  2898. & \text{True, if } x_{i}<y_{i} \\
  2899. & \text{False, if } x_{i}>=y_{i}
  2900. \end{cases}
  2901. Inputs:
  2902. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  2903. a bool or a tensor whose data type is number or bool.
  2904. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  2905. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  2906. Outputs:
  2907. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  2908. Raises:
  2909. TypeError: If `x` and `y` is not one of the following: Tensor, Number, bool.
  2910. Supported Platforms:
  2911. ``Ascend`` ``GPU`` ``CPU``
  2912. Examples:
  2913. >>> x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2914. >>> y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  2915. >>> less = ops.Less()
  2916. >>> output = less(x, y)
  2917. >>> print(output)
  2918. [False False True]
  2919. """
  2920. def infer_value(self, x, y):
  2921. if x is not None and y is not None:
  2922. x = x.asnumpy()
  2923. y = y.asnumpy()
  2924. out = np.array(np.less(x, y))
  2925. return Tensor(out)
  2926. return None
  2927. class LessEqual(_LogicBinaryOp):
  2928. r"""
  2929. Computes the boolean value of :math:`x <= y` element-wise.
  2930. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  2931. The inputs must be two tensors or one tensor and one scalar.
  2932. When the inputs are two tensors,
  2933. dtypes of them cannot be both bool , and the shapes of them could be broadcast.
  2934. When the inputs are one tensor and one scalar,
  2935. the scalar could only be a constant.
  2936. .. math::
  2937. out_{i} =\begin{cases}
  2938. & \text{True, if } x_{i}<=y_{i} \\
  2939. & \text{False, if } x_{i}>y_{i}
  2940. \end{cases}
  2941. Inputs:
  2942. - **x** (Union[Tensor, Number, bool]) - The first input is a number or
  2943. a bool or a tensor whose data type is number or bool.
  2944. - **y** (Union[Tensor, Number, bool]) - The second input is a number or
  2945. a bool when the first input is a tensor or a tensor whose data type is number or bool.
  2946. Outputs:
  2947. Tensor, the shape is the same as the one after broadcasting,and the data type is bool.
  2948. Raises:
  2949. TypeError: If neither `x` nor `y` is a Tensor.
  2950. Supported Platforms:
  2951. ``Ascend`` ``GPU`` ``CPU``
  2952. Examples:
  2953. >>> x = Tensor(np.array([1, 2, 3]), mindspore.int32)
  2954. >>> y = Tensor(np.array([1, 1, 4]), mindspore.int32)
  2955. >>> less_equal = ops.LessEqual()
  2956. >>> output = less_equal(x, y)
  2957. >>> print(output)
  2958. [ True False True]
  2959. """
  2960. def infer_value(self, x, y):
  2961. if x is not None and y is not None:
  2962. x = x.asnumpy()
  2963. y = y.asnumpy()
  2964. out = np.array(np.less_equal(x, y))
  2965. return Tensor(out)
  2966. return None
  2967. class LogicalNot(PrimitiveWithInfer):
  2968. """
  2969. Computes the "logical NOT" of a tensor element-wise.
  2970. .. math::
  2971. out_{i} = \\neg x_{i}
  2972. .. warning::
  2973. The input and output values are "1" or "0", corresponding to bool values "true" and "false".
  2974. Inputs:
  2975. - **x** (Tensor) - The input tensor whose dtype is bool.
  2976. :math:`(N,*)` where :math:`*` means,any number of additional dimensions.
  2977. Outputs:
  2978. Tensor, the shape is the same as the `x`, and the dtype is bool.
  2979. Raises:
  2980. TypeError: If `x` is not a Tensor.
  2981. Supported Platforms:
  2982. ``Ascend`` ``GPU`` ``CPU``
  2983. Examples:
  2984. >>> x = Tensor(np.array([True, False, True]), mindspore.bool_)
  2985. >>> logical_not = ops.LogicalNot()
  2986. >>> output = logical_not(x)
  2987. >>> print(output)
  2988. [False True False]
  2989. """
  2990. @prim_attr_register
  2991. def __init__(self):
  2992. """Initialize LogicalNot"""
  2993. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  2994. def infer_shape(self, x_shape):
  2995. return x_shape
  2996. def infer_dtype(self, x_dtype):
  2997. validator.check_tensor_dtype_valid("x", x_dtype, [mstype.bool_], self.name + " or '~' operator")
  2998. return mstype.tensor_type(mstype.bool_)
  2999. def infer_value(self, x):
  3000. if x is not None:
  3001. x = x.asnumpy()
  3002. return Tensor(np.logical_not(x))
  3003. return None
  3004. class LogicalAnd(_LogicBinaryOp):
  3005. r"""
  3006. Computes the "logical AND" of two tensors element-wise.
  3007. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  3008. The inputs must be two tensors or one tensor and one bool.
  3009. When the inputs are two tensors, the shapes of them could be broadcast,
  3010. and the data types of them must be bool.
  3011. When the inputs are one tensor and one bool, the bool object could only be a constant,
  3012. and the data type of the tensor must be bool.
  3013. .. math::
  3014. out_{i} = x_{i} \wedge y_{i}
  3015. Note:
  3016. LogicalAnd supports broadcasting.
  3017. Inputs:
  3018. - **x** (Union[Tensor, bool]) - The first input is a bool or a tensor whose data type is bool.
  3019. - **y** (Union[Tensor, bool]) - The second input is a bool when the first input is a tensor or
  3020. a tensor whose data type is bool.
  3021. Outputs:
  3022. Tensor, the shape is the same as the one after broadcasting, and the data type is bool.
  3023. Raises:
  3024. TypeError: If neither `x` nor `y` is a Tensor.
  3025. Supported Platforms:
  3026. ``Ascend`` ``GPU`` ``CPU``
  3027. Examples:
  3028. >>> x = Tensor(np.array([True, False, True]), mindspore.bool_)
  3029. >>> y = Tensor(np.array([True, True, False]), mindspore.bool_)
  3030. >>> logical_and = ops.LogicalAnd()
  3031. >>> output = logical_and(x, y)
  3032. >>> print(output)
  3033. [ True False False]
  3034. """
  3035. def infer_dtype(self, x_dtype, y_dtype):
  3036. return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, (mstype.bool_,), self.name)
  3037. def infer_value(self, x, y):
  3038. if x is not None and y is not None:
  3039. x = x.asnumpy()
  3040. y = y.asnumpy()
  3041. out = np.array(np.logical_and(x, y))
  3042. return Tensor(out)
  3043. return None
  3044. class LogicalOr(_LogicBinaryOp):
  3045. """
  3046. Computes the "logical OR" of two tensors element-wise.
  3047. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  3048. The inputs must be two tensors or one tensor and one bool.
  3049. When the inputs are two tensors, the shapes of them could be broadcast,
  3050. and the data types of them must be bool.
  3051. When the inputs are one tensor and one bool, the bool object could only be a constant,
  3052. and the data type of the tensor must be bool.
  3053. .. math::
  3054. out_{i} = x_{i} \\vee y_{i}
  3055. Note:
  3056. LogicalOr supports broadcasting.
  3057. Inputs:
  3058. - **x** (Union[Tensor, bool]) - The first input is a bool or a tensor whose data type is bool.
  3059. - **y** (Union[Tensor, bool]) - The second input is a bool when the first input is a tensor or
  3060. a tensor whose data type is bool.
  3061. Outputs:
  3062. Tensor, the shape is the same as the one after broadcasting, and the data type is bool.
  3063. Raises:
  3064. TypeError: If neither `x` nor `y` is a Tensor.
  3065. Supported Platforms:
  3066. ``Ascend`` ``GPU`` ``CPU``
  3067. Examples:
  3068. >>> x = Tensor(np.array([True, False, True]), mindspore.bool_)
  3069. >>> y = Tensor(np.array([True, True, False]), mindspore.bool_)
  3070. >>> logical_or = ops.LogicalOr()
  3071. >>> output = logical_or(x, y)
  3072. >>> print(output)
  3073. [ True True True]
  3074. """
  3075. def infer_dtype(self, x_dtype, y_dtype):
  3076. return _LogicBinaryOp.do_infer_dtype(x_dtype, y_dtype, (mstype.bool_,), self.name)
  3077. def infer_value(self, x, y):
  3078. if x is not None and y is not None:
  3079. x = x.asnumpy()
  3080. y = y.asnumpy()
  3081. out = np.array(np.logical_or(x, y))
  3082. return Tensor(out)
  3083. return None
  3084. class IsNan(PrimitiveWithInfer):
  3085. r"""
  3086. Determines which elements are NaN for each position.
  3087. .. math::
  3088. out_i = \begin{cases}
  3089. & \text{ if } x_{i} = \text{Nan},\ \ True \\
  3090. & \text{ if } x_{i} \ne \text{Nan},\ \ False
  3091. \end{cases}
  3092. where :math:`Nan` means not a number.
  3093. Inputs:
  3094. - **x** (Tensor) - The input tensor.
  3095. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3096. Outputs:
  3097. Tensor, has the same shape of input, and the dtype is bool.
  3098. Raises:
  3099. TypeError: If `x` is not a Tensor.
  3100. Supported Platforms:
  3101. ``GPU`` ``CPU``
  3102. Examples:
  3103. >>> is_nan = ops.IsNan()
  3104. >>> x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
  3105. >>> output = is_nan(x)
  3106. >>> print(output)
  3107. [True False False]
  3108. """
  3109. @prim_attr_register
  3110. def __init__(self):
  3111. """Initialize IsNan"""
  3112. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  3113. def infer_shape(self, x_shape):
  3114. return x_shape
  3115. def infer_dtype(self, x_dtype):
  3116. return mstype.tensor_type(mstype.bool_)
  3117. class IsInf(PrimitiveWithInfer):
  3118. r"""
  3119. Determines which elements are inf or -inf for each position
  3120. .. math::
  3121. out_i = \begin{cases}
  3122. & \text{ if } x_{i} = \text{Inf},\ \ True \\
  3123. & \text{ if } x_{i} \ne \text{Inf},\ \ False
  3124. \end{cases}
  3125. where :math:`Inf` means not a number.
  3126. Inputs:
  3127. - **x** (Tensor) - The input tensor.
  3128. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3129. Outputs:
  3130. Tensor, has the same shape of input, and the dtype is bool.
  3131. Raises:
  3132. TypeError: If `x` is not a Tensor.
  3133. Supported Platforms:
  3134. ``GPU``
  3135. Examples:
  3136. >>> is_inf = ops.IsInf()
  3137. >>> x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
  3138. >>> output = is_inf(x)
  3139. >>> print(output)
  3140. [False False True]
  3141. """
  3142. @prim_attr_register
  3143. def __init__(self):
  3144. """Initialize IsInf"""
  3145. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  3146. def infer_shape(self, x_shape):
  3147. return x_shape
  3148. def infer_dtype(self, x_dtype):
  3149. return mstype.tensor_type(mstype.bool_)
  3150. class IsFinite(PrimitiveWithInfer):
  3151. r"""
  3152. Determines which elements are finite for each position.
  3153. .. math::
  3154. out_i = \begin{cases}
  3155. & \text{ if } x_{i} = \text{Finite},\ \ True\ \\
  3156. & \text{ if } x_{i} \ne \text{Finite},\ \ False
  3157. \end{cases}
  3158. Inputs:
  3159. - **x** (Tensor) - The input tensor.
  3160. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3161. Outputs:
  3162. Tensor, has the same shape of input, and the dtype is bool.
  3163. Raises:
  3164. TypeError: If `x` is not a Tensor.
  3165. Supported Platforms:
  3166. ``Ascend`` ``GPU`` ``CPU``
  3167. Examples:
  3168. >>> is_finite = ops.IsFinite()
  3169. >>> x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
  3170. >>> output = is_finite(x)
  3171. >>> print(output)
  3172. [False True False]
  3173. """
  3174. @prim_attr_register
  3175. def __init__(self):
  3176. """Initialize IsFinite"""
  3177. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  3178. def infer_shape(self, x_shape):
  3179. return x_shape
  3180. def infer_dtype(self, x_dtype):
  3181. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type + (mstype.bool_,), self.name)
  3182. return mstype.tensor_type(mstype.bool_)
  3183. class FloatStatus(PrimitiveWithInfer):
  3184. """
  3185. Determines if the elements contain Not a Number(NaN), infinite or negative infinite. 0 for normal, 1 for overflow.
  3186. Inputs:
  3187. - **x** (Tensor) - The input tensor. The data type must be float16 or float32.
  3188. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3189. Outputs:
  3190. Tensor, has the shape of `(1,)`, and the dtype is `mindspore.dtype.float32`.
  3191. Raises:
  3192. TypeError: If dtype of `x` is neither float16 nor float32.
  3193. Supported Platforms:
  3194. ``GPU``
  3195. Examples:
  3196. >>> float_status = ops.FloatStatus()
  3197. >>> x = Tensor(np.array([np.log(-1), 1, np.log(0)]), mindspore.float32)
  3198. >>> result = float_status(x)
  3199. >>> print(result)
  3200. [1.]
  3201. """
  3202. @prim_attr_register
  3203. def __init__(self):
  3204. """Initialize FloatStatus"""
  3205. self.init_prim_io_names(inputs=['x'], outputs=['output'])
  3206. def infer_shape(self, x_shape):
  3207. return [1]
  3208. def infer_dtype(self, x_dtype):
  3209. validator.check_tensor_dtype_valid('x', x_dtype, [mstype.float32, mstype.float16], self.name)
  3210. return mstype.float32
  3211. class NPUAllocFloatStatus(PrimitiveWithInfer):
  3212. """
  3213. Allocates a flag to store the overflow status.
  3214. The flag is a tensor whose shape is `(8,)` and data type is `mindspore.dtype.float32`.
  3215. Note:
  3216. Examples: see `NPUGetFloatStatus`.
  3217. Outputs:
  3218. Tensor, has the shape of `(8,)`.
  3219. Supported Platforms:
  3220. ``Ascend``
  3221. Examples:
  3222. >>> alloc_status = ops.NPUAllocFloatStatus()
  3223. >>> output = alloc_status()
  3224. >>> print(output)
  3225. [0. 0. 0. 0. 0. 0. 0. 0.]
  3226. """
  3227. @prim_attr_register
  3228. def __init__(self):
  3229. """Initialize NPUAllocFloatStatus"""
  3230. self.add_prim_attr("_side_effect_flag", True)
  3231. def infer_shape(self):
  3232. return [8]
  3233. def infer_dtype(self):
  3234. return mstype.float32
  3235. class NPUGetFloatStatus(PrimitiveWithInfer):
  3236. """
  3237. Updates the flag which is the output tensor of `NPUAllocFloatStatus` with the latest overflow status.
  3238. The flag is a tensor whose shape is `(8,)` and data type is `mindspore.dtype.float32`.
  3239. If the sum of the flag equals to 0, there is no overflow happened. If the sum of the flag is bigger than 0, there
  3240. is overflow happened.
  3241. Inputs:
  3242. - **x** (Tensor) - The output tensor of `NPUAllocFloatStatus`.
  3243. The data type must be float16 or float32.
  3244. :math:`(N,*)` where :math:`*` means, any number of additional dimensions, its rank should less than 8.
  3245. Outputs:
  3246. Tensor, has the same shape as `x`. All the elements in the tensor will be zero.
  3247. Raises:
  3248. TypeError: If `x` is not a Tensor.
  3249. TypeError: If dtype of `x` is neither float16 nor float32.
  3250. Supported Platforms:
  3251. ``Ascend``
  3252. Examples:
  3253. >>> alloc_status = ops.NPUAllocFloatStatus()
  3254. >>> get_status = ops.NPUGetFloatStatus()
  3255. >>> init = alloc_status()
  3256. >>> get_status(init)
  3257. >>> print(init)
  3258. [0. 0. 0. 0. 0. 0. 0. 0.]
  3259. """
  3260. @prim_attr_register
  3261. def __init__(self):
  3262. """Initialize NPUGetFloatStatus"""
  3263. self.add_prim_attr("_side_effect_flag", True)
  3264. def infer_shape(self, x_shape):
  3265. cls_name = self.name
  3266. validator.check_equal_int(len(x_shape), 1, "len(x_shape)", cls_name)
  3267. validator.check_equal_int(x_shape[0], 8, "x_shape[0]", cls_name)
  3268. return [8]
  3269. def infer_dtype(self, x_dtype):
  3270. validator.check_tensor_dtype_valid('x', x_dtype, [mstype.float16, mstype.float32], self.name)
  3271. return mstype.float32
  3272. class NPUClearFloatStatus(PrimitiveWithInfer):
  3273. """
  3274. Clears the flag which stores the overflow status.
  3275. Note:
  3276. The flag is in the register on the `Ascend` device. It will be reset and can not be reused again after the
  3277. `NPUClearFloatStatus` is called.
  3278. Examples: see `NPUGetFloatStatus`.
  3279. Inputs:
  3280. - **x** (Tensor) - The output tensor of `NPUAllocFloatStatus`.
  3281. The data type must be float16 or float32.
  3282. Outputs:
  3283. Tensor, has the same shape as `x`. All the elements in the tensor will be zero.
  3284. Supported Platforms:
  3285. ``Ascend``
  3286. Examples:
  3287. >>> alloc_status = ops.NPUAllocFloatStatus()
  3288. >>> get_status = ops.NPUGetFloatStatus()
  3289. >>> clear_status = ops.NPUClearFloatStatus()
  3290. >>> init = alloc_status()
  3291. >>> flag = get_status(init)
  3292. >>> clear_status(init)
  3293. >>> print(init)
  3294. [0. 0. 0. 0. 0. 0. 0. 0.]
  3295. """
  3296. @prim_attr_register
  3297. def __init__(self):
  3298. """Initialize NPUClearFloatStatus"""
  3299. self.add_prim_attr("_side_effect_flag", True)
  3300. def infer_shape(self, x_shape):
  3301. cls_name = self.name
  3302. validator.check_equal_int(len(x_shape), 1, "len(x_shape)", cls_name)
  3303. validator.check_equal_int(x_shape[0], 8, "x_shape[0]", cls_name)
  3304. return [8]
  3305. def infer_dtype(self, x_dtype):
  3306. validator.check_tensor_dtype_valid('x', x_dtype, [mstype.float16, mstype.float32], self.name)
  3307. return mstype.float32
  3308. class Cos(Primitive):
  3309. r"""
  3310. Computes cosine of input element-wise.
  3311. .. math::
  3312. out_i = cos(x_i)
  3313. Inputs:
  3314. - **x** (Tensor) - The shape of tensor is
  3315. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3316. Outputs:
  3317. Tensor, has the same shape as `x`.
  3318. Raises:
  3319. TypeError: If `x` is not a Tensor.
  3320. Supported Platforms:
  3321. ``Ascend`` ``GPU`` ``CPU``
  3322. Examples:
  3323. >>> cos = ops.Cos()
  3324. >>> x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
  3325. >>> output = cos(x)
  3326. >>> print(output)
  3327. [0.971338 0.67487574 0.95233357 0.9959527 ]
  3328. """
  3329. @prim_attr_register
  3330. def __init__(self):
  3331. """Initialize Cos"""
  3332. class ACos(PrimitiveWithInfer):
  3333. r"""
  3334. Computes arccosine of input tensors element-wise.
  3335. .. math::
  3336. out_i = cos^{-1}(x_i)
  3337. Inputs:
  3338. - **x** (Tensor) - The shape of tensor is
  3339. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3340. Outputs:
  3341. Tensor, has the same shape as `x`.
  3342. Raises:
  3343. TypeError: If `x` is not a Tensor.
  3344. Supported Platforms:
  3345. ``Ascend`` ``GPU`` ``CPU``
  3346. Examples:
  3347. >>> acos = ops.ACos()
  3348. >>> x = Tensor(np.array([0.74, 0.04, 0.30, 0.56]), mindspore.float32)
  3349. >>> output = acos(x)
  3350. >>> print(output)
  3351. [0.7377037 1.5307858 1.2661037 0.97641146]
  3352. """
  3353. @prim_attr_register
  3354. def __init__(self):
  3355. """Initialize ACos"""
  3356. def infer_shape(self, x_shape):
  3357. return x_shape
  3358. def infer_dtype(self, x_dtype):
  3359. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name)
  3360. return x_dtype
  3361. class Sin(PrimitiveWithInfer):
  3362. r"""
  3363. Computes sine of the input element-wise.
  3364. .. math::
  3365. out_i = sin(x_i)
  3366. Inputs:
  3367. - **x** (Tensor) - The shape of tensor is
  3368. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3369. Outputs:
  3370. Tensor, has the same shape as `x`.
  3371. Raises:
  3372. TypeError: If `x` is not a Tensor.
  3373. Supported Platforms:
  3374. ``Ascend`` ``GPU`` ``CPU``
  3375. Examples:
  3376. >>> sin = ops.Sin()
  3377. >>> x = Tensor(np.array([0.62, 0.28, 0.43, 0.62]), mindspore.float32)
  3378. >>> output = sin(x)
  3379. >>> print(output)
  3380. [0.5810352 0.27635565 0.41687083 0.5810352 ]
  3381. """
  3382. @prim_attr_register
  3383. def __init__(self):
  3384. """Initialize Sin."""
  3385. def infer_shape(self, x_shape):
  3386. return x_shape
  3387. def infer_dtype(self, x_dtype):
  3388. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name)
  3389. return x_dtype
  3390. class Asin(PrimitiveWithInfer):
  3391. r"""
  3392. Computes arcsine of input tensors element-wise.
  3393. .. math::
  3394. out_i = sin^{-1}(x_i)
  3395. Inputs:
  3396. - **x** (Tensor) - The shape of tensor is
  3397. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3398. Outputs:
  3399. Tensor, has the same shape as `x`.
  3400. Raises:
  3401. TypeError: If `x` is not a Tensor.
  3402. Supported Platforms:
  3403. ``Ascend`` ``GPU`` ``CPU``
  3404. Examples:
  3405. >>> asin = ops.Asin()
  3406. >>> x = Tensor(np.array([0.74, 0.04, 0.30, 0.56]), mindspore.float32)
  3407. >>> output = asin(x)
  3408. >>> print(output)
  3409. [0.8330927 0.04001068 0.30469266 0.59438497]
  3410. """
  3411. @prim_attr_register
  3412. def __init__(self):
  3413. """Initialize Asin"""
  3414. def infer_shape(self, x_shape):
  3415. return x_shape
  3416. def infer_dtype(self, x_dtype):
  3417. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name)
  3418. return x_dtype
  3419. class NMSWithMask(PrimitiveWithInfer):
  3420. r"""
  3421. When object detection problem is performed in the computer vision field, object detection algorithm generates
  3422. a plurality of bounding boxes. Selects some bounding boxes in descending order of score(Descending order is not
  3423. supported in Ascend platform currently). Use the box with the highest score calculate the overlap between other
  3424. boxes and the current box, and delete the box based on a certain threshold(IOU). The IOU is as follows,
  3425. .. math::
  3426. \text{IOU} = \frac{\text{Area of Overlap}}{\text{Area of Union}}
  3427. .. warning::
  3428. Only supports 2864 input boxes at one time.
  3429. Args:
  3430. iou_threshold (float): Specifies the threshold of overlap boxes with respect to
  3431. IOU. Default: 0.5.
  3432. Inputs:
  3433. - **bboxes** (Tensor) - The shape of tensor is :math:`(N, 5)`. Input bounding boxes.
  3434. `N` is the number of input bounding boxes. Every bounding box
  3435. contains 5 values, the first 4 values are the coordinates(x0, y0, x1, y1) of bounding box which
  3436. represents the point of top-left and bottom-right, and the last value is the score of this bounding box.
  3437. The data type must be float16 or float32.
  3438. Outputs:
  3439. tuple[Tensor], tuple of three tensors, they are selected_boxes, selected_idx and selected_mask.
  3440. - **selected_boxes** (Tensor) - The shape of tensor is :math:`(N, 5)`. The list of bounding boxes
  3441. after non-max suppression calculation.
  3442. - **selected_idx** (Tensor) - The shape of tensor is :math:`(N,)`. The indexes list of
  3443. valid input bounding boxes.
  3444. - **selected_mask** (Tensor) - The shape of tensor is :math:`(N,)`. A mask list of
  3445. valid output bounding boxes.
  3446. Raises:
  3447. ValueError: If the `iou_threshold` is not a float number, or if the first dimension
  3448. of input Tensor is less than or equal to 0, or if the data type of the input
  3449. Tensor is not float16 or float32.
  3450. Supported Platforms:
  3451. ``Ascend`` ``GPU`` ``CPU``
  3452. Examples:
  3453. >>> bbox = np.array([[100.0, 100.0, 50.0, 68.0, 0.63], [150.0, 75.0, 165.0, 115.0, 0.55],
  3454. ... [12.0, 190.0, 288.0, 200.0, 0.9], [28.0, 130.0, 106.0, 172.0, 0.3]])
  3455. >>> bbox[:, 2] += bbox[:, 0]
  3456. >>> bbox[:, 3] += bbox[:, 1]
  3457. >>> inputs = Tensor(bbox, mindspore.float32)
  3458. >>> nms = ops.NMSWithMask(0.1)
  3459. >>> output_boxes, indices, mask = nms(inputs)
  3460. >>> indices_np = indices.asnumpy()
  3461. >>> print(indices_np[mask.asnumpy()])
  3462. [0 1 2]
  3463. """
  3464. @prim_attr_register
  3465. def __init__(self, iou_threshold=0.5):
  3466. """Initialize NMSWithMask"""
  3467. validator.check_value_type("iou_threshold", iou_threshold, [float], self.name)
  3468. self.init_prim_io_names(inputs=['bboxes'], outputs=['selected_boxes', 'selected_idx', 'selected_mask'])
  3469. self.is_ge = context.get_context("enable_ge")
  3470. def infer_shape(self, bboxes_shape):
  3471. cls_name = self.name
  3472. validator.check_equal_int(len(bboxes_shape), 2, "bboxes rank", cls_name)
  3473. validator.check_positive_int(bboxes_shape[0], "bboxes.shape[0]", cls_name)
  3474. validator.check_equal_int(bboxes_shape[1], 5, "bboxes.shape[1]", cls_name)
  3475. num = bboxes_shape[0]
  3476. return bboxes_shape, (num,), (num,)
  3477. def infer_dtype(self, bboxes_dtype):
  3478. validator.check_tensor_dtype_valid("bboxes", bboxes_dtype, [mstype.float16, mstype.float32], self.name)
  3479. return bboxes_dtype, mstype.int32, mstype.bool_
  3480. class Abs(PrimitiveWithInfer):
  3481. r"""
  3482. Returns absolute value of a tensor element-wise.
  3483. .. math::
  3484. out_i = |x_i|
  3485. Inputs:
  3486. - **x** (Tensor) - The input tensor. The shape of tensor is
  3487. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3488. Outputs:
  3489. Tensor, has the same shape as the `x`.
  3490. Raises:
  3491. TypeError: If `x` is not a Tensor.
  3492. Supported Platforms:
  3493. ``Ascend`` ``GPU`` ``CPU``
  3494. Examples:
  3495. >>> x = Tensor(np.array([-1.0, 1.0, 0.0]), mindspore.float32)
  3496. >>> abs = ops.Abs()
  3497. >>> output = abs(x)
  3498. >>> print(output)
  3499. [1. 1. 0.]
  3500. """
  3501. @prim_attr_register
  3502. def __init__(self):
  3503. """Initialize Abs"""
  3504. self.init_prim_io_names(inputs=['input_x'], outputs=['output'])
  3505. def infer_shape(self, x_shape):
  3506. return x_shape
  3507. def infer_dtype(self, x_type):
  3508. validator.check_tensor_dtype_valid('x', x_type, mstype.number_type, self.name)
  3509. return x_type
  3510. def infer_value(self, x):
  3511. if x is not None:
  3512. x = x.asnumpy()
  3513. out = np.array(np.abs(x, dtype=x.dtype))
  3514. return Tensor(out)
  3515. return None
  3516. class Sign(PrimitiveWithInfer):
  3517. r"""
  3518. Performs sign on the tensor element-wise.
  3519. .. math::
  3520. sign(x) = \begin{cases} -1, &if\ x < 0 \cr
  3521. 0, &if\ x = 0 \cr
  3522. 1, &if\ x > 0\end{cases}
  3523. Inputs:
  3524. - **x** (Tensor) - The input tensor.
  3525. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3526. Outputs:
  3527. Tensor, has the same shape and type as the `x`.
  3528. Raises:
  3529. TypeError: If `x` is not a Tensor.
  3530. Supported Platforms:
  3531. ``Ascend`` ``CPU`` ``GPU``
  3532. Examples:
  3533. >>> x = Tensor(np.array([[2.0, 0.0, -1.0]]), mindspore.float32)
  3534. >>> sign = ops.Sign()
  3535. >>> output = sign(x)
  3536. >>> print(output)
  3537. [[ 1. 0. -1.]]
  3538. """
  3539. @prim_attr_register
  3540. def __init__(self):
  3541. pass
  3542. def infer_shape(self, x_shape):
  3543. return x_shape
  3544. def infer_dtype(self, x_dtype):
  3545. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name)
  3546. return x_dtype
  3547. class Round(PrimitiveWithInfer):
  3548. r"""
  3549. Returns half to even of a tensor element-wise.
  3550. .. math::
  3551. out_i \approx x_i
  3552. Inputs:
  3553. - **x** (Tensor) - The input tensor.
  3554. Outputs:
  3555. Tensor, has the same shape and type as the `x`.
  3556. Raises:
  3557. TypeError: If `x` is not a Tensor.
  3558. Supported Platforms:
  3559. ``Ascend`` ``GPU`` ``CPU``
  3560. Examples:
  3561. >>> x = Tensor(np.array([0.8, 1.5, 2.3, 2.5, -4.5]), mindspore.float32)
  3562. >>> round = ops.Round()
  3563. >>> output = round(x)
  3564. >>> print(output)
  3565. [ 1. 2. 2. 2. -4.]
  3566. """
  3567. @prim_attr_register
  3568. def __init__(self):
  3569. """Initialize Round"""
  3570. self.init_prim_io_names(inputs=['input_x'], outputs=['output'])
  3571. def infer_shape(self, x_shape):
  3572. return x_shape
  3573. def infer_dtype(self, x_dtype):
  3574. validator.check_tensor_dtype_valid('x', x_dtype, mstype.number_type, self.name)
  3575. return x_dtype
  3576. class Tan(PrimitiveWithInfer):
  3577. r"""
  3578. Computes tangent of `x` element-wise.
  3579. .. math::
  3580. out_i = tan(x_i)
  3581. Inputs:
  3582. - **x** (Tensor) - The shape of tensor is
  3583. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3584. Data type must be float16, float32 or int32.
  3585. Outputs:
  3586. Tensor, has the same shape as `x`.
  3587. Raises:
  3588. TypeError: If dtype of `x` is not one of the following: float16, float32, int32.
  3589. TypeError: If `x` is not a Tensor.
  3590. Supported Platforms:
  3591. ``Ascend`` ``CPU``
  3592. Examples:
  3593. >>> tan = ops.Tan()
  3594. >>> x = Tensor(np.array([-1.0, 0.0, 1.0]), mindspore.float32)
  3595. >>> output = tan(x)
  3596. >>> print(output)
  3597. [-1.5574081 0. 1.5574081]
  3598. """
  3599. @prim_attr_register
  3600. def __init__(self):
  3601. """Initialize Tan"""
  3602. def infer_shape(self, x_shape):
  3603. return x_shape
  3604. def infer_dtype(self, x_type):
  3605. valid_dtypes = [mstype.float16, mstype.float32, mstype.int32]
  3606. validator.check_tensor_dtype_valid('x', x_type, valid_dtypes, self.name)
  3607. return x_type
  3608. class Atan(PrimitiveWithInfer):
  3609. r"""
  3610. Computes the trigonometric inverse tangent of the input element-wise.
  3611. .. math::
  3612. out_i = tan^{-1}(x_i)
  3613. Inputs:
  3614. - **x** (Tensor): The shape of tensor is
  3615. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3616. The data type should be one of the following types: float16, float32.
  3617. Outputs:
  3618. A Tensor, has the same type as the input.
  3619. Raises:
  3620. TypeError: If `x` is not a Tensor.
  3621. Supported Platforms:
  3622. ``Ascend`` ``GPU`` ``CPU``
  3623. Examples:
  3624. >>> x = Tensor(np.array([1.0, 0.0]), mindspore.float32)
  3625. >>> atan = ops.Atan()
  3626. >>> output = atan(x)
  3627. >>> print(output)
  3628. [0.7853982 0. ]
  3629. """
  3630. @prim_attr_register
  3631. def __init__(self):
  3632. pass
  3633. def infer_shape(self, x_shape):
  3634. return x_shape
  3635. def infer_dtype(self, x_type):
  3636. validator.check_tensor_dtype_valid('x', x_type, mstype.number_type, self.name)
  3637. return x_type
  3638. class Atanh(PrimitiveWithInfer):
  3639. r"""
  3640. Computes inverse hyperbolic tangent of the input element-wise.
  3641. .. math::
  3642. out_i = \tanh^{-1}(x_{i})
  3643. Inputs:
  3644. - **x** (Tensor): The shape of tensor is
  3645. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3646. Outputs:
  3647. A Tensor, has the same type as the input.
  3648. Raises:
  3649. TypeError: If `x` is not a Tensor.
  3650. Supported Platforms:
  3651. ``Ascend`` ``CPU``
  3652. Examples:
  3653. >>> x = Tensor(np.array([0, -0.5]), mindspore.float32)
  3654. >>> atanh = ops.Atanh()
  3655. >>> output = atanh(x)
  3656. >>> print(output)
  3657. [0. -0.54930614]
  3658. """
  3659. @prim_attr_register
  3660. def __init__(self):
  3661. pass
  3662. def infer_shape(self, x_shape):
  3663. return x_shape
  3664. def infer_dtype(self, x_type):
  3665. validator.check_tensor_dtype_valid('x', x_type, mstype.number_type, self.name)
  3666. return x_type
  3667. class Atan2(_MathBinaryOp):
  3668. r"""
  3669. Returns arctangent of x/y element-wise.
  3670. It returns :math:`\theta\ \in\ [-\pi, \pi]`
  3671. such that :math:`x = r*\sin(\theta), y = r*\cos(\theta)`, where :math:`r = \sqrt{x^2 + y^2}`.
  3672. Inputs of `x` and `y` comply with the implicit type conversion rules to make the data types consistent.
  3673. If they have different data types, lower priority data type will be converted to
  3674. relatively highest priority data type.
  3675. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  3676. Inputs:
  3677. - **x** (Tensor) - The input tensor.
  3678. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3679. The data type will give priority to the high-precision data type
  3680. - **y** (Tensor) - The input tensor.
  3681. It has the same shape with `x`. The data type will give priority to the high-precision data type.
  3682. Outputs:
  3683. Tensor, the shape is the same as the one after broadcasting,and the data type is same as `x`.
  3684. Raises:
  3685. TypeError: If `x` or `y` is not a Tensor.
  3686. Supported Platforms:
  3687. ``Ascend`` ``CPU`` ``GPU``
  3688. Examples:
  3689. >>> x = Tensor(np.array([0, 1]), mindspore.float32)
  3690. >>> y = Tensor(np.array([1, 1]), mindspore.float32)
  3691. >>> atan2 = ops.Atan2()
  3692. >>> output = atan2(x, y)
  3693. >>> print(output)
  3694. [0. 0.7853982]
  3695. """
  3696. class SquareSumAll(PrimitiveWithInfer):
  3697. r"""
  3698. Returns the square sum of a tensor element-wise
  3699. .. math::
  3700. \left\{\begin{matrix}out_{x} = {\textstyle \sum_{0}^{N}} (x_{i})^2
  3701. \\out_{y} = {\textstyle \sum_{0}^{N}} (y_{i})^2
  3702. \end{matrix}\right.
  3703. Inputs:
  3704. - **x** (Tensor) - The input tensor. The data type must be float16 or float32.
  3705. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3706. - **y** (Tensor) - The input tensor has the same type and shape as the `x`.
  3707. Note:
  3708. SquareSumAll only supports float16 and float32 data type.
  3709. Outputs:
  3710. - **output_y1** (Tensor) - The same type as the `x`.
  3711. - **output_y2** (Tensor) - The same type as the `x`.
  3712. Raises:
  3713. TypeError: If neither `x` nor `y` is a Tensor.
  3714. ValueError: If `x` and `y` are not the same shape.
  3715. Supported Platforms:
  3716. ``Ascend`` ``GPU``
  3717. Examples:
  3718. >>> x = Tensor(np.array([0, 0, 2, 0]), mindspore.float32)
  3719. >>> y = Tensor(np.array([0, 0, 2, 4]), mindspore.float32)
  3720. >>> square_sum_all = ops.SquareSumAll()
  3721. >>> output = square_sum_all(x, y)
  3722. >>> print(output)
  3723. (Tensor(shape=[], dtype=Float32, value= 4),
  3724. Tensor(shape=[], dtype=Float32, value= 20))
  3725. """
  3726. @prim_attr_register
  3727. def __init__(self):
  3728. """Initialize SquareSumAll"""
  3729. def infer_shape(self, x_shape, y_shape):
  3730. validator.check("x1_shape", x_shape, "x2_shape", y_shape, Rel.EQ, self.name)
  3731. return [], []
  3732. def infer_dtype(self, x_type, y_type):
  3733. valid_types = (mstype.float16, mstype.float32)
  3734. args = {"x1_type": x_type, "x2_type": y_type}
  3735. validator.check_tensors_dtypes_same_and_valid(args, valid_types, self.name)
  3736. return x_type, y_type
  3737. class BitwiseAnd(_BitwiseBinaryOp):
  3738. r"""
  3739. Returns bitwise `and` of two tensors element-wise.
  3740. .. math::
  3741. out_i = x_{i} \wedge y_{i}
  3742. Inputs of `x` and `y` comply with the implicit type conversion rules to
  3743. make the data types consistent.
  3744. If they have different data types, lower priority data type will be converted to
  3745. relatively highest priority data type.
  3746. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  3747. Inputs:
  3748. - **x** (Tensor) - The input tensor with int16, int32 or uint16 data type.
  3749. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3750. - **y** (Tensor) - The input tensor with same type as the `x`.
  3751. Outputs:
  3752. Tensor, has the same type as the `x`.
  3753. Raises:
  3754. TypeError: If `x` or `y` is not a Tensor.
  3755. Supported Platforms:
  3756. ``Ascend``
  3757. Examples:
  3758. >>> x = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mindspore.int16)
  3759. >>> y = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mindspore.int16)
  3760. >>> bitwise_and = ops.BitwiseAnd()
  3761. >>> output = bitwise_and(x, y)
  3762. >>> print(output)
  3763. [ 0 0 1 -1 1 0 1]
  3764. """
  3765. class BitwiseOr(_BitwiseBinaryOp):
  3766. r"""
  3767. Returns bitwise `or` of two tensors element-wise.
  3768. .. math::
  3769. out_i = x_{i} \mid y_{i}
  3770. Inputs of `x` and `y` comply with the implicit type conversion rules to
  3771. make the data types consistent.
  3772. If they have different data types, lower priority data type will be converted to
  3773. relatively highest priority data type.
  3774. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  3775. Inputs:
  3776. - **x** (Tensor) - The input tensor with int16, int32 or uint16 data type.
  3777. - **y** (Tensor) - The input tensor with same type as the `x`.
  3778. Outputs:
  3779. Tensor, has the same type as the `x`.
  3780. Raises:
  3781. TypeError: If `x` or `y` is not a Tensor.
  3782. Supported Platforms:
  3783. ``Ascend``
  3784. Examples:
  3785. >>> x = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mindspore.int16)
  3786. >>> y = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mindspore.int16)
  3787. >>> bitwise_or = ops.BitwiseOr()
  3788. >>> output = bitwise_or(x, y)
  3789. >>> print(output)
  3790. [ 0 1 1 -1 -1 3 3]
  3791. """
  3792. class BitwiseXor(_BitwiseBinaryOp):
  3793. r"""
  3794. Returns bitwise `xor` of two tensors element-wise.
  3795. .. math::
  3796. out_i = x_{i} \oplus y_{i}
  3797. Inputs of `x` and `y` comply with the implicit type conversion rules to
  3798. make the data types consistent.
  3799. If they have different data types, lower priority data type will be converted to
  3800. relatively highest priority data type.
  3801. RuntimeError exception will be thrown when the data type conversion of Parameter is required.
  3802. Inputs:
  3803. - **x** (Tensor) - The input tensor with int16, int32 or uint16 data type.
  3804. - **y** (Tensor) - The input tensor with same type as the `x`.
  3805. Outputs:
  3806. Tensor, has the same type as the `x`.
  3807. Raises:
  3808. TypeError: If `x` or `y` is not a Tensor.
  3809. Supported Platforms:
  3810. ``Ascend``
  3811. Examples:
  3812. >>> x = Tensor(np.array([0, 0, 1, -1, 1, 1, 1]), mindspore.int16)
  3813. >>> y = Tensor(np.array([0, 1, 1, -1, -1, 2, 3]), mindspore.int16)
  3814. >>> bitwise_xor = ops.BitwiseXor()
  3815. >>> output = bitwise_xor(x, y)
  3816. >>> print(output)
  3817. [ 0 1 0 0 -2 3 2]
  3818. """
  3819. class BesselI0e(PrimitiveWithInfer):
  3820. """
  3821. Computes BesselI0e of input element-wise.
  3822. Inputs:
  3823. - **x** (Tensor) - The shape of tensor is
  3824. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3825. Data type must be float16 or float32.
  3826. Outputs:
  3827. Tensor, has the same shape as `x`.
  3828. Raises:
  3829. TypeError: If `x` is not a Tensor.
  3830. Supported Platforms:
  3831. ``Ascend``
  3832. Examples:
  3833. >>> bessel_i0e = ops.BesselI0e()
  3834. >>> x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
  3835. >>> output = bessel_i0e(x)
  3836. >>> print(output)
  3837. [0.7979961 0.5144438 0.75117415 0.9157829 ]
  3838. """
  3839. @prim_attr_register
  3840. def __init__(self):
  3841. """Initialize BesselI0e"""
  3842. def infer_shape(self, x):
  3843. return x
  3844. def infer_dtype(self, x):
  3845. validator.check_tensor_dtype_valid('x', x, mstype.number_type, self.name)
  3846. return x
  3847. class BesselI1e(PrimitiveWithInfer):
  3848. """
  3849. Computes BesselI1e of input element-wise.
  3850. Inputs:
  3851. - **x** (Tensor) - The shape of tensor is
  3852. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3853. Data type must be float16 or float32.
  3854. Outputs:
  3855. Tensor, has the same shape as `x`.
  3856. Raises:
  3857. TypeError: If `x` is not a Tensor.
  3858. Supported Platforms:
  3859. ``Ascend``
  3860. Examples:
  3861. >>> bessel_i1e = ops.BesselI1e()
  3862. >>> x = Tensor(np.array([0.24, 0.83, 0.31, 0.09]), mindspore.float32)
  3863. >>> output = bessel_i1e(x)
  3864. >>> print(output)
  3865. [0.09507662 0.19699717 0.11505538 0.04116856]
  3866. """
  3867. @prim_attr_register
  3868. def __init__(self):
  3869. """Initialize BesselI1e"""
  3870. def infer_shape(self, x):
  3871. return x
  3872. def infer_dtype(self, x):
  3873. validator.check_tensor_dtype_valid('x', x, mstype.number_type, self.name)
  3874. return x
  3875. class Inv(PrimitiveWithInfer):
  3876. r"""
  3877. Computes Inv(Reciprocal) of input tensor element-wise.
  3878. .. math::
  3879. out_i = out_i = \frac{1}{x_{i} }
  3880. Inputs:
  3881. - **x** (Tensor) - The shape of tensor is
  3882. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3883. Must be one of the following types: float16, float32, int32.
  3884. Outputs:
  3885. Tensor, has the same shape and data type as `x`.
  3886. Raises:
  3887. TypeError: If dtype of `x` is not one of float16, float32, int32.
  3888. Supported Platforms:
  3889. ``Ascend``
  3890. Examples:
  3891. >>> inv = ops.Inv()
  3892. >>> x = Tensor(np.array([0.25, 0.4, 0.31, 0.52]), mindspore.float32)
  3893. >>> output = inv(x)
  3894. >>> print(output)
  3895. [4. 2.5 3.2258065 1.923077 ]
  3896. """
  3897. @prim_attr_register
  3898. def __init__(self):
  3899. pass
  3900. def infer_shape(self, x_shape):
  3901. return x_shape
  3902. def infer_dtype(self, x_dtype):
  3903. validator.check_tensor_dtype_valid('x_dtype', x_dtype, [mstype.float16, mstype.float32,
  3904. mstype.int32], self.name)
  3905. return x_dtype
  3906. class Invert(PrimitiveWithInfer):
  3907. r"""
  3908. Flips all bits of input tensor element-wise.
  3909. .. math::
  3910. out_i = -x_{i}
  3911. Inputs:
  3912. - **x** (Tensor[int16], Tensor[uint16]) - The shape of tensor is :math:`(x_1, x_2, ..., x_R)`.
  3913. Outputs:
  3914. Tensor, has the same shape as `x`.
  3915. Raises:
  3916. TypeError: If dtype of `x` is neither int16 nor uint16.
  3917. Supported Platforms:
  3918. ``Ascend``
  3919. Examples:
  3920. >>> invert = ops.Invert()
  3921. >>> x = Tensor(np.array([25, 4, 13, 9]), mindspore.int16)
  3922. >>> output = invert(x)
  3923. >>> print(output)
  3924. [-26 -5 -14 -10]
  3925. """
  3926. @prim_attr_register
  3927. def __init__(self):
  3928. pass
  3929. def infer_shape(self, x_shape):
  3930. return x_shape
  3931. def infer_dtype(self, x_dtype):
  3932. validator.check_tensor_dtype_valid('x_dtype', x_dtype, [mstype.int16, mstype.uint16], self.name)
  3933. return x_dtype
  3934. class Eps(PrimitiveWithInfer):
  3935. """
  3936. Creates a tensor filled with `x` dtype minimum value.
  3937. Inputs:
  3938. - **x** (Tensor) - Input tensor. The data type must be float16 or float32.
  3939. :math:`(N,*)` where :math:`*` means, any number of additional dimensions.
  3940. Outputs:
  3941. Tensor, has the same type and shape as `x`, but filled with `x` dtype minimum val.
  3942. Supported Platforms:
  3943. ``Ascend`` ``GPU`` ``CPU``
  3944. Examples:
  3945. >>> x = Tensor([4, 1, 2, 3], mindspore.float32)
  3946. >>> output = ops.Eps()(x)
  3947. >>> print(output)
  3948. [1.5258789e-05 1.5258789e-05 1.5258789e-05 1.5258789e-05]
  3949. """
  3950. @prim_attr_register
  3951. def __init__(self):
  3952. """Initialize Eps"""
  3953. self.init_prim_io_names(inputs=['input_x'], outputs=['y'])
  3954. def __infer__(self, input_x):
  3955. valid_dtypes = [mstype.float16, mstype.float32]
  3956. validator.check_tensor_dtype_valid('input_x', input_x['dtype'], valid_dtypes, self.name)
  3957. x_nptype = mstype.dtype_to_nptype(input_x['dtype'].element_type())
  3958. if x_nptype == np.float16:
  3959. min_val = 2 ** (-14)
  3960. else:
  3961. min_val = 2 ** (-16)
  3962. res = np.full(input_x['shape'], min_val, x_nptype)
  3963. out = {
  3964. 'value': Tensor(res),
  3965. 'shape': input_x['shape'],
  3966. 'dtype': input_x['dtype'],
  3967. }
  3968. return out
  3969. class LinSpace(PrimitiveWithInfer):
  3970. r"""
  3971. Generates values in an interval (inclusive of start and stop) and returns the corresponding
  3972. interpolated array with **num** number of ticks.
  3973. Inputs:
  3974. - **start** (Tensor[float32]) - Start value of interval, With shape of 0-D.
  3975. - **stop** (Tensor[float32]) - Last value of interval, With shape of 0-D.
  3976. - **num** (int) - Number of ticks in the interval, inclusive of start and stop.
  3977. Outputs:
  3978. Tensor, has the same shape as `start`.
  3979. Supported Platforms:
  3980. ``Ascend`` ``GPU``
  3981. Examples:
  3982. >>> linspace = ops.LinSpace()
  3983. >>> start = Tensor(1, mindspore.float32)
  3984. >>> stop = Tensor(10, mindspore.float32)
  3985. >>> num = 5
  3986. >>> output = linspace(start, stop, num)
  3987. >>> print(output)
  3988. [ 1. 3.25 5.5 7.75 10. ]
  3989. """
  3990. @prim_attr_register
  3991. def __init__(self):
  3992. """Initialize LinSpace"""
  3993. def __infer__(self, start, stop, num):
  3994. args = {"start": start['dtype'], "stop": start['dtype']}
  3995. validator.check_tensors_dtypes_same_and_valid(args, (mstype.float32,), self.name)
  3996. start_shape = start['shape']
  3997. stop_shape = stop['shape']
  3998. validator.check_equal_int(len(start_shape), 0, "rank of start_shape", self.name)
  3999. validator.check_equal_int(len(stop_shape), 0, "rank of stop_shape", self.name)
  4000. num_v = num['value']
  4001. validator.check_value_type('num', num_v, [int], self.name)
  4002. validator.check_positive_int(num_v, "num", self.name)
  4003. out_shape = [num_v]
  4004. out = {'shape': out_shape,
  4005. 'dtype': start['dtype'],
  4006. 'value': None}
  4007. return out
  4008. class MatrixInverse(PrimitiveWithInfer):
  4009. """
  4010. Returns the inverse of the input matrix. If the matrix is irreversible, an error may be reported or an unknown
  4011. result may be returned.
  4012. Note:
  4013. The parameter 'adjoint' is only supporting False right now. Because complex number is not supported at present.
  4014. Args:
  4015. adjoint (bool) : An optional bool. Default: False.
  4016. Inputs:
  4017. - **x** (Tensor) - A matrix to be calculated. The matrix must be at least two dimensions, and the last two
  4018. dimensions must be the same size. types: float32, float64.
  4019. Outputs:
  4020. Tensor, has the same type and shape as input `x`.
  4021. Raises:
  4022. TypeError: If `adjoint` is not a bool.
  4023. TypeError: If dtype of `x` is neither float32 nor float64.
  4024. ValueError: If the last two dimensions of `x` is not same size.
  4025. ValueError: If the dimension of `x` is less than 2.
  4026. Supported Platforms:
  4027. ``GPU``
  4028. Examples:
  4029. >>> x = Tensor(np.array([[[-0.710504 , -1.1207525],
  4030. ... [-1.7651395 , -1.7576632]],
  4031. ... [[ 0.52412605, 1.9070215],
  4032. ... [ 1.3384849 , 1.4274558]]]), mindspore.float32)
  4033. >>> matrix_inverse = ops.MatrixInverse(adjoint=False)
  4034. >>> output = matrix_inverse(x)
  4035. >>> print(output)
  4036. [[[ 2.4095483 -1.536419 ]
  4037. [-2.4197974 0.97401696]]
  4038. [[-0.79111797 1.0569006 ]
  4039. [ 0.74180895 -0.2904787 ]]]
  4040. """
  4041. @prim_attr_register
  4042. def __init__(self, adjoint=False):
  4043. """Initialize MatrixInverse"""
  4044. validator.check_type_name("adjoint", adjoint, False, self.name)
  4045. self.adjoint = adjoint
  4046. def infer_dtype(self, x_dtype):
  4047. valid_type = [mstype.float32, mstype.double]
  4048. validator.check_tensor_dtype_valid("x_dtype", x_dtype, valid_type, self.name)
  4049. return x_dtype
  4050. def infer_shape(self, x_shape):
  4051. validator.check_int(len(x_shape), 2, Rel.GE, self.name, None)
  4052. validator.check_equal_int(x_shape[-1], x_shape[-2], self.name, None)
  4053. return x_shape
  4054. class IndexAdd(Primitive):
  4055. """
  4056. Adds tensor y to specified axis and indices of tensor x. The axis should be in the range from 0 to len(x.dim) - 1,
  4057. and indices should be in the range from 0 to the size of x at the axis dimension.
  4058. Args:
  4059. axis (int): The dimension along which to index.
  4060. Inputs:
  4061. - **x** (Parameter) - The input tensor to add to.
  4062. - **indices** (Tensor) - The index of `x` on the `axis` th dimension to add to, with data type int32.
  4063. The `indices` must be 1D with the same size as the size of the `axis` th dimension of `y`. The values
  4064. of `indices` should be in the range of 0 to the size of the `axis` th dimension of `x`.
  4065. - **y** (Tensor) - The input tensor with the value to add. Must have same data type as `x`.
  4066. The shape must be the same as `x` except the `axis` th dimension.
  4067. Outputs:
  4068. Tensor, has the same shape and dtype as x.
  4069. Raises:
  4070. TypeError: If `x` is not a Tensor.
  4071. TypeError: If neither `indices` nor `y` is a Tensor.
  4072. ValueError: If axis is out of `x` rank's range.
  4073. ValueError: If `x` rank is not the same as `y` rank.
  4074. ValueError: If size of `indices` is not equal to dimension of y[axis].
  4075. ValueError: If `y`'s shape is not the same as `x` except the `axis` th dimension.
  4076. Supported Platforms:
  4077. ``Ascend`` ``GPU``
  4078. Examples:
  4079. >>> class Net(nn.Cell):
  4080. ... def __init__(self):
  4081. ... super(Net, self).__init__()
  4082. ... self.index_add = ops.IndexAdd(axis=1)
  4083. ... self.x = Parameter(Tensor(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), mindspore.float32))
  4084. ... self.indices = Tensor(np.array([0, 2]), mindspore.int32)
  4085. ...
  4086. ... def construct(self, y):
  4087. ... return self.index_add(self.x, self.indices, y)
  4088. ...
  4089. >>> y = Tensor(np.array([[0.5, 1.0], [1.0, 1.5], [2.0, 2.5]]), mindspore.float32)
  4090. >>> net = Net()
  4091. >>> output = net(y)
  4092. >>> print(output)
  4093. [[ 1.5 2. 4. ]
  4094. [ 5. 5. 7.5]
  4095. [ 9. 8. 11.5]]
  4096. """
  4097. __mindspore_signature__ = (
  4098. sig.make_sig('input_x', sig.sig_rw.RW_WRITE, dtype=sig.sig_dtype.T),
  4099. sig.make_sig('indices', dtype=sig.sig_dtype.T1),
  4100. sig.make_sig('input_y', dtype=sig.sig_dtype.T)
  4101. )
  4102. @prim_attr_register
  4103. def __init__(self, axis, use_lock=True, check_index_bound=True):
  4104. """Initialize InplaceAdd"""
  4105. self.init_prim_io_names(inputs=['input_x', 'indices', 'input_y'], outputs=['output'])
  4106. self.axis = axis
  4107. validator.check_value_type('axis', axis, [int], self.name)
  4108. class Erfinv(Primitive):
  4109. r"""
  4110. Computes the inverse error function of input. The inverse error function is defined in the range (-1, 1) as:
  4111. .. math::
  4112. erfinv(erf(x)) = x
  4113. Inputs:
  4114. - **input_x** (Tensor) - The input tensor to compute to, with data type float32, float16.
  4115. Outputs:
  4116. Tensor, has the same shape and dtype as `input_x`.
  4117. Raises:
  4118. TypeError: If dtype of `input_x` is not one of: float32, float16.
  4119. Supported Platforms:
  4120. ``Ascend``
  4121. Examples:
  4122. >>> x = Tensor(np.array([0, 0.5, -0.9]), mindspore.float32)
  4123. >>> erfinv = P.Erfinv()
  4124. >>> output = erfinv(x)
  4125. >>> print(output)
  4126. [ 0. 0.47695306 -1.1630805 ]
  4127. """
  4128. @prim_attr_register
  4129. def __init__(self):
  4130. """Initialize Erfinv"""
  4131. self.init_prim_io_names(inputs=['input_x'], outputs=['output'])