math.py 294 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160
  1. # Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
  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. math functions
  16. """
  17. import math
  18. import warnings
  19. import numpy as np
  20. import paddle
  21. from paddle import _C_ops
  22. from paddle.base.libpaddle import DataType
  23. from paddle.common_ops_import import VarDesc, dygraph_utils
  24. from paddle.pir import Value
  25. from paddle.utils.inplace_utils import inplace_apis_in_dygraph_only
  26. from ..base.data_feeder import (
  27. check_dtype,
  28. check_type,
  29. check_variable_and_dtype,
  30. convert_dtype,
  31. )
  32. from ..common_ops_import import Variable
  33. from ..framework import (
  34. LayerHelper,
  35. convert_np_dtype_to_dtype_,
  36. core,
  37. in_dynamic_mode,
  38. in_dynamic_or_pir_mode,
  39. in_pir_mode,
  40. )
  41. from .creation import _complex_to_real_dtype
  42. from .layer_function_generator import generate_layer_fn
  43. from .manipulation import cast, cast_
  44. from .ops import ( # noqa: F401
  45. abs,
  46. abs_,
  47. acos,
  48. acos_,
  49. acosh,
  50. acosh_,
  51. asin,
  52. asin_,
  53. asinh,
  54. asinh_,
  55. atan,
  56. atan_,
  57. atanh,
  58. atanh_,
  59. ceil,
  60. ceil_,
  61. cos,
  62. cos_,
  63. cosh,
  64. cosh_,
  65. erf,
  66. erf_,
  67. exp,
  68. exp_,
  69. expm1,
  70. expm1_,
  71. floor,
  72. floor_,
  73. reciprocal,
  74. reciprocal_,
  75. round,
  76. round_,
  77. rsqrt,
  78. rsqrt_,
  79. sigmoid,
  80. sigmoid_,
  81. sin,
  82. sin_,
  83. sinh,
  84. sinh_,
  85. sqrt,
  86. sqrt_,
  87. square,
  88. square_,
  89. tan,
  90. tan_,
  91. )
  92. __all__ = []
  93. _supported_int_dtype_ = [
  94. VarDesc.VarType.UINT8,
  95. VarDesc.VarType.INT8,
  96. VarDesc.VarType.INT16,
  97. VarDesc.VarType.INT32,
  98. VarDesc.VarType.INT64,
  99. ]
  100. _supported_float_dtype_ = [
  101. VarDesc.VarType.FP32,
  102. VarDesc.VarType.FP64,
  103. ]
  104. def _get_reduce_axis(axis, x):
  105. """
  106. Internal function for max, min, amax and amin.
  107. It computes the attribute reduce_all value based on axis.
  108. """
  109. if axis is not None and not isinstance(axis, list):
  110. if isinstance(axis, (tuple, range)):
  111. axis = list(axis)
  112. elif isinstance(axis, int):
  113. axis = [axis]
  114. else:
  115. raise TypeError(
  116. f"The type of axis must be int, list or tuple, but received {type(axis)}"
  117. )
  118. if axis is None:
  119. axis = []
  120. if axis == [] or len(axis) == len(x.shape):
  121. reduce_all = True
  122. else:
  123. reduce_all = False
  124. return reduce_all, axis
  125. def _get_reduce_axis_with_tensor(axis, x):
  126. if isinstance(axis, (Variable, paddle.pir.Value)):
  127. if axis.shape[0] == len(x.shape):
  128. reduce_all = True
  129. else:
  130. reduce_all = False
  131. else:
  132. reduce_all, axis = _get_reduce_axis(axis, x)
  133. if paddle.utils._contain_var(axis):
  134. axis = paddle.utils._convert_to_tensor_list(axis)
  135. return reduce_all, axis
  136. def log(x, name=None):
  137. r"""
  138. Calculates the natural log of the given input Tensor, element-wise.
  139. .. math::
  140. Out = \ln(x)
  141. Args:
  142. x (Tensor): Input Tensor. Must be one of the following types: int32, int64, float16, bfloat16, float32, float64, complex64, complex128.
  143. name (str|None): The default value is None. Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`
  144. Returns:
  145. Tensor: The natural log of the input Tensor computed element-wise.
  146. Examples:
  147. .. code-block:: python
  148. >>> import paddle
  149. >>> x = [[2, 3, 4], [7, 8, 9]]
  150. >>> x = paddle.to_tensor(x, dtype='float32')
  151. >>> print(paddle.log(x))
  152. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  153. [[0.69314718, 1.09861231, 1.38629436],
  154. [1.94591010, 2.07944155, 2.19722462]])
  155. """
  156. if in_dynamic_or_pir_mode():
  157. return _C_ops.log(x)
  158. else:
  159. check_variable_and_dtype(
  160. x,
  161. 'x',
  162. [
  163. 'int32',
  164. 'int64',
  165. 'uint16',
  166. 'float16',
  167. 'float32',
  168. 'float64',
  169. 'complex64',
  170. 'complex128',
  171. ],
  172. "log",
  173. )
  174. inputs = {'X': [x]}
  175. helper = LayerHelper('log', **locals())
  176. dtype = helper.input_dtype(input_param_name='x')
  177. out = helper.create_variable_for_type_inference(dtype)
  178. helper.append_op(type="log", inputs={"X": x}, outputs={"Out": out})
  179. return out
  180. @inplace_apis_in_dygraph_only
  181. def log_(x, name=None):
  182. r"""
  183. Inplace version of ``log`` API, the output Tensor will be inplaced with input ``x``.
  184. Please refer to :ref:`api_paddle_log`.
  185. """
  186. if in_dynamic_mode():
  187. return _C_ops.log_(x)
  188. def scale(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None):
  189. """
  190. Scale operator.
  191. Putting scale and bias to the input Tensor as following:
  192. ``bias_after_scale`` is True:
  193. .. math::
  194. Out=scale*X+bias
  195. ``bias_after_scale`` is False:
  196. .. math::
  197. Out=scale*(X+bias)
  198. Args:
  199. x (Tensor): Input N-D Tensor of scale operator. Data type can be float32, float64, int8, int16, int32, int64, uint8.
  200. scale (float|Tensor): The scale factor of the input, it should be a float number or a 0-D Tensor with shape [] and data type as float32.
  201. bias (float): The bias to be put on the input.
  202. bias_after_scale (bool): Apply bias addition after or before scaling. It is useful for numeric stability in some circumstances.
  203. act (str, optional): Activation applied to the output such as tanh, softmax, sigmoid, relu.
  204. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  205. Returns:
  206. Tensor: Output Tensor of scale operator, with shape and data type same as input.
  207. Examples:
  208. .. code-block:: python
  209. >>> # scale as a float32 number
  210. >>> import paddle
  211. >>> data = paddle.arange(6).astype("float32").reshape([2, 3])
  212. >>> print(data)
  213. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  214. [[0., 1., 2.],
  215. [3., 4., 5.]])
  216. >>> res = paddle.scale(data, scale=2.0, bias=1.0)
  217. >>> print(res)
  218. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  219. [[1. , 3. , 5. ],
  220. [7. , 9. , 11.]])
  221. .. code-block:: python
  222. >>> # scale with parameter scale as a Tensor
  223. >>> import paddle
  224. >>> data = paddle.arange(6).astype("float32").reshape([2, 3])
  225. >>> print(data)
  226. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  227. [[0., 1., 2.],
  228. [3., 4., 5.]])
  229. >>> factor = paddle.to_tensor([2], dtype='float32')
  230. >>> res = paddle.scale(data, scale=factor, bias=1.0)
  231. >>> print(res)
  232. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  233. [[1. , 3. , 5. ],
  234. [7. , 9. , 11.]])
  235. """
  236. if in_dynamic_mode():
  237. if act is None:
  238. return _C_ops.scale(x, scale, float(bias), bias_after_scale)
  239. out = _C_ops.scale(x, scale, float(bias), bias_after_scale)
  240. return dygraph_utils._append_activation_in_dygraph(out, act)
  241. elif in_pir_mode():
  242. if act is None:
  243. return _C_ops.scale(x, scale, float(bias), bias_after_scale)
  244. raise ValueError("act is not implement in pir of scale api.")
  245. else:
  246. check_variable_and_dtype(
  247. x,
  248. "x",
  249. [
  250. 'float16',
  251. 'bfloat16',
  252. 'uint16',
  253. 'float32',
  254. 'float64',
  255. 'int8',
  256. 'int16',
  257. 'int32',
  258. 'int64',
  259. 'uint8',
  260. 'complex64',
  261. 'complex128',
  262. ],
  263. "scale",
  264. )
  265. inputs = {'X': [x]}
  266. attrs = {
  267. 'bias': float(bias),
  268. 'bias_after_scale': bias_after_scale,
  269. }
  270. if isinstance(scale, Variable):
  271. inputs['ScaleTensor'] = [scale]
  272. else:
  273. attrs['scale'] = float(scale)
  274. helper = LayerHelper('scale', **locals())
  275. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  276. helper.append_op(
  277. type='scale', inputs=inputs, outputs={'Out': out}, attrs=attrs
  278. )
  279. return helper.append_activation(out)
  280. def stanh(x, scale_a=0.67, scale_b=1.7159, name=None):
  281. r"""
  282. stanh activation.
  283. .. math::
  284. out = b * \frac{e^{a * x} - e^{-a * x}}{e^{a * x} + e^{-a * x}}
  285. Parameters:
  286. x (Tensor): The input Tensor with data type float32, float64.
  287. scale_a (float, optional): The scale factor a of the input. Default is 0.67.
  288. scale_b (float, optional): The scale factor b of the output. Default is 1.7159.
  289. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  290. Returns:
  291. A Tensor with the same data type and shape as ``x`` .
  292. Examples:
  293. .. code-block:: python
  294. >>> import paddle
  295. >>> x = paddle.to_tensor([1.0, 2.0, 3.0, 4.0])
  296. >>> out = paddle.stanh(x, scale_a=0.67, scale_b=1.72)
  297. >>> print(out)
  298. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  299. [1.00616539, 1.49927628, 1.65933096, 1.70390463])
  300. """
  301. if in_dynamic_or_pir_mode():
  302. return _C_ops.stanh(x, scale_a, scale_b)
  303. else:
  304. check_variable_and_dtype(
  305. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'stanh'
  306. )
  307. helper = LayerHelper('stanh', **locals())
  308. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  309. helper.append_op(
  310. type='stanh',
  311. inputs={'X': x},
  312. outputs={'Out': out},
  313. attrs={'scale_a': scale_a, 'scale_b': scale_b},
  314. )
  315. return out
  316. def multiplex(inputs, index, name=None):
  317. """
  318. Based on the given index parameter, the OP selects a specific row from each input Tensor to construct the output Tensor.
  319. If the input of this OP contains :math:`m` Tensors, where :math:`I_{i}` means the i-th input Tensor, :math:`i` between :math:`[0,m)` .
  320. And :math:`O` means the output, where :math:`O[i]` means the i-th row of the output, then the output satisfies that :math:`O[i] = I_{index[i]}[i]` .
  321. For Example:
  322. .. code-block:: text
  323. Given:
  324. inputs = [[[0,0,3,4], [0,1,3,4], [0,2,4,4], [0,3,3,4]],
  325. [[1,0,3,4], [1,1,7,8], [1,2,4,2], [1,3,3,4]],
  326. [[2,0,3,4], [2,1,7,8], [2,2,4,2], [2,3,3,4]],
  327. [[3,0,3,4], [3,1,7,8], [3,2,4,2], [3,3,3,4]]]
  328. index = [[3],[0],[1],[2]]
  329. out = [[3,0,3,4], # out[0] = inputs[index[0]][0] = inputs[3][0] = [3,0,3,4]
  330. [0,1,3,4], # out[1] = inputs[index[1]][1] = inputs[0][1] = [0,1,3,4]
  331. [1,2,4,2], # out[2] = inputs[index[2]][2] = inputs[1][2] = [1,2,4,2]
  332. [2,3,3,4]] # out[3] = inputs[index[3]][3] = inputs[2][3] = [2,3,3,4]
  333. Args:
  334. inputs (list): The input Tensor list. The list elements are N-D Tensors of data types float32, float64, int32, int64, complex64, complex128. All input Tensor shapes should be the same and rank must be at least 2.
  335. index (Tensor): Used to select some rows in the input Tensor to construct an index of the output Tensor. It is a 2-D Tensor with data type int32 or int64 and shape [M, 1], where M is the number of input Tensors.
  336. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  337. Returns:
  338. Tensor: Output of multiplex OP, with data type being float32, float64, int32, int64.
  339. Examples:
  340. .. code-block:: python
  341. >>> import paddle
  342. >>> img1 = paddle.to_tensor([[1, 2], [3, 4]], dtype=paddle.float32)
  343. >>> img2 = paddle.to_tensor([[5, 6], [7, 8]], dtype=paddle.float32)
  344. >>> inputs = [img1, img2]
  345. >>> index = paddle.to_tensor([[1], [0]], dtype=paddle.int32)
  346. >>> res = paddle.multiplex(inputs, index)
  347. >>> print(res)
  348. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  349. [[5., 6.],
  350. [3., 4.]])
  351. """
  352. if in_dynamic_or_pir_mode():
  353. return _C_ops.multiplex(inputs, index)
  354. else:
  355. helper = LayerHelper('multiplex', **locals())
  356. check_type(inputs, 'inputs', (list), 'multiplex')
  357. if len(inputs) < 2:
  358. raise ValueError(
  359. "inputs should be a list object with at least 2 elements."
  360. )
  361. for id, x in enumerate(inputs):
  362. check_variable_and_dtype(
  363. x,
  364. 'input[' + str(id) + ']',
  365. [
  366. 'float32',
  367. 'float64',
  368. 'int32',
  369. 'int64',
  370. 'complex64',
  371. 'complex128',
  372. ],
  373. 'multiplex',
  374. )
  375. check_variable_and_dtype(
  376. index, "index", ['int32', 'int64'], 'multiplex'
  377. )
  378. out = helper.create_variable_for_type_inference(inputs[0].dtype)
  379. helper.append_op(
  380. type='multiplex',
  381. inputs={'X': inputs, 'Ids': index},
  382. outputs={'Out': [out]},
  383. )
  384. return out
  385. @inplace_apis_in_dygraph_only
  386. def scale_(x, scale=1.0, bias=0.0, bias_after_scale=True, act=None, name=None):
  387. """
  388. Inplace version of ``scale`` API, the output Tensor will be inplaced with input ``x``.
  389. Please refer to :ref:`api_paddle_scale`.
  390. """
  391. if in_dynamic_mode():
  392. return _C_ops.scale_(x, scale, float(bias), bias_after_scale)
  393. def pow(x, y, name=None):
  394. """
  395. Compute the power of Tensor elements. The equation is:
  396. .. math::
  397. out = x^{y}
  398. Note:
  399. ``paddle.pow`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  400. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  401. Args:
  402. x (Tensor): An N-D Tensor, the data type is float16, float32, float64, int32 or int64.
  403. y (float|int|Tensor): If it is an N-D Tensor, its data type should be the same as `x`.
  404. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  405. Returns:
  406. N-D Tensor. A location into which the result is stored. Its dimension and data type are the same as `x`.
  407. Examples:
  408. .. code-block:: python
  409. >>> import paddle
  410. >>> x = paddle.to_tensor([1, 2, 3], dtype='float32')
  411. >>> # example 1: y is a float or int
  412. >>> res = paddle.pow(x, 2)
  413. >>> print(res)
  414. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  415. [1., 4., 9.])
  416. >>> res = paddle.pow(x, 2.5)
  417. >>> print(res)
  418. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  419. [1. , 5.65685415 , 15.58845711])
  420. >>> # example 2: y is a Tensor
  421. >>> y = paddle.to_tensor([2], dtype='float32')
  422. >>> res = paddle.pow(x, y)
  423. >>> print(res)
  424. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  425. [1., 4., 9.])
  426. """
  427. # in dynamic graph mode
  428. if in_dynamic_or_pir_mode():
  429. if isinstance(y, (int, float)):
  430. return _C_ops.pow(x, y)
  431. elif isinstance(y, (paddle.Tensor, Variable, paddle.pir.Value)):
  432. return _C_ops.elementwise_pow(x, y)
  433. else:
  434. raise TypeError(
  435. f"y must be scalar, Tensor(in dygraph mode), Value(in pir mode) but received: {type(y)}"
  436. )
  437. else:
  438. # in static graph mode
  439. if isinstance(y, (int, float)):
  440. helper = LayerHelper('pow', **locals())
  441. inputs = {'X': x}
  442. attrs = {'factor': y}
  443. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  444. helper.append_op(
  445. type='pow', inputs=inputs, outputs={'Out': out}, attrs=attrs
  446. )
  447. return out
  448. elif isinstance(y, (paddle.Tensor, Variable)):
  449. # TODO A potential speed improvement is supporting different types in C++ and removing the cast ops here
  450. helper = LayerHelper('elementwise_pow', **locals())
  451. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  452. return _elementwise_op(LayerHelper('elementwise_pow', **locals()))
  453. else:
  454. raise TypeError(
  455. f"y must be scalar or tensor type, but received: {type(y)}"
  456. )
  457. @inplace_apis_in_dygraph_only
  458. def pow_(x, y, name=None):
  459. """
  460. Inplace version of ``pow`` API, the output Tensor will be inplaced with input ``x``.
  461. Please refer to :ref:`api_paddle_pow`.
  462. """
  463. if isinstance(y, (int, float)):
  464. return _C_ops.pow_(x, y)
  465. else:
  466. raise TypeError('y must be scalar type, but received: %s ' % (type(y)))
  467. OP_NAMEMAPPING = {
  468. 'elementwise_max': 'maximum',
  469. 'elementwise_min': 'minimum',
  470. 'elementwise_pow': 'elementwise_pow',
  471. 'elementwise_floordiv': 'floor_divide',
  472. 'elementwise_add': 'add',
  473. 'elementwise_sub': 'subtract',
  474. 'elementwise_mul': 'multiply',
  475. 'elementwise_div': 'divide',
  476. 'elementwise_mod': 'remainder',
  477. }
  478. def _elementwise_op(helper):
  479. op_type = helper.layer_type
  480. original_op_type = helper.kwargs.get('original_op_type', op_type)
  481. x = helper.kwargs.get('x', None)
  482. y = helper.kwargs.get('y', None)
  483. out = helper.kwargs.get('out', None)
  484. assert x is not None, f'x cannot be None in {original_op_type}'
  485. assert y is not None, f'y cannot be None in {original_op_type}'
  486. bf16_and_complex_supported_ops = [
  487. "elementwise_add",
  488. "elementwise_sub",
  489. "elementwise_mul",
  490. "elementwise_div",
  491. "elementwise_max",
  492. ]
  493. if original_op_type in bf16_and_complex_supported_ops:
  494. data_type = [
  495. 'uint16',
  496. 'float16',
  497. 'float32',
  498. 'float64',
  499. 'int32',
  500. 'int64',
  501. 'bool',
  502. 'complex64',
  503. 'complex128',
  504. ]
  505. else:
  506. data_type = [
  507. 'float16',
  508. 'uint16',
  509. 'float32',
  510. 'float64',
  511. 'int32',
  512. 'int64',
  513. 'bool',
  514. ]
  515. check_variable_and_dtype(
  516. x,
  517. 'x',
  518. data_type,
  519. original_op_type,
  520. )
  521. check_variable_and_dtype(
  522. y,
  523. 'y',
  524. data_type,
  525. original_op_type,
  526. )
  527. axis = helper.kwargs.get('axis', -1)
  528. name = helper.kwargs.get('name', None)
  529. if out is None:
  530. if name is None:
  531. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  532. else:
  533. out = helper.create_variable(
  534. name=name, dtype=x.dtype, persistable=False
  535. )
  536. helper.append_op(
  537. type=op_type,
  538. inputs={'X': x, 'Y': y},
  539. outputs={'Out': out},
  540. attrs={'axis': axis},
  541. )
  542. return helper.append_activation(out)
  543. def add(x, y, name=None):
  544. """
  545. Elementwise Add Operator.
  546. Add two tensors element-wise
  547. The equation is:
  548. .. math::
  549. Out=X+Y
  550. $X$ the tensor of any dimension.
  551. $Y$ the tensor whose dimensions must be less than or equal to the dimensions of $X$.
  552. This operator is used in the following cases:
  553. 1. The shape of $Y$ is the same with $X$.
  554. 2. The shape of $Y$ is a continuous subsequence of $X$.
  555. For example:
  556. .. code-block:: text
  557. shape(X) = (2, 3, 4, 5), shape(Y) = (,)
  558. shape(X) = (2, 3, 4, 5), shape(Y) = (5,)
  559. shape(X) = (2, 3, 4, 5), shape(Y) = (4, 5), with axis=-1(default) or axis=2
  560. shape(X) = (2, 3, 4, 5), shape(Y) = (3, 4), with axis=1
  561. shape(X) = (2, 3, 4, 5), shape(Y) = (2), with axis=0
  562. shape(X) = (2, 3, 4, 5), shape(Y) = (2, 1), with axis=0
  563. Args:
  564. x (Tensor): Tensor or LoDTensor of any dimensions. Its dtype should be int32, int64, float32, float64.
  565. y (Tensor): Tensor or LoDTensor of any dimensions. Its dtype should be int32, int64, float32, float64.
  566. name (string, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  567. Returns:
  568. N-D Tensor. A location into which the result is stored. It's dimension equals with x.
  569. Examples:
  570. .. code-block:: python
  571. >>> import paddle
  572. >>> x = paddle.to_tensor([2, 3, 4], 'float64')
  573. >>> y = paddle.to_tensor([1, 5, 2], 'float64')
  574. >>> z = paddle.add(x, y)
  575. >>> print(z)
  576. Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True,
  577. [3., 8., 6.])
  578. """
  579. if in_dynamic_or_pir_mode():
  580. return _C_ops.add(x, y)
  581. else:
  582. return _elementwise_op(LayerHelper('elementwise_add', **locals()))
  583. @inplace_apis_in_dygraph_only
  584. def add_(x, y, name=None):
  585. """
  586. Inplace version of ``add`` API, the output Tensor will be inplaced with input ``x``.
  587. Please refer to :ref:`api_paddle_add`.
  588. """
  589. out_shape = broadcast_shape(x.shape, y.shape)
  590. if out_shape != x.shape:
  591. raise ValueError(
  592. f"The shape of broadcast output {out_shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  593. )
  594. return _C_ops.add_(x, y)
  595. def logaddexp(x, y, name=None):
  596. """
  597. Elementwise LogAddExp Operator.
  598. Add of exponentiations of the inputs
  599. The equation is:
  600. .. math::
  601. Out=log(X.exp()+Y.exp())
  602. $X$ the tensor of any dimension.
  603. $Y$ the tensor whose dimensions must be less than or equal to the dimensions of $X$.
  604. There are two cases for this operator:
  605. 1. The shape of $Y$ is the same with $X$.
  606. 2. The shape of $Y$ is a continuous subsequence of $X$.
  607. For case 2:
  608. 1. Broadcast $Y$ to match the shape of $X$, where axis is the start dimension index for broadcasting $Y$ onto $X$.
  609. 2. If $axis$ is -1 (default), $axis$=rank($X$)-rank($Y$).
  610. 3. The trailing dimensions of size 1 for $Y$ will be ignored for the consideration of subsequence, such as shape($Y$) = (2, 1) => (2).
  611. For example:
  612. .. code-block:: text
  613. shape(X) = (2, 3, 4, 5), shape(Y) = (,)
  614. shape(X) = (2, 3, 4, 5), shape(Y) = (5,)
  615. shape(X) = (2, 3, 4, 5), shape(Y) = (4, 5), with axis=-1(default) or axis=2
  616. shape(X) = (2, 3, 4, 5), shape(Y) = (3, 4), with axis=1
  617. shape(X) = (2, 3, 4, 5), shape(Y) = (2), with axis=0
  618. shape(X) = (2, 3, 4, 5), shape(Y) = (2, 1), with axis=0
  619. Args:
  620. x (Tensor): Tensor or LoDTensor of any dimensions. Its dtype should be int32, int64, float32, float64, float16.
  621. y (Tensor): Tensor or LoDTensor of any dimensions. Its dtype should be int32, int64, float32, float64, float16.
  622. name (string, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  623. Returns:
  624. N-D Tensor. A location into which the result is stored. It's dimension equals with x.
  625. Examples:
  626. .. code-block:: python
  627. >>> import paddle
  628. >>> x = paddle.to_tensor([-1, -2, -3], 'float64')
  629. >>> y = paddle.to_tensor([-1], 'float64')
  630. >>> z = paddle.logaddexp(x, y)
  631. >>> print(z)
  632. Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True,
  633. [-0.30685282, -0.68673831, -0.87307199])
  634. """
  635. log_1p = paddle.log1p(paddle.exp(-paddle.abs(x - y)))
  636. maximum = paddle.maximum(x, y)
  637. if maximum.dtype == paddle.int32 or maximum.dtype == paddle.int64:
  638. maximum = maximum.astype(log_1p.dtype)
  639. return log_1p + maximum
  640. def subtract(x, y, name=None):
  641. """
  642. Subtract two tensors element-wise. The equation is:
  643. .. math::
  644. out = x - y
  645. Note:
  646. ``paddle.subtract`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  647. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  648. Args:
  649. x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
  650. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
  651. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  652. Returns:
  653. N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.
  654. Examples:
  655. .. code-block:: python
  656. >>> import paddle
  657. >>> x = paddle.to_tensor([[1, 2], [7, 8]])
  658. >>> y = paddle.to_tensor([[5, 6], [3, 4]])
  659. >>> res = paddle.subtract(x, y)
  660. >>> print(res)
  661. Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  662. [[-4, -4],
  663. [ 4, 4]])
  664. >>> x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]])
  665. >>> y = paddle.to_tensor([1, 0, 4])
  666. >>> res = paddle.subtract(x, y)
  667. >>> print(res)
  668. Tensor(shape=[1, 2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  669. [[[ 0, 2, -1],
  670. [ 0, 2, -1]]])
  671. >>> x = paddle.to_tensor([2, float('nan'), 5], dtype='float32')
  672. >>> y = paddle.to_tensor([1, 4, float('nan')], dtype='float32')
  673. >>> res = paddle.subtract(x, y)
  674. >>> print(res)
  675. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  676. [1. , nan, nan])
  677. >>> x = paddle.to_tensor([5, float('inf'), -float('inf')], dtype='float64')
  678. >>> y = paddle.to_tensor([1, 4, 5], dtype='float64')
  679. >>> res = paddle.subtract(x, y)
  680. >>> print(res)
  681. Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True,
  682. [ 4. , inf., -inf.])
  683. """
  684. if in_dynamic_or_pir_mode():
  685. return _C_ops.subtract(x, y)
  686. else:
  687. return _elementwise_op(LayerHelper('elementwise_sub', **locals()))
  688. @inplace_apis_in_dygraph_only
  689. def subtract_(x, y, name=None):
  690. """
  691. Inplace version of ``subtract`` API, the output Tensor will be inplaced with input ``x``.
  692. Please refer to :ref:`api_paddle_subtract`.
  693. """
  694. out_shape = broadcast_shape(x.shape, y.shape)
  695. if out_shape != x.shape:
  696. raise ValueError(
  697. f"The shape of broadcast output {out_shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  698. )
  699. return _C_ops.subtract_(x, y)
  700. def divide(x, y, name=None):
  701. """
  702. Divide two tensors element-wise. The equation is:
  703. .. math::
  704. out = x / y
  705. Note:
  706. ``paddle.divide`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  707. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  708. Args:
  709. x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
  710. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
  711. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  712. Returns:
  713. N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.
  714. Examples:
  715. .. code-block:: python
  716. >>> import paddle
  717. >>> x = paddle.to_tensor([2, 3, 4], dtype='float64')
  718. >>> y = paddle.to_tensor([1, 5, 2], dtype='float64')
  719. >>> z = paddle.divide(x, y)
  720. >>> print(z)
  721. Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True,
  722. [2. , 0.60000000, 2. ])
  723. """
  724. if in_dynamic_or_pir_mode():
  725. return _C_ops.divide(x, y)
  726. else:
  727. return _elementwise_op(LayerHelper('elementwise_div', **locals()))
  728. @inplace_apis_in_dygraph_only
  729. def divide_(x, y, name=None):
  730. r"""
  731. Inplace version of ``divide`` API, the output Tensor will be inplaced with input ``x``.
  732. Please refer to :ref:`api_paddle_divide`.
  733. """
  734. out_shape = broadcast_shape(x.shape, y.shape)
  735. if out_shape != x.shape:
  736. raise ValueError(
  737. f"The shape of broadcast output {out_shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  738. )
  739. return _C_ops.divide_(x, y)
  740. def floor_divide(x, y, name=None):
  741. """
  742. Floor divide two tensors element-wise and rounds the quotinents to the nearest integer toward zero. The equation is:
  743. .. math::
  744. out = trunc(x / y)
  745. - :math:`x`: Multidimensional Tensor.
  746. - :math:`y`: Multidimensional Tensor.
  747. Note:
  748. ``paddle.floor_divide`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  749. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  750. Also note that the name ``floor_divide`` can be misleading, as the quotinents are actually rounded toward zero, not toward negative infinite.
  751. Args:
  752. x (Tensor): the input tensor, it's data type should be uint8, int8, int32, int64, float32, float64, float16, bfloat16.
  753. y (Tensor): the input tensor, it's data type should be uint8, int8, int32, int64, float32, float64, float16, bfloat16.
  754. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  755. Returns:
  756. N-D Tensor. A location into which the result is stored. It's dimension equals with $x$.
  757. Examples:
  758. .. code-block:: python
  759. >>> import paddle
  760. >>> x = paddle.to_tensor([2, 3, 8, 7])
  761. >>> y = paddle.to_tensor([1, 5, 3, 3])
  762. >>> z = paddle.floor_divide(x, y)
  763. >>> print(z)
  764. Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
  765. [2, 0, 2, 2])
  766. """
  767. if in_dynamic_or_pir_mode():
  768. return _C_ops.floor_divide(x, y)
  769. else:
  770. return _elementwise_op(LayerHelper('elementwise_floordiv', **locals()))
  771. @inplace_apis_in_dygraph_only
  772. def floor_divide_(x, y, name=None):
  773. r"""
  774. Inplace version of ``floor_divide`` API, the output Tensor will be inplaced with input ``x``.
  775. Please refer to :ref:`api_paddle_floor_divide`.
  776. """
  777. out_shape = broadcast_shape(x.shape, y.shape)
  778. if out_shape != x.shape:
  779. raise ValueError(
  780. f"The shape of broadcast output {out_shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  781. )
  782. return _C_ops.floor_divide_(x, y)
  783. def remainder(x, y, name=None):
  784. r"""
  785. Mod two tensors element-wise. The equation is:
  786. .. math::
  787. out = x \% y
  788. Note:
  789. ``paddle.remainder`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  790. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  791. And `mod`, `floor_mod` are all functions with the same name
  792. Args:
  793. x (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64.
  794. y (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64.
  795. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  796. Returns:
  797. N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.
  798. Examples:
  799. .. code-block:: python
  800. >>> import paddle
  801. >>> x = paddle.to_tensor([2, 3, 8, 7])
  802. >>> y = paddle.to_tensor([1, 5, 3, 3])
  803. >>> z = paddle.remainder(x, y)
  804. >>> print(z)
  805. Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
  806. [0, 3, 2, 1])
  807. >>> z = paddle.floor_mod(x, y)
  808. >>> print(z)
  809. Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
  810. [0, 3, 2, 1])
  811. >>> z = paddle.mod(x, y)
  812. >>> print(z)
  813. Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
  814. [0, 3, 2, 1])
  815. """
  816. if in_dynamic_or_pir_mode():
  817. return _C_ops.remainder(x, y)
  818. else:
  819. return _elementwise_op(LayerHelper('elementwise_mod', **locals()))
  820. @inplace_apis_in_dygraph_only
  821. def remainder_(x, y, name=None):
  822. r"""
  823. Inplace version of ``remainder`` API, the output Tensor will be inplaced with input ``x``.
  824. Please refer to :ref:`api_paddle_remainder`.
  825. """
  826. out_shape = broadcast_shape(x.shape, y.shape)
  827. if out_shape != x.shape:
  828. raise ValueError(
  829. f"The shape of broadcast output {out_shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  830. )
  831. return _C_ops.remainder_(x, y)
  832. mod = remainder
  833. floor_mod = remainder
  834. mod_ = remainder_
  835. mod_.__doc__ = r"""
  836. Inplace version of ``mod`` API, the output Tensor will be inplaced with input ``x``.
  837. Please refer to :ref:`api_paddle_mod`.
  838. """
  839. floor_mod_ = remainder_
  840. floor_mod_.__doc__ = r"""
  841. Inplace version of ``floor_mod_`` API, the output Tensor will be inplaced with input ``x``.
  842. Please refer to :ref:`api_paddle_floor_mod_`.
  843. """
  844. def multiply(x, y, name=None):
  845. """
  846. multiply two tensors element-wise. The equation is:
  847. .. math::
  848. out = x * y
  849. Note:
  850. Supported shape of :attr:`x` and :attr:`y` for this operator:
  851. 1. `x.shape` == `y.shape`.
  852. 2. `x.shape` could be the continuous subsequence of `y.shape`.
  853. ``paddle.multiply`` supports broadcasting. If you would like to know more about broadcasting, please refer to `Introduction to Tensor`_ .
  854. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  855. Args:
  856. x (Tensor): the input tensor, its data type should be one of float32, float64, int32, int64, bool.
  857. y (Tensor): the input tensor, its data type should be one of float32, float64, int32, int64, bool.
  858. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  859. Returns:
  860. N-D Tensor. A location into which the result is stored. If :attr:`x`, :attr:`y` have different shapes and are "broadcastable", the resulting tensor shape is the shape of :attr:`x` and :attr:`y` after broadcasting. If :attr:`x`, :attr:`y` have the same shape, its shape is the same as :attr:`x` and :attr:`y`.
  861. Examples:
  862. .. code-block:: python
  863. >>> import paddle
  864. >>> x = paddle.to_tensor([[1, 2], [3, 4]])
  865. >>> y = paddle.to_tensor([[5, 6], [7, 8]])
  866. >>> res = paddle.multiply(x, y)
  867. >>> print(res)
  868. Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  869. [[5 , 12],
  870. [21, 32]])
  871. >>> x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]])
  872. >>> y = paddle.to_tensor([2])
  873. >>> res = paddle.multiply(x, y)
  874. >>> print(res)
  875. Tensor(shape=[1, 2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  876. [[[2, 4, 6],
  877. [2, 4, 6]]])
  878. """
  879. if in_dynamic_or_pir_mode():
  880. return _C_ops.multiply(x, y)
  881. else:
  882. return _elementwise_op(LayerHelper('elementwise_mul', **locals()))
  883. @inplace_apis_in_dygraph_only
  884. def multiply_(x, y, name=None):
  885. """
  886. Inplace version of ``multiply`` API, the output Tensor will be inplaced with input ``x``.
  887. Please refer to :ref:`api_paddle_multiply`.
  888. """
  889. out_shape = broadcast_shape(x.shape, y.shape)
  890. if out_shape != x.shape:
  891. raise ValueError(
  892. f"The shape of broadcast output {out_shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  893. )
  894. return _C_ops.multiply_(x, y)
  895. def _elementwise_op_with_axis(x, y, axis=-1, name=None, op_type="Undefined"):
  896. assert (
  897. in_dynamic_or_pir_mode()
  898. ), "You can only call `_elementwise_op_with_axis` function within in_dynamic_or_pir_mode"
  899. assert op_type in ["add", "subtract", "multiply", "divide"], (
  900. "op_name input error! _elementwise_op_with_axis is an inner function to replace elementwise_add/sub/mul/div. Input op_name=%s, Expect op_name=[add|subtract|multiply|divide]\n"
  901. % op_type
  902. )
  903. op = getattr(_C_ops, op_type)
  904. x_shape = list(x.shape)
  905. y_shape = list(y.shape)
  906. if axis == -1 or len(x_shape) == len(y_shape):
  907. return op(x, y)
  908. if len(x_shape) > len(y_shape):
  909. padding = len(x_shape) - len(y_shape) - axis
  910. y = paddle.reshape(y, [1] * axis + y_shape + [1] * padding)
  911. else:
  912. padding = len(y_shape) - len(x_shape) - axis
  913. x = paddle.reshape(x, [1] * axis + y_shape + [1] * padding)
  914. return op(x, y)
  915. def _add_with_axis(x, y, axis=-1, name=None):
  916. # opt performance, only dynamic mode needs reshape
  917. if in_dynamic_or_pir_mode():
  918. return _elementwise_op_with_axis(x, y, axis, name, "add")
  919. else:
  920. op_type = 'elementwise_add'
  921. return _elementwise_op(LayerHelper(op_type, **locals()))
  922. def _subtract_with_axis(x, y, axis=-1, name=None):
  923. # opt performance, only dynamic mode needs reshape
  924. if in_dynamic_or_pir_mode():
  925. return _elementwise_op_with_axis(x, y, axis, name, "subtract")
  926. else:
  927. op_type = 'elementwise_sub'
  928. return _elementwise_op(LayerHelper(op_type, **locals()))
  929. def _multiply_with_axis(x, y, axis=-1, name=None):
  930. # opt performance, only dynamic mode needs reshape
  931. if in_dynamic_or_pir_mode():
  932. return _elementwise_op_with_axis(x, y, axis, name, "multiply")
  933. else:
  934. op_type = 'elementwise_mul'
  935. return _elementwise_op(LayerHelper(op_type, **locals()))
  936. def _divide_with_axis(x, y, axis=-1, name=None):
  937. # opt performance, only dynamic mode needs reshape
  938. if in_dynamic_or_pir_mode():
  939. return _elementwise_op_with_axis(x, y, axis, name, "divide")
  940. else:
  941. op_type = 'elementwise_div'
  942. return _elementwise_op(LayerHelper(op_type, **locals()))
  943. def maximum(x, y, name=None):
  944. """
  945. Compare two tensors and returns a new tensor containing the element-wise maxima. The equation is:
  946. .. math::
  947. out = max(x, y)
  948. Note:
  949. ``paddle.maximum`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  950. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  951. Args:
  952. x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
  953. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
  954. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  955. Returns:
  956. N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.
  957. Examples:
  958. .. code-block:: python
  959. >>> import paddle
  960. >>> x = paddle.to_tensor([[1, 2], [7, 8]])
  961. >>> y = paddle.to_tensor([[3, 4], [5, 6]])
  962. >>> res = paddle.maximum(x, y)
  963. >>> print(res)
  964. Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  965. [[3, 4],
  966. [7, 8]])
  967. >>> x = paddle.to_tensor([[1, 2, 3], [1, 2, 3]])
  968. >>> y = paddle.to_tensor([3, 0, 4])
  969. >>> res = paddle.maximum(x, y)
  970. >>> print(res)
  971. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  972. [[3, 2, 4],
  973. [3, 2, 4]])
  974. >>> x = paddle.to_tensor([2, 3, 5], dtype='float32')
  975. >>> y = paddle.to_tensor([1, float("nan"), float("nan")], dtype='float32')
  976. >>> res = paddle.maximum(x, y)
  977. >>> print(res)
  978. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  979. [2. , nan, nan])
  980. >>> x = paddle.to_tensor([5, 3, float("inf")], dtype='float32')
  981. >>> y = paddle.to_tensor([1, -float("inf"), 5], dtype='float32')
  982. >>> res = paddle.maximum(x, y)
  983. >>> print(res)
  984. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  985. [5. , 3. , inf.])
  986. """
  987. if in_dynamic_or_pir_mode():
  988. return _C_ops.maximum(x, y)
  989. else:
  990. return _elementwise_op(LayerHelper('elementwise_max', **locals()))
  991. def minimum(x, y, name=None):
  992. """
  993. Compare two tensors and return a new tensor containing the element-wise minima. The equation is:
  994. .. math::
  995. out = min(x, y)
  996. Note:
  997. ``paddle.minimum`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  998. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  999. Args:
  1000. x (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
  1001. y (Tensor): the input tensor, it's data type should be float32, float64, int32, int64.
  1002. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1003. Returns:
  1004. Tensor. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.
  1005. Examples:
  1006. .. code-block:: python
  1007. >>> import paddle
  1008. >>> x = paddle.to_tensor([[1, 2], [7, 8]])
  1009. >>> y = paddle.to_tensor([[3, 4], [5, 6]])
  1010. >>> res = paddle.minimum(x, y)
  1011. >>> print(res)
  1012. Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1013. [[1, 2],
  1014. [5, 6]])
  1015. >>> x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]])
  1016. >>> y = paddle.to_tensor([3, 0, 4])
  1017. >>> res = paddle.minimum(x, y)
  1018. >>> print(res)
  1019. Tensor(shape=[1, 2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1020. [[[1, 0, 3],
  1021. [1, 0, 3]]])
  1022. >>> x = paddle.to_tensor([2, 3, 5], dtype='float32')
  1023. >>> y = paddle.to_tensor([1, float("nan"), float("nan")], dtype='float32')
  1024. >>> res = paddle.minimum(x, y)
  1025. >>> print(res)
  1026. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1027. [1. , nan, nan])
  1028. >>> x = paddle.to_tensor([5, 3, float("inf")], dtype='float64')
  1029. >>> y = paddle.to_tensor([1, -float("inf"), 5], dtype='float64')
  1030. >>> res = paddle.minimum(x, y)
  1031. >>> print(res)
  1032. Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True,
  1033. [ 1. , -inf., 5. ])
  1034. """
  1035. if in_dynamic_or_pir_mode():
  1036. return _C_ops.minimum(x, y)
  1037. else:
  1038. return _elementwise_op(LayerHelper('elementwise_min', **locals()))
  1039. def fmax(x, y, name=None):
  1040. """
  1041. Compares the elements at the corresponding positions of the two tensors and returns a new tensor containing the maximum value of the element.
  1042. If one of them is a nan value, the other value is directly returned, if both are nan values, then the first nan value is returned.
  1043. The equation is:
  1044. .. math::
  1045. out = fmax(x, y)
  1046. Note:
  1047. ``paddle.fmax`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  1048. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  1049. Args:
  1050. x (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64.
  1051. y (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64.
  1052. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1053. Returns:
  1054. N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.
  1055. Examples:
  1056. .. code-block:: python
  1057. >>> import paddle
  1058. >>> x = paddle.to_tensor([[1, 2], [7, 8]])
  1059. >>> y = paddle.to_tensor([[3, 4], [5, 6]])
  1060. >>> res = paddle.fmax(x, y)
  1061. >>> print(res)
  1062. Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1063. [[3, 4],
  1064. [7, 8]])
  1065. >>> x = paddle.to_tensor([[1, 2, 3], [1, 2, 3]])
  1066. >>> y = paddle.to_tensor([3, 0, 4])
  1067. >>> res = paddle.fmax(x, y)
  1068. >>> print(res)
  1069. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1070. [[3, 2, 4],
  1071. [3, 2, 4]])
  1072. >>> x = paddle.to_tensor([2, 3, 5], dtype='float32')
  1073. >>> y = paddle.to_tensor([1, float("nan"), float("nan")], dtype='float32')
  1074. >>> res = paddle.fmax(x, y)
  1075. >>> print(res)
  1076. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1077. [2., 3., 5.])
  1078. >>> x = paddle.to_tensor([5, 3, float("inf")], dtype='float32')
  1079. >>> y = paddle.to_tensor([1, -float("inf"), 5], dtype='float32')
  1080. >>> res = paddle.fmax(x, y)
  1081. >>> print(res)
  1082. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1083. [5. , 3. , inf.])
  1084. """
  1085. if in_dynamic_or_pir_mode():
  1086. return _C_ops.fmax(x, y)
  1087. else:
  1088. return _elementwise_op(LayerHelper('elementwise_fmax', **locals()))
  1089. def fmin(x, y, name=None):
  1090. """
  1091. Compares the elements at the corresponding positions of the two tensors and returns a new tensor containing the minimum value of the element.
  1092. If one of them is a nan value, the other value is directly returned, if both are nan values, then the first nan value is returned.
  1093. The equation is:
  1094. .. math::
  1095. out = fmin(x, y)
  1096. Note:
  1097. ``paddle.fmin`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  1098. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  1099. Args:
  1100. x (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64.
  1101. y (Tensor): the input tensor, it's data type should be float16, float32, float64, int32, int64.
  1102. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1103. Returns:
  1104. N-D Tensor. A location into which the result is stored. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.
  1105. Examples:
  1106. .. code-block:: python
  1107. >>> import paddle
  1108. >>> x = paddle.to_tensor([[1, 2], [7, 8]])
  1109. >>> y = paddle.to_tensor([[3, 4], [5, 6]])
  1110. >>> res = paddle.fmin(x, y)
  1111. >>> print(res)
  1112. Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1113. [[1, 2],
  1114. [5, 6]])
  1115. >>> x = paddle.to_tensor([[[1, 2, 3], [1, 2, 3]]])
  1116. >>> y = paddle.to_tensor([3, 0, 4])
  1117. >>> res = paddle.fmin(x, y)
  1118. >>> print(res)
  1119. Tensor(shape=[1, 2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1120. [[[1, 0, 3],
  1121. [1, 0, 3]]])
  1122. >>> x = paddle.to_tensor([2, 3, 5], dtype='float32')
  1123. >>> y = paddle.to_tensor([1, float("nan"), float("nan")], dtype='float32')
  1124. >>> res = paddle.fmin(x, y)
  1125. >>> print(res)
  1126. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1127. [1., 3., 5.])
  1128. >>> x = paddle.to_tensor([5, 3, float("inf")], dtype='float64')
  1129. >>> y = paddle.to_tensor([1, -float("inf"), 5], dtype='float64')
  1130. >>> res = paddle.fmin(x, y)
  1131. >>> print(res)
  1132. Tensor(shape=[3], dtype=float64, place=Place(cpu), stop_gradient=True,
  1133. [ 1. , -inf., 5. ])
  1134. """
  1135. if in_dynamic_or_pir_mode():
  1136. return _C_ops.fmin(x, y)
  1137. else:
  1138. return _elementwise_op(LayerHelper('elementwise_fmin', **locals()))
  1139. def sum(x, axis=None, dtype=None, keepdim=False, name=None):
  1140. """
  1141. Computes the sum of tensor elements over the given dimension.
  1142. Args:
  1143. x (Tensor): An N-D Tensor, the data type is bool, float16, float32, float64, int32 or int64.
  1144. axis (int|list|tuple, optional): The dimensions along which the sum is performed. If
  1145. :attr:`None`, sum all elements of :attr:`x` and return a
  1146. Tensor with a single element, otherwise must be in the
  1147. range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`,
  1148. the dimension to reduce is :math:`rank + axis[i]`.
  1149. dtype (str, optional): The dtype of output Tensor. The default value is None, the dtype
  1150. of output is the same as input Tensor `x`.
  1151. keepdim (bool, optional): Whether to reserve the reduced dimension in the
  1152. output Tensor. The result Tensor will have one fewer dimension
  1153. than the :attr:`x` unless :attr:`keepdim` is true, default
  1154. value is False.
  1155. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1156. Returns:
  1157. Tensor: Results of summation operation on the specified axis of input Tensor `x`,
  1158. if `x.dtype='bool'`, `x.dtype='int32'`, it's data type is `'int64'`,
  1159. otherwise it's data type is the same as `x`.
  1160. Examples:
  1161. .. code-block:: python
  1162. >>> import paddle
  1163. >>> # x is a Tensor with following elements:
  1164. >>> # [[0.2, 0.3, 0.5, 0.9]
  1165. >>> # [0.1, 0.2, 0.6, 0.7]]
  1166. >>> # Each example is followed by the corresponding output tensor.
  1167. >>> x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9],
  1168. ... [0.1, 0.2, 0.6, 0.7]])
  1169. >>> out1 = paddle.sum(x)
  1170. >>> out1
  1171. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  1172. 3.50000000)
  1173. >>> out2 = paddle.sum(x, axis=0)
  1174. >>> out2
  1175. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1176. [0.30000001, 0.50000000, 1.10000002, 1.59999990])
  1177. >>> out3 = paddle.sum(x, axis=-1)
  1178. >>> out3
  1179. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1180. [1.89999998, 1.60000002])
  1181. >>> out4 = paddle.sum(x, axis=1, keepdim=True)
  1182. >>> out4
  1183. Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
  1184. [[1.89999998],
  1185. [1.60000002]])
  1186. >>> # y is a Tensor with shape [2, 2, 2] and elements as below:
  1187. >>> # [[[1, 2], [3, 4]],
  1188. >>> # [[5, 6], [7, 8]]]
  1189. >>> # Each example is followed by the corresponding output tensor.
  1190. >>> y = paddle.to_tensor([[[1, 2], [3, 4]],
  1191. ... [[5, 6], [7, 8]]])
  1192. >>> out5 = paddle.sum(y, axis=[1, 2])
  1193. >>> out5
  1194. Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1195. [10, 26])
  1196. >>> out6 = paddle.sum(y, axis=[0, 1])
  1197. >>> out6
  1198. Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1199. [16, 20])
  1200. >>> # x is a Tensor with following elements:
  1201. >>> # [[True, True, True, True]
  1202. >>> # [False, False, False, False]]
  1203. >>> # Each example is followed by the corresponding output tensor.
  1204. >>> x = paddle.to_tensor([[True, True, True, True],
  1205. ... [False, False, False, False]])
  1206. >>> out7 = paddle.sum(x)
  1207. >>> out7
  1208. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  1209. 4)
  1210. >>> out8 = paddle.sum(x, axis=0)
  1211. >>> out8
  1212. Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
  1213. [1, 1, 1, 1])
  1214. >>> out9 = paddle.sum(x, axis=1)
  1215. >>> out9
  1216. Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1217. [4, 0])
  1218. """
  1219. dtype_flag = False
  1220. if dtype is not None:
  1221. dtype_flag = True
  1222. dtype = convert_np_dtype_to_dtype_(dtype)
  1223. if in_dynamic_or_pir_mode():
  1224. return _C_ops.sum(x, axis, dtype, keepdim)
  1225. else:
  1226. reduce_all, axis = _get_reduce_axis_with_tensor(axis, x)
  1227. attrs = {'dim': axis, 'keep_dim': keepdim}
  1228. if dtype_flag:
  1229. attrs.update({'in_dtype': x.dtype, 'out_dtype': dtype})
  1230. check_variable_and_dtype(
  1231. x,
  1232. 'x',
  1233. [
  1234. 'bool',
  1235. 'uint16',
  1236. 'int8',
  1237. 'uint8',
  1238. 'float16',
  1239. 'float32',
  1240. 'float64',
  1241. 'int16',
  1242. 'int32',
  1243. 'int64',
  1244. 'complex64',
  1245. 'complex128',
  1246. ],
  1247. 'sum',
  1248. )
  1249. check_type(
  1250. axis, 'axis', (int, list, tuple, type(None), Variable), 'sum'
  1251. )
  1252. helper = LayerHelper('sum', **locals())
  1253. if dtype_flag:
  1254. out = helper.create_variable_for_type_inference(dtype=dtype)
  1255. else:
  1256. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  1257. helper.append_op(
  1258. type='reduce_sum',
  1259. inputs={'X': x},
  1260. outputs={'Out': out},
  1261. attrs=attrs,
  1262. )
  1263. return out
  1264. def reduce_as(x, target, name=None):
  1265. """
  1266. Computes the sum of tensor elements make the shape of its result equal to the shape of target.
  1267. Args:
  1268. x (Tensor): An N-D Tensor, the data type is bool, float16, float32, float64, int8, uint8, int16, uint16, int32, int64, complex64 or complex128.
  1269. target (Tensor): An N-D Tensor, the length of x shape must greater than or equal to the length of target shape. The data type is bool, float16, float32, float64, int8, uint8, int16, uint16, int32, int64, complex64 or complex128.
  1270. Returns:
  1271. Tensor: The sum of the input tensor x along some axis has the same shape as the shape of the input tensor target, if `x.dtype='bool'`, `x.dtype='int32'`, it's data type is `'int64'`, otherwise it's data type is the same as `x`.
  1272. Examples:
  1273. .. code-block:: python
  1274. >>> import paddle
  1275. >>> x = paddle.to_tensor([[1, 2, 3, 4], [5, 6, 7, 8]])
  1276. >>> x
  1277. Tensor(shape=[2, 4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
  1278. [[1, 2, 3, 4],
  1279. [5, 6, 7, 8]])
  1280. >>> target = paddle.to_tensor([1, 2, 3, 4])
  1281. >>> target
  1282. Tensor(shape=[4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
  1283. [1, 2, 3, 4])
  1284. >>> res = paddle.reduce_as(x, target)
  1285. >>> res
  1286. Tensor(shape=[4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
  1287. [6 , 8 , 10, 12])
  1288. """
  1289. if in_dynamic_or_pir_mode():
  1290. return _C_ops.reduce_as(x, target)
  1291. else:
  1292. check_variable_and_dtype(
  1293. x,
  1294. 'x',
  1295. [
  1296. 'bool',
  1297. 'float16',
  1298. 'float32',
  1299. 'float64',
  1300. 'int8',
  1301. 'uint8',
  1302. 'int16',
  1303. 'uint16',
  1304. 'int32',
  1305. 'int64',
  1306. 'complex64',
  1307. 'complex128',
  1308. ],
  1309. 'reduce_as',
  1310. )
  1311. check_variable_and_dtype(
  1312. target,
  1313. 'target',
  1314. [
  1315. 'bool',
  1316. 'float16',
  1317. 'float32',
  1318. 'float64',
  1319. 'int8',
  1320. 'uint8',
  1321. 'int16',
  1322. 'uint16',
  1323. 'int32',
  1324. 'int64',
  1325. 'complex64',
  1326. 'complex128',
  1327. ],
  1328. 'reduce_as',
  1329. )
  1330. helper = LayerHelper('reduce_as', **locals())
  1331. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  1332. helper.append_op(
  1333. type='reduce_as',
  1334. inputs={'x': x, 'target': target},
  1335. outputs={'out': out},
  1336. )
  1337. return out
  1338. def nan_to_num(x, nan=0.0, posinf=None, neginf=None, name=None):
  1339. """
  1340. Replaces NaN, positive infinity, and negative infinity values in input tensor.
  1341. Args:
  1342. x (Tensor): An N-D Tensor, the data type is float32, float64.
  1343. nan (float, optional): the value to replace NaNs with. Default is 0.
  1344. posinf (float, optional): if a Number, the value to replace positive infinity values with. If None, positive infinity values are replaced with the greatest finite value representable by input’s dtype. Default is None.
  1345. neginf (float, optional): if a Number, the value to replace negative infinity values with. If None, negative infinity values are replaced with the lowest finite value representable by input’s dtype. Default is None.
  1346. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1347. Returns:
  1348. Tensor: Results of nan_to_num operation input Tensor ``x``.
  1349. Examples:
  1350. .. code-block:: python
  1351. >>> import paddle
  1352. >>> x = paddle.to_tensor([float('nan'), 0.3, float('+inf'), float('-inf')], dtype='float32')
  1353. >>> out1 = paddle.nan_to_num(x)
  1354. >>> out1
  1355. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1356. [ 0. ,
  1357. 0.30000001 ,
  1358. 340282346638528859811704183484516925440.,
  1359. -340282346638528859811704183484516925440.])
  1360. >>> out2 = paddle.nan_to_num(x, nan=1)
  1361. >>> out2
  1362. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1363. [ 1. ,
  1364. 0.30000001 ,
  1365. 340282346638528859811704183484516925440.,
  1366. -340282346638528859811704183484516925440.])
  1367. >>> out3 = paddle.nan_to_num(x, posinf=5)
  1368. >>> out3
  1369. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1370. [ 0. ,
  1371. 0.30000001 ,
  1372. 5. ,
  1373. -340282346638528859811704183484516925440.])
  1374. >>> out4 = paddle.nan_to_num(x, nan=10, neginf=-99)
  1375. >>> out4
  1376. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1377. [ 10. ,
  1378. 0.30000001 ,
  1379. 340282346638528859811704183484516925440.,
  1380. -99. ])
  1381. """
  1382. # NOTE(tiancaishaonvjituizi): it seems that paddle handles the dtype of python float number
  1383. # incorrectly, so we have to explicitly construct tensors here
  1384. posinf_value = paddle.full_like(x, float("+inf"))
  1385. neginf_value = paddle.full_like(x, float("-inf"))
  1386. nan = paddle.full_like(x, nan)
  1387. assert x.dtype in [
  1388. paddle.float32,
  1389. paddle.float64,
  1390. paddle.base.core.DataType.FLOAT32,
  1391. paddle.base.core.DataType.FLOAT64,
  1392. ]
  1393. is_float32 = (
  1394. x.dtype == paddle.float32
  1395. or x.dtype == paddle.base.core.DataType.FLOAT32
  1396. )
  1397. if posinf is None:
  1398. posinf = (
  1399. np.finfo(np.float32).max if is_float32 else np.finfo(np.float64).max
  1400. )
  1401. posinf = paddle.full_like(x, posinf)
  1402. if neginf is None:
  1403. neginf = (
  1404. np.finfo(np.float32).min if is_float32 else np.finfo(np.float64).min
  1405. )
  1406. neginf = paddle.full_like(x, neginf)
  1407. x = paddle.where(paddle.isnan(x), nan, x)
  1408. x = paddle.where(paddle.equal(x, posinf_value), posinf, x)
  1409. x = paddle.where(paddle.equal(x, neginf_value), neginf, x)
  1410. return x
  1411. @inplace_apis_in_dygraph_only
  1412. def nan_to_num_(x, nan=0.0, posinf=None, neginf=None, name=None):
  1413. r"""
  1414. Inplace version of ``nan_to_num`` API, the output Tensor will be inplaced with input ``x``.
  1415. Please refer to :ref:`api_paddle_nan_to_num`.
  1416. """
  1417. # NOTE(tiancaishaonvjituizi): it seems that paddle handles the dtype of python float number
  1418. # incorrectly, so we have to explicitly construct tensors here
  1419. posinf_value = paddle.full_like(x, float("+inf"))
  1420. neginf_value = paddle.full_like(x, float("-inf"))
  1421. nan = paddle.full_like(x, nan)
  1422. assert x.dtype in [paddle.float32, paddle.float64]
  1423. is_float32 = x.dtype == paddle.float32
  1424. if posinf is None:
  1425. posinf = (
  1426. np.finfo(np.float32).max if is_float32 else np.finfo(np.float64).max
  1427. )
  1428. posinf = paddle.full_like(x, posinf)
  1429. if neginf is None:
  1430. neginf = (
  1431. np.finfo(np.float32).min if is_float32 else np.finfo(np.float64).min
  1432. )
  1433. neginf = paddle.full_like(x, neginf)
  1434. x_not_nan = paddle.logical_not(paddle.isnan(x))
  1435. x = paddle.where_(x_not_nan, x, nan)
  1436. x = paddle.where_(x != posinf_value, x, posinf)
  1437. x = paddle.where_(x != neginf_value, x, neginf)
  1438. return x
  1439. def nansum(x, axis=None, dtype=None, keepdim=False, name=None):
  1440. """
  1441. Computes the sum of tensor elements over the given axis, treating Not a Numbers (NaNs) as zero.
  1442. Args:
  1443. x (Tensor): An N-D Tensor, the data type is float16, float32, float64, int32 or int64.
  1444. axis (int|list|tuple, optional): The dimensions along which the nansum is performed. If
  1445. :attr:`None`, nansum all elements of :attr:`x` and return a
  1446. Tensor with a single element, otherwise must be in the
  1447. range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`,
  1448. the dimension to reduce is :math:`rank + axis[i]`.
  1449. dtype (str, optional): The dtype of output Tensor. The default value is None, the dtype
  1450. of output is the same as input Tensor `x`.
  1451. keepdim (bool, optional): Whether to reserve the reduced dimension in the
  1452. output Tensor. The result Tensor will have one fewer dimension
  1453. than the :attr:`x` unless :attr:`keepdim` is true, default
  1454. value is False.
  1455. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1456. Returns:
  1457. Tensor: Results of summation operation on the specified axis of input Tensor `x`,
  1458. Examples:
  1459. .. code-block:: python
  1460. >>> import paddle
  1461. >>> # x is a Tensor with following elements:
  1462. >>> # [[nan, 0.3, 0.5, 0.9]
  1463. >>> # [0.1, 0.2, -nan, 0.7]]
  1464. >>> # Each example is followed by the corresponding output tensor.
  1465. >>> x = paddle.to_tensor([[float('nan'), 0.3, 0.5, 0.9],
  1466. ... [0.1, 0.2, float('-nan'), 0.7]],dtype="float32")
  1467. >>> out1 = paddle.nansum(x)
  1468. >>> out1
  1469. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  1470. 2.69999981)
  1471. >>> out2 = paddle.nansum(x, axis=0)
  1472. >>> out2
  1473. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1474. [0.10000000, 0.50000000, 0.50000000, 1.59999990])
  1475. >>> out3 = paddle.nansum(x, axis=-1)
  1476. >>> out3
  1477. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1478. [1.70000005, 1. ])
  1479. >>> out4 = paddle.nansum(x, axis=1, keepdim=True)
  1480. >>> out4
  1481. Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
  1482. [[1.70000005],
  1483. [1. ]])
  1484. >>> # y is a Tensor with shape [2, 2, 2] and elements as below:
  1485. >>> # [[[1, nan], [3, 4]],
  1486. >>> # [[5, 6], [-nan, 8]]]
  1487. >>> # Each example is followed by the corresponding output tensor.
  1488. >>> y = paddle.to_tensor([[[1, float('nan')], [3, 4]],
  1489. ... [[5, 6], [float('-nan'), 8]]])
  1490. >>> out5 = paddle.nansum(y, axis=[1, 2])
  1491. >>> out5
  1492. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1493. [8. , 19.])
  1494. >>> out6 = paddle.nansum(y, axis=[0, 1])
  1495. >>> out6
  1496. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1497. [9. , 18.])
  1498. """
  1499. check_variable_and_dtype(
  1500. x,
  1501. 'x',
  1502. ['float16', 'float32', 'float64', 'int32', 'int64', 'uint16'],
  1503. 'nansum',
  1504. )
  1505. check_type(axis, 'axis', (int, list, tuple, type(None)), 'nansum')
  1506. zero_tensor = paddle.zeros_like(x)
  1507. tmp_tensor = paddle.where(isnan(x), zero_tensor, x)
  1508. return sum(tmp_tensor, axis, dtype, keepdim, name)
  1509. def nanmean(x, axis=None, keepdim=False, name=None):
  1510. r"""
  1511. Compute the arithmetic mean along the specified axis, ignoring NaNs.
  1512. Args:
  1513. x (Tensor): The input Tensor with data type uint16, float16, float32, float64.
  1514. axis (int|list|tuple, optional):The axis along which to perform nanmean
  1515. calculations. ``axis`` should be int, list(int) or tuple(int). If
  1516. ``axis`` is a list/tuple of dimension(s), nanmean is calculated along
  1517. all element(s) of ``axis`` . ``axis`` or element(s) of ``axis``
  1518. should be in range [-D, D), where D is the dimensions of ``x`` . If
  1519. ``axis`` or element(s) of ``axis`` is less than 0, it works the
  1520. same way as :math:`axis + D` . If ``axis`` is None, nanmean is
  1521. calculated over all elements of ``x``. Default is None.
  1522. keepdim (bool, optional): Whether to reserve the reduced dimension(s)
  1523. in the output Tensor. If ``keepdim`` is True, the dimensions of
  1524. the output Tensor is the same as ``x`` except in the reduced
  1525. dimensions(it is of size 1 in this case). Otherwise, the shape of
  1526. the output Tensor is squeezed in ``axis`` . Default is False.
  1527. name (str, optional): Name for the operation (optional, default is None).
  1528. For more information, please refer to :ref:`api_guide_Name`.
  1529. Returns:
  1530. Tensor, results of arithmetic mean along ``axis`` of ``x``, with the same data
  1531. type as ``x``.
  1532. Examples:
  1533. .. code-block:: python
  1534. >>> import paddle
  1535. >>> # x is a 2-D Tensor:
  1536. >>> x = paddle.to_tensor([[float('nan'), 0.3, 0.5, 0.9],
  1537. ... [0.1, 0.2, float('-nan'), 0.7]])
  1538. >>> out1 = paddle.nanmean(x)
  1539. >>> out1
  1540. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  1541. 0.44999996)
  1542. >>> out2 = paddle.nanmean(x, axis=0)
  1543. >>> out2
  1544. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1545. [0.10000000, 0.25000000, 0.50000000, 0.79999995])
  1546. >>> out3 = paddle.nanmean(x, axis=0, keepdim=True)
  1547. >>> out3
  1548. Tensor(shape=[1, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1549. [[0.10000000, 0.25000000, 0.50000000, 0.79999995]])
  1550. >>> out4 = paddle.nanmean(x, axis=1)
  1551. >>> out4
  1552. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1553. [0.56666666, 0.33333334])
  1554. >>> out5 = paddle.nanmean(x, axis=1, keepdim=True)
  1555. >>> out5
  1556. Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
  1557. [[0.56666666],
  1558. [0.33333334]])
  1559. >>> # y is a 3-D Tensor:
  1560. >>> y = paddle.to_tensor([[[1, float('nan')], [3, 4]],
  1561. ... [[5, 6], [float('-nan'), 8]]])
  1562. >>> out6 = paddle.nanmean(y, axis=[1, 2])
  1563. >>> out6
  1564. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1565. [2.66666675, 6.33333349])
  1566. >>> out7 = paddle.nanmean(y, axis=[0, 1])
  1567. >>> out7
  1568. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1569. [3., 6.])
  1570. """
  1571. if isinstance(axis, int):
  1572. axis = [axis]
  1573. check_variable_and_dtype(
  1574. x, 'x/input', ['uint16', 'float16', 'float32', 'float64'], 'nanmean'
  1575. )
  1576. if axis is not None:
  1577. check_type(axis, 'axis/dim', (int, list, tuple), 'nanmean')
  1578. cnt = paddle.sum(~paddle.isnan(x), axis=axis, keepdim=keepdim)
  1579. return paddle.divide(
  1580. paddle.nansum(x, axis=axis, keepdim=keepdim, name=name),
  1581. cnt.astype(x.dtype),
  1582. )
  1583. def count_nonzero(x, axis=None, keepdim=False, name=None):
  1584. r"""
  1585. Counts the number of non-zero values in the tensor x along the specified axis.
  1586. Args:
  1587. x (Tensor): An N-D Tensor, the data type is bool, float16, float32, float64, int32 or int64.
  1588. axis (int|list|tuple, optional): The dimensions along which the sum is performed. If
  1589. :attr:`None`, sum all elements of :attr:`x` and return a
  1590. Tensor with a single element, otherwise must be in the
  1591. range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`,
  1592. the dimension to reduce is :math:`rank + axis[i]`.
  1593. keepdim (bool, optional): Whether to reserve the reduced dimension in the
  1594. output Tensor. The result Tensor will have one fewer dimension
  1595. than the :attr:`x` unless :attr:`keepdim` is true, default
  1596. value is False.
  1597. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1598. Returns:
  1599. Tensor: Results of count operation on the specified axis of input Tensor `x`, it's data type is `'int64'`.
  1600. Examples:
  1601. .. code-block:: python
  1602. >>> import paddle
  1603. >>> # x is a 2-D Tensor:
  1604. >>> x = paddle.to_tensor([[0., 1.1, 1.2], [0., 0., 1.3], [0., 0., 0.]])
  1605. >>> out1 = paddle.count_nonzero(x)
  1606. >>> out1
  1607. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  1608. 3)
  1609. >>> out2 = paddle.count_nonzero(x, axis=0)
  1610. >>> out2
  1611. Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1612. [0, 1, 2])
  1613. >>> out3 = paddle.count_nonzero(x, axis=0, keepdim=True)
  1614. >>> out3
  1615. Tensor(shape=[1, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1616. [[0, 1, 2]])
  1617. >>> out4 = paddle.count_nonzero(x, axis=1)
  1618. >>> out4
  1619. Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1620. [2, 1, 0])
  1621. >>> out5 = paddle.count_nonzero(x, axis=1, keepdim=True)
  1622. >>> out5
  1623. Tensor(shape=[3, 1], dtype=int64, place=Place(cpu), stop_gradient=True,
  1624. [[2],
  1625. [1],
  1626. [0]])
  1627. >>> # y is a 3-D Tensor:
  1628. >>> y = paddle.to_tensor([[[0., 1.1, 1.2], [0., 0., 1.3], [0., 0., 0.]],
  1629. ... [[0., 2.5, 2.6], [0., 0., 2.4], [2.1, 2.2, 2.3]]])
  1630. >>> out6 = paddle.count_nonzero(y, axis=[1, 2])
  1631. >>> out6
  1632. Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
  1633. [3, 6])
  1634. >>> out7 = paddle.count_nonzero(y, axis=[0, 1])
  1635. >>> out7
  1636. Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
  1637. [1, 3, 5])
  1638. """
  1639. if isinstance(axis, int):
  1640. axis = [axis]
  1641. bool_tensor = paddle.cast(x, 'bool')
  1642. int_tensor = paddle.cast(bool_tensor, 'int64')
  1643. return paddle.sum(int_tensor, axis=axis, keepdim=keepdim, name=name)
  1644. def add_n(inputs, name=None):
  1645. """
  1646. Sum one or more Tensor of the input.
  1647. For example:
  1648. .. code-block:: text
  1649. Case 1:
  1650. Input:
  1651. input.shape = [2, 3]
  1652. input = [[1, 2, 3],
  1653. [4, 5, 6]]
  1654. Output:
  1655. output.shape = [2, 3]
  1656. output = [[1, 2, 3],
  1657. [4, 5, 6]]
  1658. Case 2:
  1659. Input:
  1660. First input:
  1661. input1.shape = [2, 3]
  1662. Input1 = [[1, 2, 3],
  1663. [4, 5, 6]]
  1664. The second input:
  1665. input2.shape = [2, 3]
  1666. input2 = [[7, 8, 9],
  1667. [10, 11, 12]]
  1668. Output:
  1669. output.shape = [2, 3]
  1670. output = [[8, 10, 12],
  1671. [14, 16, 18]]
  1672. Args:
  1673. inputs (Tensor|list[Tensor]|tuple[Tensor]): A Tensor or a list/tuple of Tensors. The shape and data type of the list/tuple elements should be consistent.
  1674. Input can be multi-dimensional Tensor, and data types can be: float32, float64, int32, int64, complex64, complex128.
  1675. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1676. Returns:
  1677. Tensor, the sum of input :math:`inputs` , its shape and data types are consistent with :math:`inputs`.
  1678. Examples:
  1679. .. code-block:: python
  1680. >>> import paddle
  1681. >>> input0 = paddle.to_tensor([[1, 2, 3], [4, 5, 6]], dtype='float32')
  1682. >>> input1 = paddle.to_tensor([[7, 8, 9], [10, 11, 12]], dtype='float32')
  1683. >>> output = paddle.add_n([input0, input1])
  1684. >>> output
  1685. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  1686. [[8. , 10., 12.],
  1687. [14., 16., 18.]])
  1688. """
  1689. if in_dynamic_or_pir_mode():
  1690. if isinstance(inputs, (Variable, paddle.pir.Value)):
  1691. inputs = [inputs]
  1692. return _C_ops.add_n(inputs)
  1693. else:
  1694. helper = LayerHelper('add_n', **locals())
  1695. check_type(inputs, 'inputs', (Variable, tuple, list), 'add_n')
  1696. if isinstance(inputs, (list, tuple)):
  1697. if len(inputs) > 0:
  1698. for input in inputs:
  1699. check_variable_and_dtype(
  1700. input,
  1701. "inputs",
  1702. [
  1703. 'float16',
  1704. 'float32',
  1705. 'float64',
  1706. 'int32',
  1707. 'int64',
  1708. 'uint16',
  1709. 'complex64',
  1710. 'complex128',
  1711. ],
  1712. 'add_n',
  1713. )
  1714. else:
  1715. check_variable_and_dtype(
  1716. inputs,
  1717. "inputs",
  1718. [
  1719. 'float16',
  1720. 'float32',
  1721. 'float64',
  1722. 'int32',
  1723. 'int64',
  1724. 'uint16',
  1725. 'complex64',
  1726. 'complex128',
  1727. ],
  1728. 'add_n',
  1729. )
  1730. out = helper.create_variable_for_type_inference(
  1731. dtype=helper.input_dtype('inputs')
  1732. )
  1733. helper.append_op(
  1734. type='sum',
  1735. inputs={'X': inputs},
  1736. outputs={'Out': out},
  1737. attrs={},
  1738. )
  1739. return out
  1740. def trunc(input, name=None):
  1741. '''
  1742. This API is used to returns a new tensor with the truncated integer values of input.
  1743. Args:
  1744. input (Tensor): The input tensor, it's data type should be int32, int64, float32, float64.
  1745. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1746. Returns:
  1747. Tensor: The output Tensor of trunc.
  1748. Examples:
  1749. .. code-block:: python
  1750. >>> import paddle
  1751. >>> input = paddle.to_tensor([[0.1, 1.5], [-0.2, -2.4]], 'float32')
  1752. >>> output = paddle.trunc(input)
  1753. >>> output
  1754. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1755. [[ 0., 1.],
  1756. [-0., -2.]])
  1757. '''
  1758. if in_dynamic_or_pir_mode():
  1759. return _C_ops.trunc(input)
  1760. else:
  1761. inputs = {"X": input}
  1762. attrs = {}
  1763. helper = LayerHelper("trunc", **locals())
  1764. check_variable_and_dtype(
  1765. input, 'X', ['int32', 'int64', 'float32', 'float64'], 'trunc'
  1766. )
  1767. out = helper.create_variable_for_type_inference(dtype=input.dtype)
  1768. helper.append_op(
  1769. type="trunc", inputs=inputs, attrs=attrs, outputs={"Out": out}
  1770. )
  1771. return out
  1772. @inplace_apis_in_dygraph_only
  1773. def trunc_(input, name=None):
  1774. r"""
  1775. Inplace version of ``trunc`` API, the output Tensor will be inplaced with input ``x``.
  1776. Please refer to :ref:`api_paddle_trunc`.
  1777. """
  1778. if in_dynamic_mode():
  1779. return _C_ops.trunc_(input)
  1780. def mm(input, mat2, name=None):
  1781. """
  1782. Applies matrix multiplication to two tensors.
  1783. Currently, the input tensors' rank can be any, but when the rank of any
  1784. inputs is bigger than 3, this two inputs' rank should be equal.
  1785. Also note that if the raw tensor :math:`x` or :math:`mat2` is rank-1 and
  1786. nontransposed, the prepended or appended dimension :math:`1` will be
  1787. removed after matrix multiplication.
  1788. Args:
  1789. input (Tensor): The input tensor which is a Tensor.
  1790. mat2 (Tensor): The input tensor which is a Tensor.
  1791. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1792. Returns:
  1793. Tensor: The product Tensor.
  1794. ::
  1795. * example 1:
  1796. input: [B, ..., M, K], mat2: [B, ..., K, N]
  1797. out: [B, ..., M, N]
  1798. * example 2:
  1799. input: [B, M, K], mat2: [B, K, N]
  1800. out: [B, M, N]
  1801. * example 3:
  1802. input: [B, M, K], mat2: [K, N]
  1803. out: [B, M, N]
  1804. * example 4:
  1805. input: [M, K], mat2: [K, N]
  1806. out: [M, N]
  1807. * example 5:
  1808. input: [B, M, K], mat2: [K]
  1809. out: [B, M]
  1810. * example 6:
  1811. input: [K], mat2: [K]
  1812. out: [1]
  1813. Examples:
  1814. .. code-block:: python
  1815. >>> import paddle
  1816. >>> input = paddle.arange(1, 7).reshape((3, 2)).astype('float32')
  1817. >>> mat2 = paddle.arange(1, 9).reshape((2, 4)).astype('float32')
  1818. >>> out = paddle.mm(input, mat2)
  1819. >>> out
  1820. Tensor(shape=[3, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  1821. [[11., 14., 17., 20.],
  1822. [23., 30., 37., 44.],
  1823. [35., 46., 57., 68.]])
  1824. """
  1825. if in_dynamic_mode():
  1826. return _C_ops.matmul(input, mat2, False, False)
  1827. def __check_input(x, y):
  1828. var_names = {'x': x, 'y': y}
  1829. for name, val in var_names.items():
  1830. check_variable_and_dtype(
  1831. val, name, ['float16', 'float32', 'float64'], 'mm'
  1832. )
  1833. x_shape = list(x.shape)
  1834. y_shape = list(y.shape)
  1835. if len(x_shape) == 1:
  1836. x_shape = [1] + x_shape
  1837. if len(y_shape) == 1:
  1838. y_shape = y_shape + [1]
  1839. # check the inner 2 dimensions
  1840. if x_shape[-1] != y_shape[-2]:
  1841. if not ((x_shape[-1] == -1) or (y_shape[-2] == -1)):
  1842. raise ValueError(
  1843. "After performing an optional transpose, Input X's width should be "
  1844. "equal to Y's width for multiplication "
  1845. f"prerequisites. But received X's shape: {x_shape}, Y's shape: {y_shape}\n"
  1846. )
  1847. if len(y_shape) > 2 and len(x_shape) > 2:
  1848. for i, dim_x in enumerate(x_shape[:-2]):
  1849. # don't check neg shape
  1850. if dim_x < 0 or y_shape[i] < 0:
  1851. continue
  1852. if dim_x != y_shape[i]:
  1853. raise ValueError(
  1854. "When the matrix is larger than 2 dimensions, the higher "
  1855. "dimensional values of the two matrices need to be equal. "
  1856. "But received x_shape[%d] != y_shape[%d]. X's shape: %s, "
  1857. "Y's shape: %s.\n" % (i, i, x_shape, y_shape)
  1858. )
  1859. __check_input(input, mat2)
  1860. if in_pir_mode():
  1861. return _C_ops.matmul(input, mat2, False, False)
  1862. else:
  1863. helper = LayerHelper('mm', **locals())
  1864. out = helper.create_variable_for_type_inference(dtype=input.dtype)
  1865. helper.append_op(
  1866. type='matmul_v2',
  1867. inputs={'X': input, 'Y': mat2},
  1868. outputs={'Out': out},
  1869. )
  1870. return out
  1871. def addmm(input, x, y, beta=1.0, alpha=1.0, name=None):
  1872. """
  1873. **addmm**
  1874. Perform matrix multiplication for input $x$ and $y$.
  1875. $input$ is added to the final result.
  1876. The equation is:
  1877. .. math::
  1878. Out = alpha * x * y + beta * input
  1879. $Input$, $x$ and $y$ can carry the LoD (Level of Details) information, or not. But the output only shares the LoD information with input $input$.
  1880. Args:
  1881. input (Tensor): The input Tensor to be added to the final result.
  1882. x (Tensor): The first input Tensor for matrix multiplication.
  1883. y (Tensor): The second input Tensor for matrix multiplication.
  1884. beta (float, optional): Coefficient of $input$, default is 1.
  1885. alpha (float, optional): Coefficient of $x*y$, default is 1.
  1886. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  1887. Returns:
  1888. Tensor: The output Tensor of addmm.
  1889. Examples:
  1890. .. code-block:: python
  1891. >>> import paddle
  1892. >>> x = paddle.ones([2, 2])
  1893. >>> y = paddle.ones([2, 2])
  1894. >>> input = paddle.ones([2, 2])
  1895. >>> out = paddle.addmm(input=input, x=x, y=y, beta=0.5, alpha=5.0)
  1896. >>> print(out)
  1897. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  1898. [[10.50000000, 10.50000000],
  1899. [10.50000000, 10.50000000]])
  1900. """
  1901. input_shape = input.shape
  1902. x_shape = x.shape
  1903. y_shape = y.shape
  1904. if not len(x_shape) == len(y_shape) == 2:
  1905. raise ValueError(
  1906. f"The dimension of x, y should be 2 but receive x's shape: {x_shape}, y's shape: {y_shape}"
  1907. )
  1908. if x_shape[1] != y_shape[0]:
  1909. raise ValueError(
  1910. f"The input Variable x's width must be equal with Variable y' height. But received x's shape = {x_shape}, y's shape = {y_shape}."
  1911. )
  1912. if len(input_shape) == 2:
  1913. if input_shape[0] != x_shape[0]:
  1914. if input_shape[0] != 1:
  1915. raise ValueError(
  1916. f"When x's dimension[0] is not equal with input's dimension[0], input's dimension[0] must be 1 but got {input_shape[0]}"
  1917. )
  1918. if input_shape[1] != y_shape[1] and input_shape[1] != 1:
  1919. raise ValueError(
  1920. f"When y's dimension[1] is not equal with input's dimension[1], input's dimension[1] must be 1 but got {input_shape[1]}"
  1921. )
  1922. if input_shape[1] != y_shape[1]:
  1923. if input_shape[1] != 1:
  1924. raise ValueError(
  1925. f"When y's dimension[1] is not equal with input's dimension[1], input's dimension[1] must be 1 but got {input_shape[1]}"
  1926. )
  1927. elif len(input_shape) == 1:
  1928. if input_shape[0] not in (y_shape[1], 1):
  1929. raise ValueError(
  1930. f"The input's shape: {input_shape} is not broadcastable with [x.shape[0], y.shape[1]]: [{x_shape[0]},{y_shape[1]}]"
  1931. )
  1932. else:
  1933. raise ValueError(
  1934. f"The dimension of input should be 2 or 1 but receive input's shape: {input_shape}"
  1935. )
  1936. if in_dynamic_or_pir_mode():
  1937. return _C_ops.addmm(input, x, y, beta, alpha)
  1938. else:
  1939. inputs = {'Input': input, "X": x, "Y": y}
  1940. attrs = {'Alpha': alpha, 'Beta': beta}
  1941. helper = LayerHelper("addmm", **locals())
  1942. check_variable_and_dtype(
  1943. input, 'Input', ['float16', 'float32', 'float64', 'uint16'], 'addmm'
  1944. )
  1945. check_variable_and_dtype(
  1946. x, 'X', ['float16', 'float32', 'float64', 'uint16'], 'addmm'
  1947. )
  1948. check_variable_and_dtype(
  1949. y, 'Y', ['float16', 'float32', 'float64', 'uint16'], 'addmm'
  1950. )
  1951. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  1952. helper.append_op(
  1953. type="addmm", inputs=inputs, attrs=attrs, outputs={"Out": out}
  1954. )
  1955. return out
  1956. @inplace_apis_in_dygraph_only
  1957. def addmm_(input, x, y, beta=1.0, alpha=1.0, name=None):
  1958. """
  1959. Inplace version of ``addmm`` API, the output Tensor will be inplaced with input ``x``.
  1960. Please refer to :ref:`api_paddle_addmm`.
  1961. """
  1962. input_shape = input.shape
  1963. x_shape = x.shape
  1964. y_shape = y.shape
  1965. if not len(x_shape) == len(y_shape) == 2:
  1966. raise ValueError(
  1967. f"The dimension of x, y should be 2 but receive x's shape: {x_shape}, y's shape: {y_shape}"
  1968. )
  1969. if x_shape[1] != y_shape[0]:
  1970. raise ValueError(
  1971. f"The input Variable x's width must be equal with Variable y' height. But received x's shape = {x_shape}, y's shape = {y_shape}."
  1972. )
  1973. if len(input_shape) == 2:
  1974. if input_shape[0] != x_shape[0]:
  1975. if input_shape[0] != 1:
  1976. raise ValueError(
  1977. f"When x's dimension[0] is not equal with input's dimension[0], input's dimension[0] must be 1 but got {input_shape[0]}"
  1978. )
  1979. if input_shape[1] != y_shape[1] and input_shape[1] != 1:
  1980. raise ValueError(
  1981. f"When y's dimension[1] is not equal with input's dimension[1], input's dimension[1] must be 1 but got {input_shape[1]}"
  1982. )
  1983. if input_shape[1] != y_shape[1]:
  1984. if input_shape[1] != 1:
  1985. raise ValueError(
  1986. f"When y's dimension[1] is not equal with input's dimension[1], input's dimension[1] must be 1 but got {input_shape[1]}"
  1987. )
  1988. elif len(input_shape) == 1:
  1989. if input_shape[0] not in (y_shape[1], 1):
  1990. raise ValueError(
  1991. f"The input's shape: {input_shape} is not broadcastable with [x.shape[0], y.shape[1]]: [{x_shape[0]},{y_shape[1]}]"
  1992. )
  1993. else:
  1994. raise ValueError(
  1995. f"The dimension of input should be 2 or 1 but receive input's shape: {input_shape}"
  1996. )
  1997. if in_dynamic_mode():
  1998. return _C_ops.addmm_(input, x, y, beta, alpha)
  1999. def renorm(x, p, axis, max_norm):
  2000. """
  2001. **renorm**
  2002. This operator is used to calculate the p-norm along the axis,
  2003. suppose the input-shape on axis dimension has the value of T, then
  2004. the tensor is split into T parts, the p-norm should be calculated for each
  2005. part, if the p-norm for part i is larger than max-norm, then each element
  2006. in part i should be re-normalized at the same scale so that part-i' p-norm equals
  2007. max-norm exactly, otherwise part-i stays unchanged.
  2008. Args:
  2009. x (Tensor): The input Tensor
  2010. p (float): The power of the norm operation.
  2011. axis (int): the dimension to slice the tensor.
  2012. max-norm (float): the maximal norm limit.
  2013. Returns:
  2014. Tensor: the renorm Tensor.
  2015. Examples:
  2016. .. code-block:: python
  2017. >>> import paddle
  2018. >>> input = [[[2.0, 2, -2], [3, 0.3, 3]],
  2019. ... [[2, -8, 2], [3.1, 3.7, 3]]]
  2020. >>> x = paddle.to_tensor(input,dtype='float32')
  2021. >>> y = paddle.renorm(x, 1.0, 2, 2.05)
  2022. >>> print(y)
  2023. Tensor(shape=[2, 2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  2024. [[[ 0.40594056, 0.29285714, -0.41000000],
  2025. [ 0.60891086, 0.04392857, 0.61500001]],
  2026. [[ 0.40594056, -1.17142856, 0.41000000],
  2027. [ 0.62920785, 0.54178572, 0.61500001]]])
  2028. """
  2029. input_shape = x.shape
  2030. if not axis < len(input_shape):
  2031. raise ValueError(
  2032. f"the axis:{axis} should be less then the shape's size {len(input_shape)}:{input_shape}"
  2033. )
  2034. if not axis >= 0:
  2035. if not axis >= -1 * len(input_shape):
  2036. raise ValueError(
  2037. f"the axis:{axis} should not be less than -1 * length of input_shape:{-1 * len(input_shape)}"
  2038. )
  2039. axis = axis + len(input_shape)
  2040. if in_dynamic_or_pir_mode():
  2041. out = _C_ops.renorm(x, p, axis, max_norm)
  2042. return out
  2043. else:
  2044. check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'renorm')
  2045. inputs = {'X': x}
  2046. attrs = {'p': p, 'axis': axis, 'max_norm': max_norm}
  2047. helper = LayerHelper("renorm", **locals())
  2048. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  2049. helper.append_op(
  2050. type="renorm", inputs=inputs, attrs=attrs, outputs={"Out": out}
  2051. )
  2052. return out
  2053. @inplace_apis_in_dygraph_only
  2054. def renorm_(x, p, axis, max_norm):
  2055. """
  2056. Inplace version of ``renorm`` API, the output Tensor will be inplaced with input ``x``.
  2057. Please refer to :ref:`api_paddle_renorm`.
  2058. """
  2059. input_shape = x.shape
  2060. if not axis < len(input_shape):
  2061. raise ValueError(
  2062. f"the axis:{axis} should be less then the shape's size {len(input_shape)}:{input_shape}"
  2063. )
  2064. if not axis >= 0:
  2065. if not axis >= -1 * len(input_shape):
  2066. raise ValueError(
  2067. f"the axis:{axis} should not be less than -1 * length of input_shape:{-1 * len(input_shape)}"
  2068. )
  2069. axis = axis + len(input_shape)
  2070. if in_dynamic_mode():
  2071. out = _C_ops.renorm_(x, p, axis, max_norm)
  2072. return out
  2073. def inner(x, y, name=None):
  2074. """
  2075. Inner product of two input Tensor.
  2076. Ordinary inner product for 1-D Tensors, in higher dimensions a sum product over the last axes.
  2077. Args:
  2078. x (Tensor): An N-D Tensor or a Scalar Tensor. If its not a scalar Tensor, its last dimensions must match y's.
  2079. y (Tensor): An N-D Tensor or a Scalar Tensor. If its not a scalar Tensor, its last dimensions must match x's.
  2080. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2081. Returns:
  2082. Tensor: The inner-product Tensor, the output shape is x.shape[:-1] + y.shape[:-1].
  2083. Examples:
  2084. .. code-block:: python
  2085. >>> import paddle
  2086. >>> x = paddle.arange(1, 7).reshape((2, 3)).astype('float32')
  2087. >>> y = paddle.arange(1, 10).reshape((3, 3)).astype('float32')
  2088. >>> out = paddle.inner(x, y)
  2089. >>> print(out)
  2090. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  2091. [[14. , 32. , 50. ],
  2092. [32. , 77. , 122.]])
  2093. """
  2094. if in_dynamic_mode() and (x.size == 1 or y.size == 1):
  2095. return multiply(x, y)
  2096. else:
  2097. xshape = x.shape
  2098. yshape = y.shape
  2099. dstshape = list(xshape[:-1]) + list(yshape[:-1])
  2100. nx = x.reshape((-1, xshape[-1]))
  2101. ny = y.reshape((-1, yshape[-1]))
  2102. def __check_input(x, y):
  2103. var_names = {'x': x, 'y': y}
  2104. for name, val in var_names.items():
  2105. check_variable_and_dtype(
  2106. val, name, ['float16', 'float32', 'float64'], 'inner'
  2107. )
  2108. x_shape = list(xshape)
  2109. y_shape = list(yshape)
  2110. # check the inner 2 dimensions
  2111. if x_shape[-1] != y_shape[-1]:
  2112. if not ((x_shape[-1] == -1) or (y_shape[-1] == -1)):
  2113. raise ValueError(
  2114. "After performing an optional transpose, Input X's last dim should be "
  2115. "equal to Y's last dim for multiplication "
  2116. f"prerequisites. But received X's shape: {x_shape}, Y's shape: {y_shape}\n"
  2117. )
  2118. __check_input(nx, ny)
  2119. if in_dynamic_or_pir_mode():
  2120. return _C_ops.matmul(
  2121. nx, paddle.transpose(ny, [1, 0]), False, False
  2122. ).reshape(dstshape)
  2123. else:
  2124. helper = LayerHelper('inner', **locals())
  2125. out = helper.create_variable_for_type_inference(dtype=nx.dtype)
  2126. helper.append_op(
  2127. type='matmul_v2',
  2128. inputs={'X': nx, 'Y': ny.T},
  2129. outputs={'Out': out},
  2130. )
  2131. return out.reshape(dstshape)
  2132. def outer(x, y, name=None):
  2133. """
  2134. Outer product of two Tensors.
  2135. Input is flattened if not already 1-dimensional.
  2136. Args:
  2137. x (Tensor): An N-D Tensor or a Scalar Tensor.
  2138. y (Tensor): An N-D Tensor or a Scalar Tensor.
  2139. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2140. Returns:
  2141. Tensor: The outer-product Tensor.
  2142. Examples:
  2143. .. code-block:: python
  2144. >>> import paddle
  2145. >>> x = paddle.arange(1, 4).astype('float32')
  2146. >>> y = paddle.arange(1, 6).astype('float32')
  2147. >>> out = paddle.outer(x, y)
  2148. >>> print(out)
  2149. Tensor(shape=[3, 5], dtype=float32, place=Place(cpu), stop_gradient=True,
  2150. [[1. , 2. , 3. , 4. , 5. ],
  2151. [2. , 4. , 6. , 8. , 10.],
  2152. [3. , 6. , 9. , 12., 15.]])
  2153. """
  2154. nx = x.reshape((-1, 1))
  2155. ny = y.reshape((1, -1))
  2156. if in_dynamic_mode():
  2157. return _C_ops.matmul(nx, ny, False, False)
  2158. def __check_input(x, y):
  2159. var_names = {'x': x, 'y': y}
  2160. for name, val in var_names.items():
  2161. check_variable_and_dtype(
  2162. val,
  2163. name,
  2164. ['float16', 'float32', 'float64', 'int32', 'int64'],
  2165. 'outer',
  2166. )
  2167. __check_input(nx, ny)
  2168. if in_pir_mode():
  2169. return _C_ops.matmul(nx, ny, False, False)
  2170. else:
  2171. helper = LayerHelper('outer', **locals())
  2172. out = helper.create_variable_for_type_inference(dtype=nx.dtype)
  2173. helper.append_op(
  2174. type='matmul_v2', inputs={'X': nx, 'Y': ny}, outputs={'Out': out}
  2175. )
  2176. return out
  2177. def logsumexp(x, axis=None, keepdim=False, name=None):
  2178. r"""
  2179. Calculates the log of the sum of exponentials of ``x`` along ``axis`` .
  2180. .. math::
  2181. logsumexp(x) = \log\sum exp(x)
  2182. Args:
  2183. x (Tensor): The input Tensor with data type float16, float32 or float64, which
  2184. have no more than 4 dimensions.
  2185. axis (int|list|tuple, optional): The axis along which to perform
  2186. logsumexp calculations. ``axis`` should be int, list(int) or
  2187. tuple(int). If ``axis`` is a list/tuple of dimension(s), logsumexp
  2188. is calculated along all element(s) of ``axis`` . ``axis`` or
  2189. element(s) of ``axis`` should be in range [-D, D), where D is the
  2190. dimensions of ``x`` . If ``axis`` or element(s) of ``axis`` is
  2191. less than 0, it works the same way as :math:`axis + D` . If
  2192. ``axis`` is None, logsumexp is calculated along all elements of
  2193. ``x``. Default is None.
  2194. keepdim (bool, optional): Whether to reserve the reduced dimension(s)
  2195. in the output Tensor. If ``keep_dim`` is True, the dimensions of
  2196. the output Tensor is the same as ``x`` except in the reduced
  2197. dimensions(it is of size 1 in this case). Otherwise, the shape of
  2198. the output Tensor is squeezed in ``axis`` . Default is False.
  2199. name (str, optional): Name for the operation (optional, default is None).
  2200. For more information, please refer to :ref:`api_guide_Name`.
  2201. Returns:
  2202. Tensor, results of logsumexp along ``axis`` of ``x``, with the same data
  2203. type as ``x``.
  2204. Examples:
  2205. .. code-block:: python
  2206. >>> import paddle
  2207. >>> x = paddle.to_tensor([[-1.5, 0., 2.], [3., 1.2, -2.4]])
  2208. >>> out1 = paddle.logsumexp(x)
  2209. >>> out1
  2210. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  2211. 3.46912265)
  2212. >>> out2 = paddle.logsumexp(x, 1)
  2213. >>> out2
  2214. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  2215. [2.15317822, 3.15684605])
  2216. """
  2217. reduce_all, axis = _get_reduce_axis(axis, x)
  2218. if in_dynamic_or_pir_mode():
  2219. return _C_ops.logsumexp(x, axis, keepdim, reduce_all)
  2220. else:
  2221. check_variable_and_dtype(
  2222. x, 'x', ['float16', 'float32', 'float64', 'uint16'], 'logsumexp'
  2223. )
  2224. helper = LayerHelper('logsumexp', **locals())
  2225. attrs = {'axis': axis, 'keepdim': keepdim, 'reduce_all': reduce_all}
  2226. out = helper.create_variable_for_type_inference(x.dtype)
  2227. helper.append_op(
  2228. type='logsumexp', inputs={'X': x}, outputs={'Out': out}, attrs=attrs
  2229. )
  2230. return out
  2231. def inverse(x, name=None):
  2232. """
  2233. Takes the inverse of the square matrix. A square matrix is a matrix with
  2234. the same number of rows and columns. The input can be a square matrix
  2235. (2-D Tensor) or batches of square matrices.
  2236. Args:
  2237. x (Tensor): The input tensor. The last two
  2238. dimensions should be equal. When the number of dimensions is
  2239. greater than 2, it is treated as batches of square matrix. The data
  2240. type can be float32, float64, complex64, complex128.
  2241. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2242. Returns:
  2243. Tensor: A Tensor holds the inverse of x. The shape and data type
  2244. is the same as x.
  2245. Examples:
  2246. .. code-block:: python
  2247. >>> import paddle
  2248. >>> mat = paddle.to_tensor([[2, 0], [0, 2]], dtype='float32')
  2249. >>> inv = paddle.inverse(mat)
  2250. >>> print(inv)
  2251. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  2252. [[0.50000000, 0. ],
  2253. [0. , 0.50000000]])
  2254. """
  2255. if in_dynamic_or_pir_mode():
  2256. return _C_ops.inverse(x)
  2257. else:
  2258. def _check_input(x):
  2259. check_variable_and_dtype(
  2260. x,
  2261. 'x',
  2262. ['float32', 'float64', 'complex64', 'complex128'],
  2263. 'inverse',
  2264. )
  2265. if len(x.shape) < 2:
  2266. raise ValueError(
  2267. "The input of inverse is expected to be a Tensor whose number "
  2268. "of dimensions is no less than 2. But received: %d, "
  2269. "x's shape: %s." % (len(x.shape), x.shape)
  2270. )
  2271. _check_input(x)
  2272. helper = LayerHelper('inverse', **locals())
  2273. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  2274. helper.append_op(
  2275. type='inverse', inputs={'Input': [x]}, outputs={'Output': [out]}
  2276. )
  2277. return out
  2278. def max(x, axis=None, keepdim=False, name=None):
  2279. """
  2280. Computes the maximum of tensor elements over the given axis.
  2281. Note:
  2282. The difference between max and amax is: If there are multiple maximum elements,
  2283. amax evenly distributes gradient between these equal values,
  2284. while max propagates gradient to all of them.
  2285. Args:
  2286. x (Tensor): A tensor, the data type is float32, float64, int32, int64.
  2287. axis (int|list|tuple, optional): The axis along which the maximum is computed.
  2288. If :attr:`None`, compute the maximum over all elements of
  2289. `x` and return a Tensor with a single element,
  2290. otherwise must be in the range :math:`[-x.ndim(x), x.ndim(x))`.
  2291. If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`.
  2292. keepdim (bool, optional): Whether to reserve the reduced dimension in the
  2293. output Tensor. The result tensor will have one fewer dimension
  2294. than the `x` unless :attr:`keepdim` is true, default
  2295. value is False.
  2296. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2297. Returns:
  2298. Tensor, results of maximum on the specified axis of input tensor,
  2299. it's data type is the same as `x`.
  2300. Examples:
  2301. .. code-block:: python
  2302. >>> import paddle
  2303. >>> # data_x is a Tensor with shape [2, 4]
  2304. >>> # the axis is a int element
  2305. >>> x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9],
  2306. ... [0.1, 0.2, 0.6, 0.7]],
  2307. ... dtype='float64', stop_gradient=False)
  2308. >>> result1 = paddle.max(x)
  2309. >>> result1.backward()
  2310. >>> result1
  2311. Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=False,
  2312. 0.90000000)
  2313. >>> x.grad
  2314. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2315. [[0., 0., 0., 1.],
  2316. [0., 0., 0., 0.]])
  2317. >>> x.clear_grad()
  2318. >>> result2 = paddle.max(x, axis=0)
  2319. >>> result2.backward()
  2320. >>> result2
  2321. Tensor(shape=[4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2322. [0.20000000, 0.30000000, 0.60000000, 0.90000000])
  2323. >>> x.grad
  2324. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2325. [[1., 1., 0., 1.],
  2326. [0., 0., 1., 0.]])
  2327. >>> x.clear_grad()
  2328. >>> result3 = paddle.max(x, axis=-1)
  2329. >>> result3.backward()
  2330. >>> result3
  2331. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2332. [0.90000000, 0.70000000])
  2333. >>> x.grad
  2334. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2335. [[0., 0., 0., 1.],
  2336. [0., 0., 0., 1.]])
  2337. >>> x.clear_grad()
  2338. >>> result4 = paddle.max(x, axis=1, keepdim=True)
  2339. >>> result4.backward()
  2340. >>> result4
  2341. Tensor(shape=[2, 1], dtype=float64, place=Place(cpu), stop_gradient=False,
  2342. [[0.90000000],
  2343. [0.70000000]])
  2344. >>> x.grad
  2345. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2346. [[0., 0., 0., 1.],
  2347. [0., 0., 0., 1.]])
  2348. >>> # data_y is a Tensor with shape [2, 2, 2]
  2349. >>> # the axis is list
  2350. >>> y = paddle.to_tensor([[[1.0, 2.0], [3.0, 4.0]],
  2351. ... [[5.0, 6.0], [7.0, 8.0]]],
  2352. ... dtype='float64', stop_gradient=False)
  2353. >>> result5 = paddle.max(y, axis=[1, 2])
  2354. >>> result5.backward()
  2355. >>> result5
  2356. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2357. [4., 8.])
  2358. >>> y.grad
  2359. Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2360. [[[0., 0.],
  2361. [0., 1.]],
  2362. [[0., 0.],
  2363. [0., 1.]]])
  2364. >>> y.clear_grad()
  2365. >>> result6 = paddle.max(y, axis=[0, 1])
  2366. >>> result6.backward()
  2367. >>> result6
  2368. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2369. [7., 8.])
  2370. >>> y.grad
  2371. Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2372. [[[0., 0.],
  2373. [0., 0.]],
  2374. [[0., 0.],
  2375. [1., 1.]]])
  2376. """
  2377. if in_dynamic_or_pir_mode():
  2378. return _C_ops.max(x, axis, keepdim)
  2379. else:
  2380. reduce_all, axis = _get_reduce_axis_with_tensor(axis, x)
  2381. helper = LayerHelper('max', **locals())
  2382. check_variable_and_dtype(
  2383. x,
  2384. 'x',
  2385. ['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
  2386. 'max',
  2387. )
  2388. if not isinstance(axis, Variable) and paddle.utils._contain_var(axis):
  2389. axis = paddle.utils._convert_to_tensor_list(axis)
  2390. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  2391. helper.append_op(
  2392. type='reduce_max',
  2393. inputs={'X': x},
  2394. outputs={'Out': out},
  2395. attrs={'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all},
  2396. )
  2397. return out
  2398. def min(x, axis=None, keepdim=False, name=None):
  2399. """
  2400. Computes the minimum of tensor elements over the given axis
  2401. Note:
  2402. The difference between min and amin is: If there are multiple minimum elements,
  2403. amin evenly distributes gradient between these equal values,
  2404. while min propagates gradient to all of them.
  2405. Args:
  2406. x (Tensor): A tensor, the data type is float32, float64, int32, int64.
  2407. axis (int|list|tuple, optional): The axis along which the minimum is computed.
  2408. If :attr:`None`, compute the minimum over all elements of
  2409. `x` and return a Tensor with a single element,
  2410. otherwise must be in the range :math:`[-x.ndim, x.ndim)`.
  2411. If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`.
  2412. keepdim (bool, optional): Whether to reserve the reduced dimension in the
  2413. output Tensor. The result tensor will have one fewer dimension
  2414. than the `x` unless :attr:`keepdim` is true, default
  2415. value is False.
  2416. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2417. Returns:
  2418. Tensor, results of minimum on the specified axis of input tensor,
  2419. it's data type is the same as input's Tensor.
  2420. Examples:
  2421. .. code-block:: python
  2422. >>> import paddle
  2423. >>> # data_x is a Tensor with shape [2, 4]
  2424. >>> # the axis is a int element
  2425. >>> x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9],
  2426. ... [0.1, 0.2, 0.6, 0.7]],
  2427. ... dtype='float64', stop_gradient=False)
  2428. >>> result1 = paddle.min(x)
  2429. >>> result1.backward()
  2430. >>> result1
  2431. Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=False,
  2432. 0.10000000)
  2433. >>> x.grad
  2434. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2435. [[0., 0., 0., 0.],
  2436. [1., 0., 0., 0.]])
  2437. >>> x.clear_grad()
  2438. >>> result2 = paddle.min(x, axis=0)
  2439. >>> result2.backward()
  2440. >>> result2
  2441. Tensor(shape=[4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2442. [0.10000000, 0.20000000, 0.50000000, 0.70000000])
  2443. >>> x.grad
  2444. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2445. [[0., 0., 1., 0.],
  2446. [1., 1., 0., 1.]])
  2447. >>> x.clear_grad()
  2448. >>> result3 = paddle.min(x, axis=-1)
  2449. >>> result3.backward()
  2450. >>> result3
  2451. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2452. [0.20000000, 0.10000000])
  2453. >>> x.grad
  2454. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2455. [[1., 0., 0., 0.],
  2456. [1., 0., 0., 0.]])
  2457. >>> x.clear_grad()
  2458. >>> result4 = paddle.min(x, axis=1, keepdim=True)
  2459. >>> result4.backward()
  2460. >>> result4
  2461. Tensor(shape=[2, 1], dtype=float64, place=Place(cpu), stop_gradient=False,
  2462. [[0.20000000],
  2463. [0.10000000]])
  2464. >>> x.grad
  2465. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2466. [[1., 0., 0., 0.],
  2467. [1., 0., 0., 0.]])
  2468. >>> # data_y is a Tensor with shape [2, 2, 2]
  2469. >>> # the axis is list
  2470. >>> y = paddle.to_tensor([[[1.0, 2.0], [3.0, 4.0]],
  2471. ... [[5.0, 6.0], [7.0, 8.0]]],
  2472. ... dtype='float64', stop_gradient=False)
  2473. >>> result5 = paddle.min(y, axis=[1, 2])
  2474. >>> result5.backward()
  2475. >>> result5
  2476. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2477. [1., 5.])
  2478. >>> y.grad
  2479. Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2480. [[[1., 0.],
  2481. [0., 0.]],
  2482. [[1., 0.],
  2483. [0., 0.]]])
  2484. >>> y.clear_grad()
  2485. >>> result6 = paddle.min(y, axis=[0, 1])
  2486. >>> result6.backward()
  2487. >>> result6
  2488. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2489. [1., 2.])
  2490. >>> y.grad
  2491. Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2492. [[[1., 1.],
  2493. [0., 0.]],
  2494. [[0., 0.],
  2495. [0., 0.]]])
  2496. """
  2497. if in_dynamic_or_pir_mode():
  2498. return _C_ops.min(x, axis, keepdim)
  2499. else:
  2500. reduce_all, axis = _get_reduce_axis_with_tensor(axis, x)
  2501. helper = LayerHelper('min', **locals())
  2502. check_variable_and_dtype(
  2503. x,
  2504. 'x',
  2505. ['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
  2506. 'min',
  2507. )
  2508. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  2509. helper.append_op(
  2510. type='reduce_min',
  2511. inputs={'X': x},
  2512. outputs={'Out': out},
  2513. attrs={'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all},
  2514. )
  2515. return out
  2516. def amax(x, axis=None, keepdim=False, name=None):
  2517. """
  2518. Computes the maximum of tensor elements over the given axis.
  2519. Note:
  2520. The difference between max and amax is: If there are multiple maximum elements,
  2521. amax evenly distributes gradient between these equal values,
  2522. while max propagates gradient to all of them.
  2523. Args:
  2524. x (Tensor): A tensor, the data type is float32, float64, int32, int64,
  2525. the dimension is no more than 4.
  2526. axis (int|list|tuple, optional): The axis along which the maximum is computed.
  2527. If :attr:`None`, compute the maximum over all elements of
  2528. `x` and return a Tensor with a single element,
  2529. otherwise must be in the range :math:`[-x.ndim(x), x.ndim(x))`.
  2530. If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`.
  2531. keepdim (bool, optional): Whether to reserve the reduced dimension in the
  2532. output Tensor. The result tensor will have one fewer dimension
  2533. than the `x` unless :attr:`keepdim` is true, default
  2534. value is False.
  2535. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2536. Returns:
  2537. Tensor, results of maximum on the specified axis of input tensor,
  2538. it's data type is the same as `x`.
  2539. Examples:
  2540. .. code-block:: python
  2541. >>> import paddle
  2542. >>> # data_x is a Tensor with shape [2, 4] with multiple maximum elements
  2543. >>> # the axis is a int element
  2544. >>> x = paddle.to_tensor([[0.1, 0.9, 0.9, 0.9],
  2545. ... [0.9, 0.9, 0.6, 0.7]],
  2546. ... dtype='float64', stop_gradient=False)
  2547. >>> # There are 5 maximum elements:
  2548. >>> # 1) amax evenly distributes gradient between these equal values,
  2549. >>> # thus the corresponding gradients are 1/5=0.2;
  2550. >>> # 2) while max propagates gradient to all of them,
  2551. >>> # thus the corresponding gradient are 1.
  2552. >>> result1 = paddle.amax(x)
  2553. >>> result1.backward()
  2554. >>> result1
  2555. Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=False,
  2556. 0.90000000)
  2557. >>> x.grad
  2558. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2559. [[0. , 0.20000000, 0.20000000, 0.20000000],
  2560. [0.20000000, 0.20000000, 0. , 0. ]])
  2561. >>> x.clear_grad()
  2562. >>> result1_max = paddle.max(x)
  2563. >>> result1_max.backward()
  2564. >>> result1_max
  2565. Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=False,
  2566. 0.90000000)
  2567. >>> x.grad
  2568. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2569. [[0., 1., 1., 1.],
  2570. [1., 1., 0., 0.]])
  2571. >>> x.clear_grad()
  2572. >>> result2 = paddle.amax(x, axis=0)
  2573. >>> result2.backward()
  2574. >>> result2
  2575. Tensor(shape=[4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2576. [0.90000000, 0.90000000, 0.90000000, 0.90000000])
  2577. >>> x.grad
  2578. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2579. [[0. , 0.50000000, 1. , 1. ],
  2580. [1. , 0.50000000, 0. , 0. ]])
  2581. >>> x.clear_grad()
  2582. >>> result3 = paddle.amax(x, axis=-1)
  2583. >>> result3.backward()
  2584. >>> result3
  2585. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2586. [0.90000000, 0.90000000])
  2587. >>> x.grad
  2588. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2589. [[0. , 0.33333333, 0.33333333, 0.33333333],
  2590. [0.50000000, 0.50000000, 0. , 0. ]])
  2591. >>> x.clear_grad()
  2592. >>> result4 = paddle.amax(x, axis=1, keepdim=True)
  2593. >>> result4.backward()
  2594. >>> result4
  2595. Tensor(shape=[2, 1], dtype=float64, place=Place(cpu), stop_gradient=False,
  2596. [[0.90000000],
  2597. [0.90000000]])
  2598. >>> x.grad
  2599. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2600. [[0. , 0.33333333, 0.33333333, 0.33333333],
  2601. [0.50000000, 0.50000000, 0. , 0. ]])
  2602. >>> # data_y is a Tensor with shape [2, 2, 2]
  2603. >>> # the axis is list
  2604. >>> y = paddle.to_tensor([[[0.1, 0.9], [0.9, 0.9]],
  2605. ... [[0.9, 0.9], [0.6, 0.7]]],
  2606. ... dtype='float64', stop_gradient=False)
  2607. >>> result5 = paddle.amax(y, axis=[1, 2])
  2608. >>> result5.backward()
  2609. >>> result5
  2610. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2611. [0.90000000, 0.90000000])
  2612. >>> y.grad
  2613. Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2614. [[[0. , 0.33333333],
  2615. [0.33333333, 0.33333333]],
  2616. [[0.50000000, 0.50000000],
  2617. [0. , 0. ]]])
  2618. >>> y.clear_grad()
  2619. >>> result6 = paddle.amax(y, axis=[0, 1])
  2620. >>> result6.backward()
  2621. >>> result6
  2622. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2623. [0.90000000, 0.90000000])
  2624. >>> y.grad
  2625. Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2626. [[[0. , 0.33333333],
  2627. [0.50000000, 0.33333333]],
  2628. [[0.50000000, 0.33333333],
  2629. [0. , 0. ]]])
  2630. """
  2631. if in_dynamic_or_pir_mode():
  2632. return _C_ops.amax(x, axis, keepdim)
  2633. else:
  2634. reduce_all, axis = _get_reduce_axis(axis, x)
  2635. helper = LayerHelper('amax', **locals())
  2636. check_variable_and_dtype(
  2637. x, 'x', ['float32', 'float64', 'int32', 'int64'], 'amax'
  2638. )
  2639. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  2640. helper.append_op(
  2641. type='reduce_amax',
  2642. inputs={'X': x},
  2643. outputs={'Out': out},
  2644. attrs={'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all},
  2645. )
  2646. return out
  2647. def amin(x, axis=None, keepdim=False, name=None):
  2648. """
  2649. Computes the minimum of tensor elements over the given axis
  2650. Note:
  2651. The difference between min and amin is: If there are multiple minimum elements,
  2652. amin evenly distributes gradient between these equal values,
  2653. while min propagates gradient to all of them.
  2654. Args:
  2655. x (Tensor): A tensor, the data type is float32, float64, int32, int64,
  2656. the dimension is no more than 4.
  2657. axis (int|list|tuple, optional): The axis along which the minimum is computed.
  2658. If :attr:`None`, compute the minimum over all elements of
  2659. `x` and return a Tensor with a single element,
  2660. otherwise must be in the range :math:`[-x.ndim, x.ndim)`.
  2661. If :math:`axis[i] < 0`, the axis to reduce is :math:`x.ndim + axis[i]`.
  2662. keepdim (bool, optional): Whether to reserve the reduced dimension in the
  2663. output Tensor. The result tensor will have one fewer dimension
  2664. than the `x` unless :attr:`keepdim` is true, default
  2665. value is False.
  2666. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2667. Returns:
  2668. Tensor, results of minimum on the specified axis of input tensor,
  2669. it's data type is the same as input's Tensor.
  2670. Examples:
  2671. .. code-block:: python
  2672. >>> import paddle
  2673. >>> # data_x is a Tensor with shape [2, 4] with multiple minimum elements
  2674. >>> # the axis is a int element
  2675. >>> x = paddle.to_tensor([[0.2, 0.1, 0.1, 0.1],
  2676. ... [0.1, 0.1, 0.6, 0.7]],
  2677. ... dtype='float64', stop_gradient=False)
  2678. >>> # There are 5 minimum elements:
  2679. >>> # 1) amin evenly distributes gradient between these equal values,
  2680. >>> # thus the corresponding gradients are 1/5=0.2;
  2681. >>> # 2) while min propagates gradient to all of them,
  2682. >>> # thus the corresponding gradient are 1.
  2683. >>> result1 = paddle.amin(x)
  2684. >>> result1.backward()
  2685. >>> result1
  2686. Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=False,
  2687. 0.10000000)
  2688. >>> x.grad
  2689. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2690. [[0. , 0.20000000, 0.20000000, 0.20000000],
  2691. [0.20000000, 0.20000000, 0. , 0. ]])
  2692. >>> x.clear_grad()
  2693. >>> result1_min = paddle.min(x)
  2694. >>> result1_min.backward()
  2695. >>> result1_min
  2696. Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=False,
  2697. 0.10000000)
  2698. >>> x.grad
  2699. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2700. [[0., 1., 1., 1.],
  2701. [1., 1., 0., 0.]])
  2702. >>> x.clear_grad()
  2703. >>> result2 = paddle.amin(x, axis=0)
  2704. >>> result2.backward()
  2705. >>> result2
  2706. Tensor(shape=[4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2707. [0.10000000, 0.10000000, 0.10000000, 0.10000000])
  2708. >>> x.grad
  2709. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2710. [[0. , 0.50000000, 1. , 1. ],
  2711. [1. , 0.50000000, 0. , 0. ]])
  2712. >>> x.clear_grad()
  2713. >>> result3 = paddle.amin(x, axis=-1)
  2714. >>> result3.backward()
  2715. >>> result3
  2716. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2717. [0.10000000, 0.10000000])
  2718. >>> x.grad
  2719. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2720. [[0. , 0.33333333, 0.33333333, 0.33333333],
  2721. [0.50000000, 0.50000000, 0. , 0. ]])
  2722. >>> x.clear_grad()
  2723. >>> result4 = paddle.amin(x, axis=1, keepdim=True)
  2724. >>> result4.backward()
  2725. >>> result4
  2726. Tensor(shape=[2, 1], dtype=float64, place=Place(cpu), stop_gradient=False,
  2727. [[0.10000000],
  2728. [0.10000000]])
  2729. >>> x.grad
  2730. Tensor(shape=[2, 4], dtype=float64, place=Place(cpu), stop_gradient=False,
  2731. [[0. , 0.33333333, 0.33333333, 0.33333333],
  2732. [0.50000000, 0.50000000, 0. , 0. ]])
  2733. >>> # data_y is a Tensor with shape [2, 2, 2]
  2734. >>> # the axis is list
  2735. >>> y = paddle.to_tensor([[[0.2, 0.1], [0.1, 0.1]],
  2736. ... [[0.1, 0.1], [0.6, 0.7]]],
  2737. ... dtype='float64', stop_gradient=False)
  2738. >>> result5 = paddle.amin(y, axis=[1, 2])
  2739. >>> result5.backward()
  2740. >>> result5
  2741. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2742. [0.10000000, 0.10000000])
  2743. >>> y.grad
  2744. Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2745. [[[0. , 0.33333333],
  2746. [0.33333333, 0.33333333]],
  2747. [[0.50000000, 0.50000000],
  2748. [0. , 0. ]]])
  2749. >>> y.clear_grad()
  2750. >>> result6 = paddle.amin(y, axis=[0, 1])
  2751. >>> result6.backward()
  2752. >>> result6
  2753. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2754. [0.10000000, 0.10000000])
  2755. >>> y.grad
  2756. Tensor(shape=[2, 2, 2], dtype=float64, place=Place(cpu), stop_gradient=False,
  2757. [[[0. , 0.33333333],
  2758. [0.50000000, 0.33333333]],
  2759. [[0.50000000, 0.33333333],
  2760. [0. , 0. ]]])
  2761. """
  2762. if in_dynamic_or_pir_mode():
  2763. return _C_ops.amin(x, axis, keepdim)
  2764. else:
  2765. reduce_all, axis = _get_reduce_axis(axis, x)
  2766. helper = LayerHelper('amin', **locals())
  2767. check_variable_and_dtype(
  2768. x, 'x', ['float32', 'float64', 'int32', 'int64'], 'amin'
  2769. )
  2770. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  2771. helper.append_op(
  2772. type='reduce_amin',
  2773. inputs={'X': x},
  2774. outputs={'Out': out},
  2775. attrs={'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all},
  2776. )
  2777. return out
  2778. def log1p(x, name=None):
  2779. r"""
  2780. Calculates the natural log of the given input tensor, element-wise.
  2781. .. math::
  2782. Out = \ln(x+1)
  2783. Args:
  2784. x (Tensor): Input Tensor. Must be one of the following types: int32, int64, float16, bfloat16, float32, float64, complex64, complex128.
  2785. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2786. Returns:
  2787. Tensor, the natural log of the input Tensor computed element-wise.
  2788. Examples:
  2789. .. code-block:: python
  2790. >>> import paddle
  2791. >>> data = paddle.to_tensor([[0], [1]], dtype='float32')
  2792. >>> res = paddle.log1p(data)
  2793. >>> res
  2794. Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
  2795. [[0. ],
  2796. [0.69314718]])
  2797. """
  2798. if in_dynamic_or_pir_mode():
  2799. return _C_ops.log1p(x)
  2800. else:
  2801. check_variable_and_dtype(
  2802. x,
  2803. 'x',
  2804. [
  2805. 'int32',
  2806. 'int64',
  2807. 'float16',
  2808. 'uint16',
  2809. 'float32',
  2810. 'float64',
  2811. 'complex64',
  2812. 'complex128',
  2813. ],
  2814. "log1p",
  2815. )
  2816. inputs = {'X': [x]}
  2817. helper = LayerHelper('log1p', **locals())
  2818. dtype = helper.input_dtype(input_param_name='x')
  2819. out = helper.create_variable_for_type_inference(dtype)
  2820. helper.append_op(type="log1p", inputs={"X": x}, outputs={"Out": out})
  2821. return out
  2822. @inplace_apis_in_dygraph_only
  2823. def log1p_(x, name=None):
  2824. r"""
  2825. Inplace version of ``log1p`` API, the output Tensor will be inplaced with input ``x``.
  2826. Please refer to :ref:`api_paddle_log1p`.
  2827. """
  2828. if in_dynamic_mode():
  2829. return _C_ops.log1p_(x)
  2830. def log2(x, name=None):
  2831. r"""
  2832. Calculates the log to the base 2 of the given input tensor, element-wise.
  2833. .. math::
  2834. Out = \log_2x
  2835. Args:
  2836. x (Tensor): Input tensor must be one of the following types: int32, int64, float16, bfloat16, float32, float64, complex64, complex128.
  2837. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2838. Returns:
  2839. Tensor: The log to the base 2 of the input Tensor computed element-wise.
  2840. Examples:
  2841. .. code-block:: python
  2842. >>> import paddle
  2843. >>> # example 1: x is a float
  2844. >>> x_i = paddle.to_tensor([[1.0], [2.0]])
  2845. >>> res = paddle.log2(x_i)
  2846. >>> res
  2847. Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
  2848. [[0.],
  2849. [1.]])
  2850. >>> # example 2: x is float32
  2851. >>> x_i = paddle.full(shape=[1], fill_value=2, dtype='float32')
  2852. >>> paddle.to_tensor(x_i)
  2853. >>> res = paddle.log2(x_i)
  2854. >>> res
  2855. Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
  2856. [1.])
  2857. >>> # example 3: x is float64
  2858. >>> x_i = paddle.full(shape=[1], fill_value=2, dtype='float64')
  2859. >>> paddle.to_tensor(x_i)
  2860. >>> res = paddle.log2(x_i)
  2861. >>> res
  2862. Tensor(shape=[1], dtype=float64, place=Place(cpu), stop_gradient=True,
  2863. [1.])
  2864. """
  2865. if in_dynamic_or_pir_mode():
  2866. return _C_ops.log2(x)
  2867. else:
  2868. check_variable_and_dtype(
  2869. x,
  2870. 'x',
  2871. [
  2872. 'int32',
  2873. 'int64',
  2874. 'float16',
  2875. 'uint16',
  2876. 'float32',
  2877. 'float64',
  2878. 'complex64',
  2879. 'complex128',
  2880. ],
  2881. "log2",
  2882. )
  2883. inputs = {'X': [x]}
  2884. helper = LayerHelper('log2', **locals())
  2885. dtype = helper.input_dtype(input_param_name='x')
  2886. out = helper.create_variable_for_type_inference(dtype)
  2887. helper.append_op(type="log2", inputs={"X": x}, outputs={"Out": out})
  2888. return out
  2889. @inplace_apis_in_dygraph_only
  2890. def log2_(x, name=None):
  2891. r"""
  2892. Inplace version of ``log2`` API, the output Tensor will be inplaced with input ``x``.
  2893. Please refer to :ref:`api_paddle_log2`.
  2894. """
  2895. if in_dynamic_mode():
  2896. return _C_ops.log2_(x)
  2897. def log10(x, name=None):
  2898. r"""
  2899. Calculates the log to the base 10 of the given input tensor, element-wise.
  2900. .. math::
  2901. Out = \log_10_x
  2902. Args:
  2903. x (Tensor): Input tensor must be one of the following types: int32, int64, float16, bfloat16, float32, float64, complex64, complex128.
  2904. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2905. Returns:
  2906. Tensor: The log to the base 10 of the input Tensor computed element-wise.
  2907. Examples:
  2908. .. code-block:: python
  2909. >>> import paddle
  2910. >>> # example 1: x is a float
  2911. >>> x_i = paddle.to_tensor([[1.0], [10.0]])
  2912. >>> res = paddle.log10(x_i)
  2913. >>> res
  2914. Tensor(shape=[2, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
  2915. [[0.],
  2916. [1.]])
  2917. >>> # example 2: x is float32
  2918. >>> x_i = paddle.full(shape=[1], fill_value=10, dtype='float32')
  2919. >>> paddle.to_tensor(x_i)
  2920. >>> res = paddle.log10(x_i)
  2921. >>> res
  2922. Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
  2923. [1.])
  2924. >>> # example 3: x is float64
  2925. >>> x_i = paddle.full(shape=[1], fill_value=10, dtype='float64')
  2926. >>> paddle.to_tensor(x_i)
  2927. >>> res = paddle.log10(x_i)
  2928. >>> res
  2929. Tensor(shape=[1], dtype=float64, place=Place(cpu), stop_gradient=True,
  2930. [1.])
  2931. """
  2932. if in_dynamic_or_pir_mode():
  2933. return _C_ops.log10(x)
  2934. else:
  2935. check_variable_and_dtype(
  2936. x,
  2937. 'x',
  2938. [
  2939. 'int32',
  2940. 'int64',
  2941. 'float16',
  2942. 'uint16',
  2943. 'float32',
  2944. 'float64',
  2945. 'complex64',
  2946. 'complex128',
  2947. ],
  2948. "log10",
  2949. )
  2950. inputs = {'X': [x]}
  2951. helper = LayerHelper('log10', **locals())
  2952. dtype = helper.input_dtype(input_param_name='x')
  2953. out = helper.create_variable_for_type_inference(dtype)
  2954. helper.append_op(type="log10", inputs={"X": x}, outputs={"Out": out})
  2955. return out
  2956. @inplace_apis_in_dygraph_only
  2957. def log10_(x, name=None):
  2958. r"""
  2959. Inplace version of ``log10`` API, the output Tensor will be inplaced with input ``x``.
  2960. Please refer to :ref:`api_paddle_log10`.
  2961. """
  2962. if in_dynamic_mode():
  2963. return _C_ops.log10_(x)
  2964. def clip(x, min=None, max=None, name=None):
  2965. """
  2966. This operator clip all elements in input into the range [ min, max ] and return
  2967. a resulting tensor as the following equation:
  2968. .. math::
  2969. Out = MIN(MAX(x, min), max)
  2970. Args:
  2971. x (Tensor): An N-D Tensor with data type float16, float32, float64, int32 or int64.
  2972. min (float|int|Tensor, optional): The lower bound with type ``float`` , ``int`` or a ``0-D Tensor``
  2973. with shape [] and type ``int32``, ``float16``, ``float32``, ``float64``.
  2974. max (float|int|Tensor, optional): The upper bound with type ``float``, ``int`` or a ``0-D Tensor``
  2975. with shape [] and type ``int32``, ``float16``, ``float32``, ``float64``.
  2976. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  2977. Returns:
  2978. Tensor: A Tensor with the same data type and data shape as input.
  2979. Examples:
  2980. .. code-block:: python
  2981. >>> import paddle
  2982. >>> x1 = paddle.to_tensor([[1.2, 3.5], [4.5, 6.4]], 'float32')
  2983. >>> out1 = paddle.clip(x1, min=3.5, max=5.0)
  2984. >>> out1
  2985. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  2986. [[3.50000000, 3.50000000],
  2987. [4.50000000, 5. ]])
  2988. >>> out2 = paddle.clip(x1, min=2.5)
  2989. >>> out2
  2990. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  2991. [[2.50000000, 3.50000000],
  2992. [4.50000000, 6.40000010]])
  2993. """
  2994. x_dtype = str(x.dtype)
  2995. if x_dtype == 'paddle.int32':
  2996. min_ = np.iinfo(np.int32).min
  2997. max_ = np.iinfo(np.int32).max - 2**7
  2998. elif x_dtype == 'paddle.int64':
  2999. min_ = np.iinfo(np.int64).min
  3000. max_ = np.iinfo(np.int64).max - 2**39
  3001. elif x_dtype == 'paddle.float16':
  3002. min_ = float(np.finfo(np.float16).min)
  3003. max_ = float(np.finfo(np.float16).max)
  3004. else:
  3005. min_ = float(np.finfo(np.float32).min)
  3006. max_ = float(np.finfo(np.float32).max)
  3007. if in_dynamic_or_pir_mode():
  3008. if isinstance(min, Variable):
  3009. min = min.item(0)
  3010. if isinstance(max, Variable):
  3011. max = max.item(0)
  3012. min = min_ if min is None else min
  3013. max = max_ if max is None else max
  3014. return _C_ops.clip(x, min, max)
  3015. else:
  3016. if min is not None:
  3017. check_type(min, 'min', (float, int, Variable), 'clip')
  3018. if isinstance(min, Variable):
  3019. check_dtype(
  3020. min.dtype,
  3021. 'min',
  3022. ['float16', 'float32', 'float64', 'int32', 'uint16'],
  3023. 'clip',
  3024. '(When the type of min in clip is Variable.)',
  3025. )
  3026. if max is not None:
  3027. check_type(max, 'max', (float, int, Variable), 'clip')
  3028. if isinstance(max, Variable):
  3029. check_dtype(
  3030. max.dtype,
  3031. 'max',
  3032. ['float16', 'float32', 'float64', 'int32', 'uint16'],
  3033. 'clip',
  3034. '(When the type of max in clip is Variable.)',
  3035. )
  3036. check_variable_and_dtype(
  3037. x,
  3038. 'x',
  3039. ['float16', 'float32', 'float64', 'int32', 'int64', 'uint16'],
  3040. 'clip',
  3041. )
  3042. inputs = {'X': x}
  3043. attrs = {'min': min_, 'max': max_}
  3044. if isinstance(min, Variable):
  3045. min.stop_gradient = True
  3046. inputs['Min'] = min
  3047. elif min is not None:
  3048. attrs['min'] = min
  3049. if isinstance(max, Variable):
  3050. max.stop_gradient = True
  3051. inputs['Max'] = max
  3052. elif max is not None:
  3053. attrs['max'] = max
  3054. helper = LayerHelper('clip', **locals())
  3055. output = helper.create_variable_for_type_inference(
  3056. dtype=helper.input_dtype('x')
  3057. )
  3058. helper.append_op(
  3059. type='clip', inputs=inputs, outputs={'Out': [output]}, attrs=attrs
  3060. )
  3061. return output
  3062. @inplace_apis_in_dygraph_only
  3063. def clip_(x, min=None, max=None, name=None):
  3064. """
  3065. Inplace version of ``clip`` API, the output Tensor will be inplaced with input ``x``.
  3066. Please refer to :ref:`api_paddle_clip`.
  3067. """
  3068. fmin = float(np.finfo(np.float32).min)
  3069. fmax = float(np.finfo(np.float32).max)
  3070. if isinstance(min, Variable):
  3071. min = min.item(0)
  3072. if isinstance(max, Variable):
  3073. max = max.item(0)
  3074. min = fmin if min is None else min
  3075. max = fmax if max is None else max
  3076. if in_dynamic_mode():
  3077. return _C_ops.clip_(x, min, max)
  3078. def trace(x, offset=0, axis1=0, axis2=1, name=None):
  3079. """
  3080. Computes the sum along diagonals of the input tensor x.
  3081. If ``x`` is 2D, returns the sum of diagonal.
  3082. If ``x`` has larger dimensions, then returns an tensor of diagonals sum, diagonals be taken from
  3083. the 2D planes specified by axis1 and axis2. By default, the 2D planes formed by the first and second axes
  3084. of the input tensor x.
  3085. The argument ``offset`` determines where diagonals are taken from input tensor x:
  3086. - If offset = 0, it is the main diagonal.
  3087. - If offset > 0, it is above the main diagonal.
  3088. - If offset < 0, it is below the main diagonal.
  3089. - Note that if offset is out of input's shape indicated by axis1 and axis2, 0 will be returned.
  3090. Args:
  3091. x (Tensor): The input tensor x. Must be at least 2-dimensional. The input data type should be float32, float64, int32, int64.
  3092. offset (int, optional): Which diagonals in input tensor x will be taken. Default: 0 (main diagonals).
  3093. axis1 (int, optional): The first axis with respect to take diagonal. Default: 0.
  3094. axis2 (int, optional): The second axis with respect to take diagonal. Default: 1.
  3095. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3096. Returns:
  3097. Tensor: the output data type is the same as input data type.
  3098. Examples:
  3099. .. code-block:: python
  3100. >>> import paddle
  3101. >>> case1 = paddle.randn([2, 3])
  3102. >>> case2 = paddle.randn([3, 10, 10])
  3103. >>> case3 = paddle.randn([3, 10, 5, 10])
  3104. >>> data1 = paddle.trace(case1)
  3105. >>> data1.shape
  3106. []
  3107. >>> data2 = paddle.trace(case2, offset=1, axis1=1, axis2=2)
  3108. >>> data2.shape
  3109. [3]
  3110. >>> data3 = paddle.trace(case3, offset=-3, axis1=1, axis2=-1)
  3111. >>> data3.shape
  3112. [3, 5]
  3113. """
  3114. def __check_input(x, offset, axis1, axis2):
  3115. check_dtype(
  3116. x.dtype,
  3117. 'Input',
  3118. ['int32', 'int64', 'float16', 'float32', 'float64'],
  3119. 'trace',
  3120. )
  3121. input_shape = list(x.shape)
  3122. assert len(input_shape) >= 2, (
  3123. "The x must be at least 2-dimensional, "
  3124. "But received Input x's dimensional: %s.\n" % len(input_shape)
  3125. )
  3126. axis1_ = axis1 if axis1 >= 0 else len(input_shape) + axis1
  3127. axis2_ = axis2 if axis2 >= 0 else len(input_shape) + axis2
  3128. assert (0 <= axis1_) and (axis1_ < len(input_shape)), (
  3129. "The argument axis1 is out of range (expected to be in range of [%d, %d], but got %d).\n"
  3130. % (-(len(input_shape)), len(input_shape) - 1, axis1)
  3131. )
  3132. assert (0 <= axis2_) and (axis2_ < len(input_shape)), (
  3133. "The argument axis2 is out of range (expected to be in range of [%d, %d], but got %d).\n"
  3134. % (-(len(input_shape)), len(input_shape) - 1, axis2)
  3135. )
  3136. assert axis1_ != axis2_, (
  3137. "axis1 and axis2 cannot be the same axis."
  3138. "But received axis1 = %d, axis2 = %d\n" % (axis1, axis2)
  3139. )
  3140. if in_dynamic_or_pir_mode():
  3141. return _C_ops.trace(x, offset, axis1, axis2)
  3142. else:
  3143. __check_input(x, offset, axis1, axis2)
  3144. helper = LayerHelper('trace', **locals())
  3145. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  3146. helper.append_op(
  3147. type='trace',
  3148. inputs={'Input': [x]},
  3149. attrs={'offset': offset, 'axis1': axis1, 'axis2': axis2},
  3150. outputs={'Out': [out]},
  3151. )
  3152. return out
  3153. def diagonal(x, offset=0, axis1=0, axis2=1, name=None):
  3154. """
  3155. Computes the diagonals of the input tensor x.
  3156. If ``x`` is 2D, returns the diagonal.
  3157. If ``x`` has larger dimensions, diagonals be taken from the 2D planes specified by axis1 and axis2.
  3158. By default, the 2D planes formed by the first and second axis of the input tensor x.
  3159. The argument ``offset`` determines where diagonals are taken from input tensor x:
  3160. - If offset = 0, it is the main diagonal.
  3161. - If offset > 0, it is above the main diagonal.
  3162. - If offset < 0, it is below the main diagonal.
  3163. Args:
  3164. x (Tensor): The input tensor x. Must be at least 2-dimensional. The input data type should be bool, int32, int64, float16, float32, float64.
  3165. offset (int, optional): Which diagonals in input tensor x will be taken. Default: 0 (main diagonals).
  3166. axis1 (int, optional): The first axis with respect to take diagonal. Default: 0.
  3167. axis2 (int, optional): The second axis with respect to take diagonal. Default: 1.
  3168. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3169. Returns:
  3170. Tensor: a partial view of input tensor in specify two dimensions, the output data type is the same as input data type.
  3171. Examples:
  3172. .. code-block:: python
  3173. >>> import paddle
  3174. >>> paddle.seed(2023)
  3175. >>> x = paddle.rand([2, 2, 3],'float32')
  3176. >>> print(x)
  3177. Tensor(shape=[2, 2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  3178. [[[0.86583614, 0.52014720, 0.25960937],
  3179. [0.90525323, 0.42400089, 0.40641287]],
  3180. [[0.97020894, 0.74437362, 0.51785129],
  3181. [0.73292869, 0.97786582, 0.04315904]]])
  3182. >>> out1 = paddle.diagonal(x)
  3183. >>> print(out1)
  3184. Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  3185. [[0.86583614, 0.73292869],
  3186. [0.52014720, 0.97786582],
  3187. [0.25960937, 0.04315904]])
  3188. >>> out2 = paddle.diagonal(x, offset=0, axis1=2, axis2=1)
  3189. >>> print(out2)
  3190. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  3191. [[0.86583614, 0.42400089],
  3192. [0.97020894, 0.97786582]])
  3193. >>> out3 = paddle.diagonal(x, offset=1, axis1=0, axis2=1)
  3194. >>> print(out3)
  3195. Tensor(shape=[3, 1], dtype=float32, place=Place(cpu), stop_gradient=True,
  3196. [[0.90525323],
  3197. [0.42400089],
  3198. [0.40641287]])
  3199. >>> out4 = paddle.diagonal(x, offset=0, axis1=1, axis2=2)
  3200. >>> print(out4)
  3201. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  3202. [[0.86583614, 0.42400089],
  3203. [0.97020894, 0.97786582]])
  3204. """
  3205. if in_dynamic_or_pir_mode():
  3206. return _C_ops.diagonal(x, offset, axis1, axis2)
  3207. else:
  3208. def __check_input(x, offset, axis1, axis2):
  3209. check_dtype(
  3210. x.dtype,
  3211. 'Input',
  3212. [
  3213. 'bool',
  3214. 'int32',
  3215. 'int64',
  3216. 'float16',
  3217. 'uint16',
  3218. 'float32',
  3219. 'float64',
  3220. ],
  3221. 'diagonal',
  3222. )
  3223. input_shape = list(x.shape)
  3224. assert len(input_shape) >= 2, (
  3225. "The x must be at least 2-dimensional, "
  3226. "But received Input x's dimensional: %s.\n" % len(input_shape)
  3227. )
  3228. axis1_ = axis1 if axis1 >= 0 else len(input_shape) + axis1
  3229. axis2_ = axis2 if axis2 >= 0 else len(input_shape) + axis2
  3230. assert axis1_ < len(input_shape), (
  3231. "The argument axis1 is out of range (expected to be in range of [%d, %d], but got %d).\n"
  3232. % (-(len(input_shape)), len(input_shape) - 1, axis1)
  3233. )
  3234. assert axis2_ < len(input_shape), (
  3235. "The argument axis2 is out of range (expected to be in range of [%d, %d], but got %d).\n"
  3236. % (-(len(input_shape)), len(input_shape) - 1, axis2)
  3237. )
  3238. assert axis1_ != axis2_, (
  3239. "axis1 and axis2 cannot be the same axis."
  3240. "But received axis1 = %d, axis2 = %d\n" % (axis1, axis2)
  3241. )
  3242. __check_input(x, offset, axis1, axis2)
  3243. helper = LayerHelper('diagonal', **locals())
  3244. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  3245. helper.append_op(
  3246. type='diagonal',
  3247. inputs={'Input': [x]},
  3248. attrs={'offset': offset, 'axis1': axis1, 'axis2': axis2},
  3249. outputs={'Out': [out]},
  3250. )
  3251. return out
  3252. def kron(x, y, name=None):
  3253. r"""
  3254. Compute the Kronecker product of two tensors, a
  3255. composite tensor made of blocks of the second tensor scaled by the
  3256. first.
  3257. Assume that the rank of the two tensors, $X$ and $Y$
  3258. are the same, if necessary prepending the smallest with ones. If the
  3259. shape of $X$ is [$r_0$, $r_1$, ..., $r_N$] and the shape of $Y$ is
  3260. [$s_0$, $s_1$, ..., $s_N$], then the shape of the output tensor is
  3261. [$r_{0}s_{0}$, $r_{1}s_{1}$, ..., $r_{N}s_{N}$]. The elements are
  3262. products of elements from $X$ and $Y$.
  3263. The equation is:
  3264. $$
  3265. output[k_{0}, k_{1}, ..., k_{N}] = X[i_{0}, i_{1}, ..., i_{N}] *
  3266. Y[j_{0}, j_{1}, ..., j_{N}]
  3267. $$
  3268. where
  3269. $$
  3270. k_{t} = i_{t} * s_{t} + j_{t}, t = 0, 1, ..., N
  3271. $$
  3272. Args:
  3273. x (Tensor): the fist operand of kron op, data type: float16, float32, float64, int32 or int64.
  3274. y (Tensor): the second operand of kron op, data type: float16, float32, float64, int32 or int64. Its data type should be the same with x.
  3275. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3276. Returns:
  3277. Tensor: The output of kron, data type: float16, float32, float64, int32 or int64. Its data is the same with x.
  3278. Examples:
  3279. .. code-block:: python
  3280. >>> import paddle
  3281. >>> x = paddle.to_tensor([[1, 2], [3, 4]], dtype='int64')
  3282. >>> y = paddle.to_tensor([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype='int64')
  3283. >>> out = paddle.kron(x, y)
  3284. >>> out
  3285. Tensor(shape=[6, 6], dtype=int64, place=Place(cpu), stop_gradient=True,
  3286. [[1 , 2 , 3 , 2 , 4 , 6 ],
  3287. [4 , 5 , 6 , 8 , 10, 12],
  3288. [7 , 8 , 9 , 14, 16, 18],
  3289. [3 , 6 , 9 , 4 , 8 , 12],
  3290. [12, 15, 18, 16, 20, 24],
  3291. [21, 24, 27, 28, 32, 36]])
  3292. """
  3293. if in_dynamic_or_pir_mode():
  3294. return _C_ops.kron(x, y)
  3295. else:
  3296. helper = LayerHelper('kron', **locals())
  3297. check_variable_and_dtype(
  3298. x,
  3299. 'x',
  3300. ['float16', 'float32', 'float64', 'int32', 'int64', 'uint16'],
  3301. 'kron',
  3302. )
  3303. check_variable_and_dtype(
  3304. y,
  3305. 'y',
  3306. ['float16', 'float32', 'float64', 'int32', 'int64', 'uint16'],
  3307. 'kron',
  3308. )
  3309. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  3310. helper.append_op(
  3311. type="kron", inputs={"X": x, "Y": y}, outputs={"Out": out}
  3312. )
  3313. return out
  3314. def cumsum(x, axis=None, dtype=None, name=None):
  3315. """
  3316. The cumulative sum of the elements along a given axis.
  3317. Note:
  3318. The first element of the result is the same as the first element of the input.
  3319. Args:
  3320. x (Tensor): The input tensor needed to be cumsumed.
  3321. axis (int, optional): The dimension to accumulate along. -1 means the last dimension. The default (None) is to compute the cumsum over the flattened array.
  3322. dtype (str, optional): The data type of the output tensor, can be float16, float32, float64, int32, int64. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. The default value is None.
  3323. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3324. Returns:
  3325. Tensor, the result of cumsum operator.
  3326. Examples:
  3327. .. code-block:: python
  3328. >>> import paddle
  3329. >>> data = paddle.arange(12)
  3330. >>> data = paddle.reshape(data, (3, 4))
  3331. >>> y = paddle.cumsum(data)
  3332. >>> y
  3333. Tensor(shape=[12], dtype=int64, place=Place(cpu), stop_gradient=True,
  3334. [0 , 1 , 3 , 6 , 10, 15, 21, 28, 36, 45, 55, 66])
  3335. >>> y = paddle.cumsum(data, axis=0)
  3336. >>> y
  3337. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  3338. [[0 , 1 , 2 , 3 ],
  3339. [4 , 6 , 8 , 10],
  3340. [12, 15, 18, 21]])
  3341. >>> y = paddle.cumsum(data, axis=-1)
  3342. >>> y
  3343. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  3344. [[0 , 1 , 3 , 6 ],
  3345. [4 , 9 , 15, 22],
  3346. [8 , 17, 27, 38]])
  3347. >>> y = paddle.cumsum(data, dtype='float64')
  3348. >>> assert y.dtype == paddle.float64
  3349. """
  3350. if axis is None:
  3351. flatten = True
  3352. else:
  3353. flatten = False
  3354. if dtype is not None and x.dtype != convert_np_dtype_to_dtype_(dtype):
  3355. x = cast(x, dtype)
  3356. if in_dynamic_or_pir_mode():
  3357. if axis is None:
  3358. axis = -1
  3359. return _C_ops.cumsum(x, axis, flatten, False, False)
  3360. else:
  3361. check_variable_and_dtype(
  3362. x,
  3363. 'x',
  3364. ['float16', 'uint16', 'float32', 'float64', 'int32', 'int64'],
  3365. 'cumsum',
  3366. )
  3367. check_type(x, 'x', (Variable), 'cumsum')
  3368. locals_var = locals().copy()
  3369. kwargs = {}
  3370. for name, val in locals_var.items():
  3371. if val is not None:
  3372. kwargs[name] = val
  3373. _cum_sum_ = generate_layer_fn('cumsum')
  3374. return _cum_sum_(**kwargs)
  3375. @inplace_apis_in_dygraph_only
  3376. def cumsum_(x, axis=None, dtype=None, name=None):
  3377. r"""
  3378. Inplace version of ``cumprod`` API, the output Tensor will be inplaced with input ``x``.
  3379. Please refer to :ref:`api_paddle_cumprod`.
  3380. """
  3381. if axis is None:
  3382. flatten = True
  3383. else:
  3384. flatten = False
  3385. if dtype is not None and x.dtype != convert_np_dtype_to_dtype_(dtype):
  3386. x = cast_(x, dtype)
  3387. if in_dynamic_mode():
  3388. if axis is None:
  3389. axis = -1
  3390. return _C_ops.cumsum_(x, axis, flatten, False, False)
  3391. def cummax(x, axis=None, dtype='int64', name=None):
  3392. """
  3393. The cumulative max of the elements along a given axis.
  3394. Note:
  3395. The first element of the result is the same as the first element of the input.
  3396. Args:
  3397. x (Tensor): The input tensor needed to be cummaxed.
  3398. axis (int, optional): The dimension to accumulate along. -1 means the last dimension. The default (None) is to compute the cummax over the flattened array.
  3399. dtype (str, optional): The data type of the indices tensor, can be int32, int64. The default value is int64.
  3400. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3401. Returns:
  3402. out (Tensor), The result of cummax operation. The dtype of cummax result is same with input x.
  3403. indices (Tensor), The corresponding index results of cummax operation.
  3404. Examples:
  3405. .. code-block:: python
  3406. >>> import paddle
  3407. >>> data = paddle.to_tensor([-1, 5, 0, -2, -3, 2])
  3408. >>> data = paddle.reshape(data, (2, 3))
  3409. >>> value, indices = paddle.cummax(data)
  3410. >>> value
  3411. Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
  3412. [-1, 5, 5, 5, 5, 5])
  3413. >>> indices
  3414. Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
  3415. [0, 1, 1, 1, 1, 1])
  3416. >>> value, indices = paddle.cummax(data, axis=0)
  3417. >>> value
  3418. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  3419. [[-1, 5, 0],
  3420. [-1, 5, 2]])
  3421. >>> indices
  3422. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  3423. [[0, 0, 0],
  3424. [0, 0, 1]])
  3425. >>> value, indices = paddle.cummax(data, axis=-1)
  3426. >>> value
  3427. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  3428. [[-1, 5, 5],
  3429. [-2, -2, 2]])
  3430. >>> indices
  3431. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  3432. [[0, 1, 1],
  3433. [0, 0, 2]])
  3434. >>> value, indices = paddle.cummax(data, dtype='int64')
  3435. >>> assert indices.dtype == paddle.int64
  3436. """
  3437. if axis is None:
  3438. axis = -1
  3439. x = x.flatten(0, len(x.shape) - 1)
  3440. check_dtype(dtype, 'dtype', ['int32', 'int64'], 'cummax')
  3441. if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
  3442. dtype = convert_np_dtype_to_dtype_(dtype)
  3443. if in_dynamic_or_pir_mode():
  3444. return _C_ops.cummax(x, axis, dtype)
  3445. else:
  3446. check_variable_and_dtype(
  3447. x,
  3448. 'x',
  3449. ['float32', 'float64', 'int32', 'int64'],
  3450. 'cummax',
  3451. )
  3452. check_type(x, 'x', (Variable), 'cummax')
  3453. helper = LayerHelper('cummax', **locals())
  3454. out = helper.create_variable_for_type_inference(x.dtype)
  3455. indices = helper.create_variable_for_type_inference(dtype='int64')
  3456. helper.append_op(
  3457. type='cummax',
  3458. inputs={'x': x},
  3459. outputs={'out': out, 'indices': indices},
  3460. attrs={'axis': axis, 'dtype': dtype},
  3461. )
  3462. return out, indices
  3463. def cummin(x, axis=None, dtype='int64', name=None):
  3464. """
  3465. The cumulative min of the elements along a given axis.
  3466. Note:
  3467. The first element of the result is the same as the first element of the input.
  3468. Args:
  3469. x (Tensor): The input tensor needed to be cummined.
  3470. axis (int, optional): The dimension to accumulate along. -1 means the last dimension. The default (None) is to compute the cummin over the flattened array.
  3471. dtype (str, optional): The data type of the indices tensor, can be int32, int64. The default value is int64.
  3472. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3473. Returns:
  3474. out (Tensor), The result of cummin operation. The dtype of cummin result is same with input x.
  3475. indices (Tensor), The corresponding index results of cummin operation.
  3476. Examples:
  3477. .. code-block:: python
  3478. >>> import paddle
  3479. >>> data = paddle.to_tensor([-1, 5, 0, -2, -3, 2])
  3480. >>> data = paddle.reshape(data, (2, 3))
  3481. >>> value, indices = paddle.cummin(data)
  3482. >>> value
  3483. Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
  3484. [-1, -1, -1, -2, -3, -3])
  3485. >>> indices
  3486. Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
  3487. [0, 0, 0, 3, 4, 4])
  3488. >>> value, indices = paddle.cummin(data, axis=0)
  3489. >>> value
  3490. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  3491. [[-1, 5, 0],
  3492. [-2, -3, 0]])
  3493. >>> indices
  3494. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  3495. [[0, 0, 0],
  3496. [1, 1, 0]])
  3497. >>> value, indices = paddle.cummin(data, axis=-1)
  3498. >>> value
  3499. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  3500. [[-1, -1, -1],
  3501. [-2, -3, -3]])
  3502. >>> indices
  3503. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  3504. [[0, 0, 0],
  3505. [0, 1, 1]])
  3506. >>> value, indices = paddle.cummin(data, dtype='int64')
  3507. >>> assert indices.dtype == paddle.int64
  3508. """
  3509. if axis is None:
  3510. axis = -1
  3511. x = x.flatten(0, len(x.shape) - 1)
  3512. check_dtype(dtype, 'dtype', ['int32', 'int64'], 'cummin')
  3513. if not isinstance(dtype, (core.VarDesc.VarType, core.DataType)):
  3514. dtype = convert_np_dtype_to_dtype_(dtype)
  3515. if in_dynamic_or_pir_mode():
  3516. return _C_ops.cummin(x, axis, dtype)
  3517. else:
  3518. check_variable_and_dtype(
  3519. x,
  3520. 'x',
  3521. ['float32', 'float64', 'int32', 'int64'],
  3522. 'cummin',
  3523. )
  3524. check_type(x, 'x', (Variable), 'cummin')
  3525. helper = LayerHelper('cummin', **locals())
  3526. out = helper.create_variable_for_type_inference(x.dtype)
  3527. indices = helper.create_variable_for_type_inference(dtype='int64')
  3528. helper.append_op(
  3529. type='cummin',
  3530. inputs={'x': x},
  3531. outputs={'out': out, 'indices': indices},
  3532. attrs={'axis': axis, 'dtype': dtype},
  3533. )
  3534. return out, indices
  3535. def logcumsumexp(x, axis=None, dtype=None, name=None):
  3536. r"""
  3537. The logarithm of the cumulative summation of the exponentiation of the elements along a given axis.
  3538. For summation index j given by `axis` and other indices i, the result is
  3539. .. math::
  3540. logcumsumexp(x)_{ij} = log \sum_{i=0}^{j}exp(x_{ij})
  3541. Note:
  3542. The first element of the result is the same as the first element of the input.
  3543. Args:
  3544. x (Tensor): The input tensor.
  3545. axis (int, optional): The dimension to do the operation along. -1 means the last dimension. The default (None) is to compute the cumsum over the flattened array.
  3546. dtype (str, optional): The data type of the output tensor, can be float16, float32, float64. If specified, the input tensor is casted to dtype before the operation is performed. This is useful for preventing data type overflows. The default value is None.
  3547. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3548. Returns:
  3549. Tensor, the result of logcumsumexp operator.
  3550. Examples:
  3551. .. code-block:: python
  3552. >>> import paddle
  3553. >>> data = paddle.arange(12, dtype='float64')
  3554. >>> data = paddle.reshape(data, (3, 4))
  3555. >>> y = paddle.logcumsumexp(data)
  3556. >>> y
  3557. Tensor(shape=[12], dtype=float64, place=Place(cpu), stop_gradient=True,
  3558. [0. , 1.31326169 , 2.40760596 , 3.44018970 , 4.45191440 ,
  3559. 5.45619332 , 6.45776285 , 7.45833963 , 8.45855173 , 9.45862974 ,
  3560. 10.45865844, 11.45866900])
  3561. >>> y = paddle.logcumsumexp(data, axis=0)
  3562. >>> y
  3563. Tensor(shape=[3, 4], dtype=float64, place=Place(cpu), stop_gradient=True,
  3564. [[0. , 1. , 2. , 3. ],
  3565. [4.01814993 , 5.01814993 , 6.01814993 , 7.01814993 ],
  3566. [8.01847930 , 9.01847930 , 10.01847930, 11.01847930]])
  3567. >>> y = paddle.logcumsumexp(data, axis=-1)
  3568. >>> y
  3569. Tensor(shape=[3, 4], dtype=float64, place=Place(cpu), stop_gradient=True,
  3570. [[0. , 1.31326169 , 2.40760596 , 3.44018970 ],
  3571. [4. , 5.31326169 , 6.40760596 , 7.44018970 ],
  3572. [8. , 9.31326169 , 10.40760596, 11.44018970]])
  3573. >>> y = paddle.logcumsumexp(data, dtype='float64')
  3574. >>> assert y.dtype == paddle.float64
  3575. """
  3576. if axis is None:
  3577. flatten = True
  3578. else:
  3579. flatten = False
  3580. if dtype is not None and x.dtype != convert_np_dtype_to_dtype_(dtype):
  3581. x = cast(x, dtype)
  3582. if in_dynamic_or_pir_mode():
  3583. if axis is None:
  3584. axis = -1
  3585. return _C_ops.logcumsumexp(x, axis, flatten, False, False)
  3586. else:
  3587. check_variable_and_dtype(
  3588. x, 'x', ['float16', 'float32', 'float64', 'uint16'], "logcumsumexp"
  3589. )
  3590. helper = LayerHelper('logcumsumexp', **locals())
  3591. out = helper.create_variable_for_type_inference(x.dtype)
  3592. helper.append_op(
  3593. type='logcumsumexp',
  3594. inputs={'X': x},
  3595. outputs={'Out': out},
  3596. attrs={'axis': axis, 'flatten': flatten},
  3597. )
  3598. return out
  3599. def cumprod(x, dim=None, dtype=None, name=None):
  3600. """
  3601. Compute the cumulative product of the input tensor x along a given dimension dim.
  3602. Note:
  3603. The first element of the result is the same as the first element of the input.
  3604. Args:
  3605. x (Tensor): the input tensor need to be cumproded.
  3606. dim (int, optional): the dimension along which the input tensor will be accumulated. It need to be in the range of [-x.rank, x.rank),
  3607. where x.rank means the dimensions of the input tensor x and -1 means the last dimension.
  3608. dtype (str, optional): The data type of the output tensor, can be float32, float64, int32, int64, complex64,
  3609. complex128. If specified, the input tensor is casted to dtype before the operation is performed.
  3610. This is useful for preventing data type overflows. The default value is None.
  3611. name (str, optional): Name for the operation (optional, default is None). For more information,
  3612. please refer to :ref:`api_guide_Name`.
  3613. Returns:
  3614. Tensor, the result of cumprod operator.
  3615. Examples:
  3616. .. code-block:: python
  3617. >>> import paddle
  3618. >>> data = paddle.arange(12)
  3619. >>> data = paddle.reshape(data, (3, 4))
  3620. >>> data
  3621. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  3622. [[0 , 1 , 2 , 3 ],
  3623. [4 , 5 , 6 , 7 ],
  3624. [8 , 9 , 10, 11]])
  3625. >>> y = paddle.cumprod(data, dim=0)
  3626. >>> y
  3627. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  3628. [[0 , 1 , 2 , 3 ],
  3629. [0 , 5 , 12 , 21 ],
  3630. [0 , 45 , 120, 231]])
  3631. >>> y = paddle.cumprod(data, dim=-1)
  3632. >>> y
  3633. Tensor(shape=[3, 4], dtype=int64, place=Place(cpu), stop_gradient=True,
  3634. [[0 , 0 , 0 , 0 ],
  3635. [4 , 20 , 120 , 840 ],
  3636. [8 , 72 , 720 , 7920]])
  3637. >>> y = paddle.cumprod(data, dim=1, dtype='float64')
  3638. >>> y
  3639. Tensor(shape=[3, 4], dtype=float64, place=Place(cpu), stop_gradient=True,
  3640. [[0. , 0. , 0. , 0. ],
  3641. [4. , 20. , 120. , 840. ],
  3642. [8. , 72. , 720. , 7920.]])
  3643. >>> assert y.dtype == paddle.float64
  3644. """
  3645. if dtype is not None and x.dtype != convert_np_dtype_to_dtype_(dtype):
  3646. x = cast(x, dtype)
  3647. if in_dynamic_or_pir_mode():
  3648. return _C_ops.cumprod(x, dim, False, False)
  3649. else:
  3650. check_variable_and_dtype(
  3651. x,
  3652. "x",
  3653. [
  3654. 'complex64',
  3655. 'complex128',
  3656. 'float16',
  3657. 'uint16',
  3658. 'float32',
  3659. 'float64',
  3660. 'int32',
  3661. 'int64',
  3662. ],
  3663. 'cumprod',
  3664. )
  3665. check_type(dim, 'dim', int, 'cumprod')
  3666. helper = LayerHelper('cumprod', **locals())
  3667. out = helper.create_variable_for_type_inference(x.dtype)
  3668. helper.append_op(
  3669. type='cumprod',
  3670. inputs={'X': x},
  3671. outputs={'Out': out},
  3672. attrs={'dim': dim},
  3673. )
  3674. return out
  3675. @inplace_apis_in_dygraph_only
  3676. def cumprod_(x, dim=None, dtype=None, name=None):
  3677. r"""
  3678. Inplace version of ``cumprod`` API, the output Tensor will be inplaced with input ``x``.
  3679. Please refer to :ref:`api_paddle_cumprod`.
  3680. """
  3681. if dtype is not None and x.dtype != convert_np_dtype_to_dtype_(dtype):
  3682. x = cast_(x, dtype)
  3683. if in_dynamic_mode():
  3684. return _C_ops.cumprod_(x, dim, False, False)
  3685. def isfinite(x, name=None):
  3686. """
  3687. Return whether every element of input tensor is finite number or not.
  3688. Args:
  3689. x (Tensor): The input tensor, it's data type should be float16, float32, float64, int32, int64.
  3690. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3691. Returns:
  3692. `Tensor`, the bool result which shows every element of `x` whether it is finite number or not.
  3693. Examples:
  3694. .. code-block:: python
  3695. >>> import paddle
  3696. >>> x = paddle.to_tensor([float('-inf'), -2, 3.6, float('inf'), 0, float('-nan'), float('nan')])
  3697. >>> out = paddle.isfinite(x)
  3698. >>> out
  3699. Tensor(shape=[7], dtype=bool, place=Place(cpu), stop_gradient=True,
  3700. [False, True , True , False, True , False, False])
  3701. """
  3702. if in_dynamic_or_pir_mode():
  3703. return _C_ops.isfinite(x)
  3704. else:
  3705. helper = LayerHelper("isfinite_v2", **locals())
  3706. check_variable_and_dtype(
  3707. x,
  3708. 'x',
  3709. [
  3710. 'float16',
  3711. 'float32',
  3712. 'float64',
  3713. 'int32',
  3714. 'int64',
  3715. 'uint16',
  3716. ],
  3717. 'isfinite',
  3718. )
  3719. out = helper.create_variable_for_type_inference('bool')
  3720. helper.append_op(
  3721. type="isfinite_v2", inputs={"X": x}, outputs={"Out": out}
  3722. )
  3723. return out
  3724. def isinf(x, name=None):
  3725. """
  3726. Return whether every element of input tensor is `+/-INF` or not.
  3727. Args:
  3728. x (Tensor): The input tensor, it's data type should be float16, float32, float64, uint8, int8, int16, int32, int64.
  3729. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3730. Returns:
  3731. `Tensor`, the bool result which shows every element of `x` whether it is `+/-INF` or not.
  3732. Examples:
  3733. .. code-block:: python
  3734. >>> import paddle
  3735. >>> x = paddle.to_tensor([float('-inf'), -2, 3.6, float('inf'), 0, float('-nan'), float('nan')])
  3736. >>> out = paddle.isinf(x)
  3737. >>> out
  3738. Tensor(shape=[7], dtype=bool, place=Place(cpu), stop_gradient=True,
  3739. [True , False, False, True , False, False, False])
  3740. """
  3741. if in_dynamic_or_pir_mode():
  3742. return _C_ops.isinf(x)
  3743. else:
  3744. helper = LayerHelper("isinf_v2", **locals())
  3745. check_variable_and_dtype(
  3746. x,
  3747. 'x',
  3748. [
  3749. 'float16',
  3750. 'float32',
  3751. 'float64',
  3752. 'int8',
  3753. 'int16',
  3754. 'int32',
  3755. 'int64',
  3756. 'uint8',
  3757. 'uint16',
  3758. ],
  3759. 'isinf',
  3760. )
  3761. out = helper.create_variable_for_type_inference(dtype='bool')
  3762. helper.append_op(type="isinf_v2", inputs={"X": x}, outputs={"Out": out})
  3763. return out
  3764. def isnan(x, name=None):
  3765. """
  3766. Return whether every element of input tensor is `NaN` or not.
  3767. Args:
  3768. x (Tensor): The input tensor, it's data type should be float16, float32, float64, int32, int64.
  3769. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3770. Returns:
  3771. `Tensor`, the bool result which shows every element of `x` whether it is `NaN` or not.
  3772. Examples:
  3773. .. code-block:: python
  3774. >>> import paddle
  3775. >>> x = paddle.to_tensor([float('-inf'), -2, 3.6, float('inf'), 0, float('-nan'), float('nan')])
  3776. >>> out = paddle.isnan(x)
  3777. >>> out
  3778. Tensor(shape=[7], dtype=bool, place=Place(cpu), stop_gradient=True,
  3779. [False, False, False, False, False, True , True ])
  3780. """
  3781. if in_dynamic_or_pir_mode():
  3782. return _C_ops.isnan(x)
  3783. else:
  3784. helper = LayerHelper("isnan_v2", **locals())
  3785. check_variable_and_dtype(
  3786. x,
  3787. 'x',
  3788. [
  3789. 'float16',
  3790. 'float32',
  3791. 'float64',
  3792. 'int32',
  3793. 'int64',
  3794. 'uint16',
  3795. ],
  3796. 'isnan',
  3797. )
  3798. out = helper.create_variable_for_type_inference(dtype='bool')
  3799. helper.append_op(type="isnan_v2", inputs={"X": x}, outputs={"Out": out})
  3800. return out
  3801. def prod(x, axis=None, keepdim=False, dtype=None, name=None):
  3802. """
  3803. Compute the product of tensor elements over the given axis.
  3804. Args:
  3805. x (Tensor): The input tensor, its data type should be float32, float64, int32, int64.
  3806. axis (int|list|tuple, optional): The axis along which the product is computed. If :attr:`None`,
  3807. multiply all elements of `x` and return a Tensor with a single element,
  3808. otherwise must be in the range :math:`[-x.ndim, x.ndim)`. If :math:`axis[i]<0`,
  3809. the axis to reduce is :math:`x.ndim + axis[i]`. Default is None.
  3810. keepdim (bool, optional): Whether to reserve the reduced dimension in the output Tensor. The result
  3811. tensor will have one fewer dimension than the input unless `keepdim` is true. Default is False.
  3812. dtype (str|np.dtype, optional): The desired date type of returned tensor, can be float32, float64,
  3813. int32, int64. If specified, the input tensor is casted to dtype before operator performed.
  3814. This is very useful for avoiding data type overflows. The default value is None, the dtype
  3815. of output is the same as input Tensor `x`.
  3816. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3817. Returns:
  3818. Tensor, result of product on the specified dim of input tensor.
  3819. Examples:
  3820. .. code-block:: python
  3821. >>> import paddle
  3822. >>> # the axis is a int element
  3823. >>> x = paddle.to_tensor([[0.2, 0.3, 0.5, 0.9],
  3824. ... [0.1, 0.2, 0.6, 0.7]])
  3825. >>> out1 = paddle.prod(x)
  3826. >>> out1
  3827. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  3828. 0.00022680)
  3829. >>> out2 = paddle.prod(x, -1)
  3830. >>> out2
  3831. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  3832. [0.02700000, 0.00840000])
  3833. >>> out3 = paddle.prod(x, 0)
  3834. >>> out3
  3835. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  3836. [0.02000000, 0.06000000, 0.30000001, 0.63000000])
  3837. >>> out4 = paddle.prod(x, 0, keepdim=True)
  3838. >>> out4
  3839. Tensor(shape=[1, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  3840. [[0.02000000, 0.06000000, 0.30000001, 0.63000000]])
  3841. >>> out5 = paddle.prod(x, 0, dtype='int64')
  3842. >>> out5
  3843. Tensor(shape=[4], dtype=int64, place=Place(cpu), stop_gradient=True,
  3844. [0, 0, 0, 0])
  3845. >>> # the axis is list
  3846. >>> y = paddle.to_tensor([[[1.0, 2.0], [3.0, 4.0]],
  3847. ... [[5.0, 6.0], [7.0, 8.0]]])
  3848. >>> out6 = paddle.prod(y, [0, 1])
  3849. >>> out6
  3850. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  3851. [105., 384.])
  3852. >>> out7 = paddle.prod(y, (1, 2))
  3853. >>> out7
  3854. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  3855. [24. , 1680.])
  3856. """
  3857. if dtype is not None:
  3858. check_dtype(
  3859. dtype,
  3860. 'dtype',
  3861. ['float32', 'float64', 'int32', 'int64', "float16", "uint16"],
  3862. 'prod',
  3863. )
  3864. if x.dtype != convert_np_dtype_to_dtype_(dtype):
  3865. x = cast(x, dtype)
  3866. reduce_all, axis = _get_reduce_axis_with_tensor(axis, x)
  3867. if in_dynamic_or_pir_mode():
  3868. return _C_ops.prod(x, axis, keepdim, reduce_all)
  3869. else:
  3870. helper = LayerHelper('reduce_prod', **locals())
  3871. check_variable_and_dtype(
  3872. x,
  3873. 'x/input',
  3874. ['float32', 'float64', 'int32', 'int64', "float16", "uint16"],
  3875. 'reduce_prod',
  3876. )
  3877. out = helper.create_variable_for_type_inference(
  3878. dtype=helper.input_dtype()
  3879. )
  3880. helper.append_op(
  3881. type='reduce_prod',
  3882. inputs={'X': x},
  3883. outputs={'Out': out},
  3884. attrs={'dim': axis, 'keep_dim': keepdim, 'reduce_all': reduce_all},
  3885. )
  3886. return out
  3887. def sign(x, name=None):
  3888. """
  3889. Returns sign of every element in `x`: 1 for positive, -1 for negative and 0 for zero.
  3890. Args:
  3891. x (Tensor): The input tensor. The data type can be uint8, int8, int16, int32, int64, float16, float32 or float64.
  3892. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3893. Returns:
  3894. Tensor: The output sign tensor with identical shape and data type to the input :attr:`x`.
  3895. Examples:
  3896. .. code-block:: python
  3897. >>> import paddle
  3898. >>> x = paddle.to_tensor([3.0, 0.0, -2.0, 1.7], dtype='float32')
  3899. >>> out = paddle.sign(x=x)
  3900. >>> out
  3901. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  3902. [ 1., 0., -1., 1.])
  3903. """
  3904. if in_dynamic_or_pir_mode():
  3905. return _C_ops.sign(x)
  3906. else:
  3907. check_variable_and_dtype(
  3908. x,
  3909. 'x',
  3910. [
  3911. 'uint8',
  3912. 'int8',
  3913. 'int16',
  3914. 'int32',
  3915. 'int64',
  3916. 'float16',
  3917. 'bfloat16',
  3918. 'float32',
  3919. 'float64',
  3920. ],
  3921. 'sign',
  3922. )
  3923. helper = LayerHelper("sign", **locals())
  3924. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  3925. helper.append_op(type='sign', inputs={'X': [x]}, outputs={'Out': [out]})
  3926. return out
  3927. def tanh(x, name=None):
  3928. r"""
  3929. Tanh Activation Operator.
  3930. .. math::
  3931. out = \frac{e^{x} - e^{-x}}{e^{x} + e^{-x}}
  3932. Args:
  3933. x (Tensor): Input of Tanh operator, an N-D Tensor, with data type bfloat16, float32, float64 or float16.
  3934. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3935. Returns:
  3936. Output of Tanh operator, a Tensor with same data type and shape as input.
  3937. Examples:
  3938. .. code-block:: python
  3939. >>> import paddle
  3940. >>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
  3941. >>> out = paddle.tanh(x)
  3942. >>> out
  3943. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  3944. [-0.37994900, -0.19737528, 0.09966799, 0.29131261])
  3945. """
  3946. if in_dynamic_or_pir_mode():
  3947. return _C_ops.tanh(x)
  3948. else:
  3949. check_variable_and_dtype(
  3950. x, 'x', ['uint16', 'float16', 'float32', 'float64'], 'tanh'
  3951. )
  3952. check_type(x, 'x', (Variable), 'tanh')
  3953. helper = LayerHelper('tanh', **locals())
  3954. out = helper.create_variable_for_type_inference(x.dtype)
  3955. helper.append_op(type='tanh', inputs={'X': x}, outputs={'Out': out})
  3956. return out
  3957. @inplace_apis_in_dygraph_only
  3958. def tanh_(x, name=None):
  3959. r"""
  3960. Inplace version of ``tanh`` API, the output Tensor will be inplaced with input ``x``.
  3961. Please refer to :ref:`api_paddle_tanh`.
  3962. """
  3963. return _C_ops.tanh_(x)
  3964. def increment(x, value=1.0, name=None):
  3965. """
  3966. The API is usually used for control flow to increment the data of :attr:`x` by an amount :attr:`value`.
  3967. Notice that the number of elements in :attr:`x` must be equal to 1.
  3968. Args:
  3969. x (Tensor): A tensor that must always contain only one element, its data type supports float32, float64, int32 and int64.
  3970. value (float, optional): The amount to increment the data of :attr:`x`. Default: 1.0.
  3971. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  3972. Returns:
  3973. Tensor, the elementwise-incremented tensor with the same shape and data type as :attr:`x`.
  3974. Examples:
  3975. .. code-block:: python
  3976. >>> import paddle
  3977. >>> data = paddle.zeros(shape=[1], dtype='float32')
  3978. >>> counter = paddle.increment(data)
  3979. >>> counter
  3980. Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
  3981. [1.])
  3982. """
  3983. if in_dynamic_mode():
  3984. return _C_ops.increment_(x, value)
  3985. check_variable_and_dtype(
  3986. x, 'x', ['float32', 'float64', 'int32', 'int64'], 'increment'
  3987. )
  3988. if in_pir_mode():
  3989. _C_ops.increment_(x, value)
  3990. return x
  3991. else:
  3992. helper = LayerHelper("increment", **locals())
  3993. helper.append_op(
  3994. type='increment',
  3995. inputs={'X': [x]},
  3996. outputs={'Out': [x]},
  3997. attrs={'step': float(value)},
  3998. )
  3999. return x
  4000. def all(x, axis=None, keepdim=False, name=None):
  4001. """
  4002. Computes the ``logical and`` of tensor elements over the given dimension.
  4003. Args:
  4004. x (Tensor): An N-D Tensor, the input data type should be `bool`.
  4005. axis (int|list|tuple, optional): The dimensions along which the ``logical and`` is compute. If
  4006. :attr:`None`, and all elements of :attr:`x` and return a
  4007. Tensor with a single element, otherwise must be in the
  4008. range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`,
  4009. the dimension to reduce is :math:`rank + axis[i]`.
  4010. keepdim (bool, optional): Whether to reserve the reduced dimension in the
  4011. output Tensor. The result Tensor will have one fewer dimension
  4012. than the :attr:`x` unless :attr:`keepdim` is true, default
  4013. value is False.
  4014. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4015. Returns:
  4016. Tensor: Results the ``logical and`` on the specified axis of input Tensor `x`, it's data type is bool.
  4017. Examples:
  4018. .. code-block:: python
  4019. >>> import paddle
  4020. >>> # x is a bool Tensor with following elements:
  4021. >>> # [[True, False]
  4022. >>> # [True, True]]
  4023. >>> x = paddle.to_tensor([[1, 0], [1, 1]], dtype='int32')
  4024. >>> x
  4025. Tensor(shape=[2, 2], dtype=int32, place=Place(cpu), stop_gradient=True,
  4026. [[1, 0],
  4027. [1, 1]])
  4028. >>> x = paddle.cast(x, 'bool')
  4029. >>> # out1 should be False
  4030. >>> out1 = paddle.all(x)
  4031. >>> out1
  4032. Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
  4033. False)
  4034. >>> # out2 should be [True, False]
  4035. >>> out2 = paddle.all(x, axis=0)
  4036. >>> out2
  4037. Tensor(shape=[2], dtype=bool, place=Place(cpu), stop_gradient=True,
  4038. [True , False])
  4039. >>> # keepdim=False, out3 should be [False, True], out.shape should be (2,)
  4040. >>> out3 = paddle.all(x, axis=-1)
  4041. >>> out3
  4042. Tensor(shape=[2], dtype=bool, place=Place(cpu), stop_gradient=True,
  4043. [False, True ])
  4044. >>> # keepdim=True, out4 should be [[False], [True]], out.shape should be (2, 1)
  4045. >>> out4 = paddle.all(x, axis=1, keepdim=True)
  4046. >>> out4
  4047. Tensor(shape=[2, 1], dtype=bool, place=Place(cpu), stop_gradient=True,
  4048. [[False],
  4049. [True ]])
  4050. """
  4051. if in_dynamic_or_pir_mode():
  4052. return _C_ops.all(x, axis, keepdim)
  4053. else:
  4054. reduce_all, axis = _get_reduce_axis(axis, x)
  4055. attrs = {
  4056. 'dim': axis,
  4057. 'keep_dim': keepdim,
  4058. 'reduce_all': reduce_all,
  4059. }
  4060. check_variable_and_dtype(
  4061. x, 'x', ['bool', 'float32', 'float64', 'int32', 'int64'], 'all'
  4062. )
  4063. check_type(axis, 'axis', (int, list, tuple, type(None)), 'all')
  4064. helper = LayerHelper('all', **locals())
  4065. out = helper.create_variable_for_type_inference(dtype=paddle.bool)
  4066. helper.append_op(
  4067. type='reduce_all',
  4068. inputs={'X': x},
  4069. outputs={'Out': out},
  4070. attrs=attrs,
  4071. )
  4072. return out
  4073. def any(x, axis=None, keepdim=False, name=None):
  4074. """
  4075. Computes the ``logical or`` of tensor elements over the given dimension, and return the result.
  4076. Args:
  4077. x (Tensor): An N-D Tensor, the input data type should be `bool`.
  4078. axis (int|list|tuple, optional): The dimensions along which the ``logical or`` is compute. If
  4079. :attr:`None`, and all elements of :attr:`x` and return a
  4080. Tensor with a single element, otherwise must be in the
  4081. range :math:`[-rank(x), rank(x))`. If :math:`axis[i] < 0`,
  4082. the dimension to reduce is :math:`rank + axis[i]`.
  4083. keepdim (bool, optional): Whether to reserve the reduced dimension in the
  4084. output Tensor. The result Tensor will have one fewer dimension
  4085. than the :attr:`x` unless :attr:`keepdim` is true, default
  4086. value is False.
  4087. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4088. Returns:
  4089. Tensor: Results the ``logical or`` on the specified axis of input Tensor `x`, it's data type is bool.
  4090. Examples:
  4091. .. code-block:: python
  4092. >>> import paddle
  4093. >>> x = paddle.to_tensor([[1, 0], [1, 1]], dtype='int32')
  4094. >>> x = paddle.assign(x)
  4095. >>> x
  4096. Tensor(shape=[2, 2], dtype=int32, place=Place(cpu), stop_gradient=True,
  4097. [[1, 0],
  4098. [1, 1]])
  4099. >>> x = paddle.cast(x, 'bool')
  4100. >>> # x is a bool Tensor with following elements:
  4101. >>> # [[True, False]
  4102. >>> # [True, True]]
  4103. >>> # out1 should be True
  4104. >>> out1 = paddle.any(x)
  4105. >>> out1
  4106. Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
  4107. True)
  4108. >>> # out2 should be [True, True]
  4109. >>> out2 = paddle.any(x, axis=0)
  4110. >>> out2
  4111. Tensor(shape=[2], dtype=bool, place=Place(cpu), stop_gradient=True,
  4112. [True, True])
  4113. >>> # keepdim=False, out3 should be [True, True], out.shape should be (2,)
  4114. >>> out3 = paddle.any(x, axis=-1)
  4115. >>> out3
  4116. Tensor(shape=[2], dtype=bool, place=Place(cpu), stop_gradient=True,
  4117. [True, True])
  4118. >>> # keepdim=True, result should be [[True], [True]], out.shape should be (2,1)
  4119. >>> out4 = paddle.any(x, axis=1, keepdim=True)
  4120. >>> out4
  4121. Tensor(shape=[2, 1], dtype=bool, place=Place(cpu), stop_gradient=True,
  4122. [[True],
  4123. [True]])
  4124. """
  4125. if in_dynamic_or_pir_mode():
  4126. return _C_ops.any(x, axis, keepdim)
  4127. else:
  4128. reduce_all, axis = _get_reduce_axis(axis, x)
  4129. attrs = {
  4130. 'dim': axis,
  4131. 'keep_dim': keepdim,
  4132. 'reduce_all': reduce_all,
  4133. }
  4134. check_variable_and_dtype(
  4135. x, 'x', ['bool', 'float32', 'float64', 'int32', 'int64'], 'any'
  4136. )
  4137. check_type(axis, 'axis', (int, list, tuple, type(None)), 'any')
  4138. helper = LayerHelper('any', **locals())
  4139. out = helper.create_variable_for_type_inference(dtype=paddle.bool)
  4140. helper.append_op(
  4141. type='reduce_any',
  4142. inputs={'X': x},
  4143. outputs={'Out': out},
  4144. attrs=attrs,
  4145. )
  4146. return out
  4147. def broadcast_shape(x_shape, y_shape):
  4148. """
  4149. The function returns the shape of doing operation with broadcasting on tensors of x_shape and y_shape.
  4150. Note:
  4151. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  4152. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  4153. Args:
  4154. x_shape (list[int]|tuple[int]): A shape of tensor.
  4155. y_shape (list[int]|tuple[int]): A shape of tensor.
  4156. Returns:
  4157. list[int], the result shape.
  4158. Examples:
  4159. .. code-block:: python
  4160. >>> import paddle
  4161. >>> shape = paddle.broadcast_shape([2, 1, 3], [1, 3, 1])
  4162. >>> shape
  4163. [2, 3, 3]
  4164. >>> # shape = paddle.broadcast_shape([2, 1, 3], [3, 3, 1])
  4165. >>> # ValueError (terminated with error message).
  4166. """
  4167. return core.broadcast_shape(x_shape, y_shape)
  4168. def conj(x, name=None):
  4169. r"""
  4170. This function computes the conjugate of the Tensor elementwisely.
  4171. Args:
  4172. x (Tensor): The input Tensor which hold the complex numbers.
  4173. Optional data types are:float16, complex64, complex128, float32, float64, int32 or int64.
  4174. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4175. Returns:
  4176. out (Tensor): The conjugate of input. The shape and data type is the same with input. If the elements of tensor is real type such as float32, float64, int32 or int64, the out is the same with input.
  4177. Examples:
  4178. .. code-block:: python
  4179. >>> import paddle
  4180. >>> data = paddle.to_tensor([[1+1j, 2+2j, 3+3j], [4+4j, 5+5j, 6+6j]])
  4181. >>> data
  4182. Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
  4183. [[(1+1j), (2+2j), (3+3j)],
  4184. [(4+4j), (5+5j), (6+6j)]])
  4185. >>> conj_data = paddle.conj(data)
  4186. >>> conj_data
  4187. Tensor(shape=[2, 3], dtype=complex64, place=Place(cpu), stop_gradient=True,
  4188. [[(1-1j), (2-2j), (3-3j)],
  4189. [(4-4j), (5-5j), (6-6j)]])
  4190. """
  4191. if in_dynamic_or_pir_mode():
  4192. return _C_ops.conj(x)
  4193. else:
  4194. check_variable_and_dtype(
  4195. x,
  4196. "x",
  4197. [
  4198. 'complex64',
  4199. 'complex128',
  4200. 'float16',
  4201. 'uint16',
  4202. 'float32',
  4203. 'float64',
  4204. 'int32',
  4205. 'int64',
  4206. ],
  4207. 'conj',
  4208. )
  4209. helper = LayerHelper('conj', **locals())
  4210. out = helper.create_variable_for_type_inference(
  4211. dtype=helper.input_dtype()
  4212. )
  4213. helper.append_op(type='conj', inputs={'X': x}, outputs={'Out': [out]})
  4214. return out
  4215. def gammaln(x, name=None):
  4216. r"""
  4217. Calculates the logarithm of the absolute value of the gamma function elementwisely.
  4218. Args:
  4219. x (Tensor): Input Tensor. Must be one of the following types: float16, float32, float64, bfloat16.
  4220. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4221. Returns:
  4222. Tensor, The values of the logarithm of the absolute value of the gamma at the given tensor x.
  4223. Examples:
  4224. .. code-block:: python
  4225. >>> import paddle
  4226. >>> x = paddle.arange(1.5, 4.5, 0.5)
  4227. >>> out = paddle.gammaln(x)
  4228. >>> print(out)
  4229. Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
  4230. [-0.12078224, 0. , 0.28468287, 0.69314718, 1.20097363,
  4231. 1.79175949])
  4232. """
  4233. if in_dynamic_or_pir_mode():
  4234. return _C_ops.gammaln(x)
  4235. else:
  4236. check_variable_and_dtype(
  4237. x, 'x', ['float16', 'float32', 'float64', 'bfloat16'], 'gammaln'
  4238. )
  4239. helper = LayerHelper('gammaln', **locals())
  4240. out = helper.create_variable_for_type_inference(x.dtype)
  4241. helper.append_op(type='gammaln', inputs={'x': x}, outputs={'out': out})
  4242. return out
  4243. @inplace_apis_in_dygraph_only
  4244. def gammaln_(x, name=None):
  4245. r"""
  4246. Inplace version of ``gammaln`` API, the output Tensor will be inplaced with input ``x``.
  4247. Please refer to :ref:`api_paddle_gammaln`.
  4248. """
  4249. if in_dynamic_mode():
  4250. return _C_ops.gammaln_(x)
  4251. def digamma(x, name=None):
  4252. r"""
  4253. Calculates the digamma of the given input tensor, element-wise.
  4254. .. math::
  4255. Out = \Psi(x) = \frac{ \Gamma^{'}(x) }{ \Gamma(x) }
  4256. Args:
  4257. x (Tensor): Input Tensor. Must be one of the following types: float32, float64.
  4258. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4259. Returns:
  4260. Tensor, the digamma of the input Tensor, the shape and data type is the same with input.
  4261. Examples:
  4262. .. code-block:: python
  4263. >>> import paddle
  4264. >>> data = paddle.to_tensor([[1, 1.5], [0, -2.2]], dtype='float32')
  4265. >>> res = paddle.digamma(data)
  4266. >>> res
  4267. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  4268. [[-0.57721591, 0.03648996],
  4269. [ nan , 5.32286835]])
  4270. """
  4271. if in_dynamic_or_pir_mode():
  4272. return _C_ops.digamma(x)
  4273. else:
  4274. check_variable_and_dtype(
  4275. x, 'x', ['float16', 'float32', 'float64', 'uint16'], 'digamma'
  4276. )
  4277. helper = LayerHelper('digamma', **locals())
  4278. out = helper.create_variable_for_type_inference(x.dtype)
  4279. helper.append_op(type='digamma', inputs={'X': x}, outputs={'Out': out})
  4280. return out
  4281. @inplace_apis_in_dygraph_only
  4282. def digamma_(x, name=None):
  4283. r"""
  4284. Inplace version of ``digamma`` API, the output Tensor will be inplaced with input ``x``.
  4285. Please refer to :ref:`api_paddle_digamma`.
  4286. """
  4287. if in_dynamic_mode():
  4288. return _C_ops.digamma_(x)
  4289. def gammaincc(x, y, name=None):
  4290. r"""
  4291. Computes the regularized upper incomplete gamma function.
  4292. .. math:: Q(x, y) = \frac{1}{\Gamma(x)} \int_{y}^{\infty} t^{x-1} e^{-t} dt
  4293. Args:
  4294. x (Tensor): The non-negative argument Tensor. Must be one of the following types: float32, float64.
  4295. y (Tensor): The positive parameter Tensor. Must be one of the following types: float32, float64.
  4296. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4297. Returns:
  4298. Tensor, the gammaincc of the input Tensor.
  4299. Examples:
  4300. .. code-block:: python
  4301. >>> import paddle
  4302. >>> x = paddle.to_tensor([0.5, 0.5, 0.5, 0.5, 0.5], dtype="float32")
  4303. >>> y = paddle.to_tensor([0, 1, 10, 100, 1000], dtype="float32")
  4304. >>> out = paddle.gammaincc(x, y)
  4305. >>> print(out)
  4306. Tensor(shape=[5], dtype=float32, place=Place(cpu), stop_gradient=True,
  4307. [1. , 0.15729916, 0.00000774, 0. , 0. ])
  4308. """
  4309. if not isinstance(x, Value) and not paddle.all(
  4310. paddle.greater_equal(x, paddle.zeros_like(x))
  4311. ):
  4312. raise ValueError(
  4313. "The input argument x must be greater than or equal to 0."
  4314. )
  4315. if not isinstance(x, Value) and not paddle.all(
  4316. paddle.greater_equal(y, paddle.zeros_like(y))
  4317. ):
  4318. raise ValueError(
  4319. "The input argument y must be greater than or equal to 0."
  4320. )
  4321. if in_dynamic_or_pir_mode():
  4322. return _C_ops.gammaincc(x, y)
  4323. else:
  4324. check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'gammaincc')
  4325. check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'gammaincc')
  4326. helper = LayerHelper('gammaincc', **locals())
  4327. out = helper.create_variable_for_type_inference(x.dtype)
  4328. helper.append_op(
  4329. type='gammaincc', inputs={'x': x, 'y': y}, outputs={'out': out}
  4330. )
  4331. return out
  4332. @inplace_apis_in_dygraph_only
  4333. def gammaincc_(x, y, name=None):
  4334. r"""
  4335. Inplace version of ``gammaincc`` API, the output Tensor will be inplaced with input ``x``.
  4336. Please refer to :ref:`api_paddle_gammaincc`.
  4337. """
  4338. if in_dynamic_mode():
  4339. return _C_ops.gammaincc_(x, y)
  4340. def gammainc(x, y, name=None):
  4341. r"""
  4342. Computes the regularized lower incomplete gamma function.
  4343. .. math:: P(x, y) = \frac{1}{\Gamma(x)} \int_{0}^{y} t^{x-1} e^{-t} dt
  4344. Args:
  4345. x (Tensor): The non-negative argument Tensor. Must be one of the following types: float32, float64.
  4346. y (Tensor): The positive parameter Tensor. Must be one of the following types: float32, float64.
  4347. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4348. Returns:
  4349. Tensor, the gammainc of the input Tensor.
  4350. Examples:
  4351. .. code-block:: python
  4352. >>> import paddle
  4353. >>> x = paddle.to_tensor([0.5, 0.5, 0.5, 0.5, 0.5], dtype="float32")
  4354. >>> y = paddle.to_tensor([0, 1, 10, 100, 1000], dtype="float32")
  4355. >>> out = paddle.gammainc(x, y)
  4356. >>> print(out)
  4357. Tensor(shape=[5], dtype=float32, place=Place(cpu), stop_gradient=True,
  4358. [0. , 0.84270084, 0.99999225, 1. , 1. ])
  4359. """
  4360. return 1 - paddle.gammaincc(x, y)
  4361. @inplace_apis_in_dygraph_only
  4362. def gammainc_(x, y, name=None):
  4363. r"""
  4364. Inplace version of ``gammainc`` API, the output Tensor will be inplaced with input ``x``.
  4365. Please refer to :ref:`api_paddle_gammainc`.
  4366. """
  4367. return (
  4368. paddle.gammaincc_(x, y)
  4369. .multiply_(paddle.full_like(x, -1.0))
  4370. .add_(paddle.full_like(x, 1.0))
  4371. )
  4372. def lgamma(x, name=None):
  4373. r"""
  4374. Calculates the lgamma of the given input tensor, element-wise.
  4375. This operator performs elementwise lgamma for input $X$.
  4376. :math:`out = log\Gamma(x)`
  4377. Args:
  4378. x (Tensor): Input Tensor. Must be one of the following types: float16, float32, float64, uint16.
  4379. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4380. Returns:
  4381. Tensor, the lgamma of the input Tensor, the shape and data type is the same with input.
  4382. Examples:
  4383. .. code-block:: python
  4384. >>> import paddle
  4385. >>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
  4386. >>> out = paddle.lgamma(x)
  4387. >>> out
  4388. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  4389. [1.31452453, 1.76149762, 2.25271273, 1.09579790])
  4390. """
  4391. if in_dynamic_or_pir_mode():
  4392. return _C_ops.lgamma(x)
  4393. else:
  4394. check_variable_and_dtype(
  4395. x, 'x', ['float16', 'float32', 'float64', 'uint16'], 'lgamma'
  4396. )
  4397. helper = LayerHelper('lgamma', **locals())
  4398. out = helper.create_variable_for_type_inference(x.dtype)
  4399. helper.append_op(type='lgamma', inputs={'X': x}, outputs={'Out': out})
  4400. return out
  4401. @inplace_apis_in_dygraph_only
  4402. def lgamma_(x, name=None):
  4403. r"""
  4404. Inplace version of ``lgamma`` API, the output Tensor will be inplaced with input ``x``.
  4405. Please refer to :ref:`api_paddle_lgamma`.
  4406. """
  4407. if in_dynamic_mode():
  4408. return _C_ops.lgamma_(x)
  4409. def multigammaln(x, p, name=None):
  4410. """
  4411. This function computes the log of multivariate gamma, also sometimes called the generalized gamma.
  4412. Args:
  4413. x (Tensor): Input Tensor. Must be one of the following types: float16, float32, float64, uint16.
  4414. p (int): The dimension of the space of integration.
  4415. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4416. Returns:
  4417. out (Tensor): The values of the log multivariate gamma at the given tensor x.
  4418. Examples:
  4419. .. code-block:: python
  4420. >>> import paddle
  4421. >>> x = paddle.to_tensor([2.5, 3.5, 4, 6.5, 7.8, 10.23, 34.25])
  4422. >>> p = 2
  4423. >>> out = paddle.multigammaln(x, p)
  4424. >>> print(out)
  4425. Tensor(shape=[7], dtype=float32, place=Place(cpu), stop_gradient=True,
  4426. [0.85704780 , 2.46648574 , 3.56509781 , 11.02241898 , 15.84497833 ,
  4427. 26.09257698 , 170.68318176])
  4428. """
  4429. assert p >= 1, (
  4430. "The p must be greater than or equal to 1, "
  4431. "But received p is %s.\n" % p
  4432. )
  4433. c = 0.25 * p * (p - 1) * math.log(math.pi)
  4434. b = 0.5 * paddle.arange(start=(1 - p), end=1, step=1, dtype=x.dtype)
  4435. return paddle.sum(paddle.lgamma(x.unsqueeze(-1) + b), axis=-1) + c
  4436. @inplace_apis_in_dygraph_only
  4437. def multigammaln_(x, p, name=None):
  4438. r"""
  4439. Inplace version of ``multigammaln_`` API, the output Tensor will be inplaced with input ``x``.
  4440. Please refer to :ref:`api_paddle_multigammaln`.
  4441. """
  4442. assert p >= 1, (
  4443. "The p must be greater than or equal to 1, "
  4444. "But received p is %s.\n" % p
  4445. )
  4446. c = 0.25 * p * (p - 1) * math.log(math.pi)
  4447. c = paddle.to_tensor(c, dtype=x.dtype)
  4448. b = 0.5 * paddle.arange(start=(1 - p), end=1, step=1, dtype=x.dtype)
  4449. paddle.assign((x.unsqueeze(-1) + b).lgamma_().sum(-1).add_(c), x)
  4450. return x
  4451. def neg(x, name=None):
  4452. """
  4453. This function computes the negative of the Tensor elementwisely.
  4454. Args:
  4455. x (Tensor): Input of neg operator, an N-D Tensor, with data type float32, float64, int8, int16, int32, or int64.
  4456. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4457. Returns:
  4458. out (Tensor): The negative of input Tensor. The shape and data type are the same with input Tensor.
  4459. Examples:
  4460. .. code-block:: python
  4461. >>> import paddle
  4462. >>> x = paddle.to_tensor([-0.4, -0.2, 0.1, 0.3])
  4463. >>> out = paddle.neg(x)
  4464. >>> out
  4465. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  4466. [ 0.40000001, 0.20000000, -0.10000000, -0.30000001])
  4467. """
  4468. return scale(
  4469. x, scale=-1.0, bias=0.0, bias_after_scale=True, act=None, name=name
  4470. )
  4471. @inplace_apis_in_dygraph_only
  4472. def neg_(x, name=None):
  4473. r"""
  4474. Inplace version of ``neg`` API, the output Tensor will be inplaced with input ``x``.
  4475. Please refer to :ref:`api_paddle_neg`.
  4476. """
  4477. return x.scale_(
  4478. scale=-1.0, bias=0.0, bias_after_scale=True, act=None, name=name
  4479. )
  4480. def atan2(x, y, name=None):
  4481. r"""
  4482. Element-wise arctangent of x/y with consideration of the quadrant.
  4483. Equation:
  4484. .. math::
  4485. atan2(x,y)=\left\{\begin{matrix}
  4486. & tan^{-1}(\frac{x}{y}) & y > 0 \\
  4487. & tan^{-1}(\frac{x}{y}) + \pi & x>=0, y < 0 \\
  4488. & tan^{-1}(\frac{x}{y}) - \pi & x<0, y < 0 \\
  4489. & +\frac{\pi}{2} & x>0, y = 0 \\
  4490. & -\frac{\pi}{2} & x<0, y = 0 \\
  4491. &\text{undefined} & x=0, y = 0
  4492. \end{matrix}\right.
  4493. Args:
  4494. x (Tensor): An N-D Tensor, the data type is int32, int64, float16, float32, float64.
  4495. y (Tensor): An N-D Tensor, must have the same type as `x`.
  4496. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4497. Returns:
  4498. out (Tensor): An N-D Tensor, the shape and data type is the same with input (The output data type is float64 when the input data type is int).
  4499. Examples:
  4500. .. code-block:: python
  4501. >>> import paddle
  4502. >>> x = paddle.to_tensor([-1, +1, +1, -1]).astype('float32')
  4503. >>> x
  4504. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  4505. [-1, 1, 1, -1])
  4506. >>> y = paddle.to_tensor([-1, -1, +1, +1]).astype('float32')
  4507. >>> y
  4508. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  4509. [-1, -1, 1, 1])
  4510. >>> out = paddle.atan2(x, y)
  4511. >>> out
  4512. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  4513. [-2.35619450, 2.35619450, 0.78539819, -0.78539819])
  4514. """
  4515. if in_dynamic_or_pir_mode():
  4516. return _C_ops.atan2(x, y)
  4517. else:
  4518. check_variable_and_dtype(
  4519. x,
  4520. 'x',
  4521. ['int32', 'int64', 'float16', 'float32', 'float64'],
  4522. 'atan2',
  4523. )
  4524. check_variable_and_dtype(
  4525. y,
  4526. 'y',
  4527. ['int32', 'int64', 'float16', 'float32', 'float64'],
  4528. 'atan2',
  4529. )
  4530. helper = LayerHelper('atan2', **locals())
  4531. inputs = {'X1': x, 'X2': y}
  4532. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  4533. helper.append_op(type='atan2', inputs=inputs, outputs={'Out': out})
  4534. return out
  4535. def logit(x, eps=None, name=None):
  4536. r"""
  4537. This function generates a new tensor with the logit of the elements of input x. x is clamped to [eps, 1-eps] when eps is not zero. When eps is zero and x < 0 or x > 1, the function will yields NaN.
  4538. .. math::
  4539. logit(x) = ln(\frac{x}{1 - x})
  4540. where
  4541. .. math::
  4542. x_i=
  4543. \left\{\begin{array}{rcl}
  4544. x_i & &\text{if } eps == Default \\
  4545. eps & &\text{if } x_i < eps \\
  4546. x_i & &\text{if } eps <= x_i <= 1-eps \\
  4547. 1-eps & &\text{if } x_i > 1-eps
  4548. \end{array}\right.
  4549. Args:
  4550. x (Tensor): The input Tensor with data type bfloat16, float16, float32, float64.
  4551. eps (float, optional): the epsilon for input clamp bound. Default is None.
  4552. name (str, optional): Name for the operation (optional, default is None).
  4553. For more information, please refer to :ref:`api_guide_Name`.
  4554. Returns:
  4555. out(Tensor): A Tensor with the same data type and shape as ``x`` .
  4556. Examples:
  4557. .. code-block:: python
  4558. >>> import paddle
  4559. >>> x = paddle.to_tensor([0.2635, 0.0106, 0.2780, 0.2097, 0.8095])
  4560. >>> out1 = paddle.logit(x)
  4561. >>> out1
  4562. Tensor(shape=[5], dtype=float32, place=Place(cpu), stop_gradient=True,
  4563. [-1.02785587, -4.53624487, -0.95440406, -1.32673466, 1.44676447])
  4564. """
  4565. if eps is None:
  4566. eps = 0.0
  4567. if in_dynamic_or_pir_mode():
  4568. return _C_ops.logit(x, eps)
  4569. else:
  4570. check_variable_and_dtype(
  4571. x, 'x', ['float16', 'uint16', 'float32', 'float64'], 'logit'
  4572. )
  4573. helper = LayerHelper("logit", **locals())
  4574. out = helper.create_variable_for_type_inference(x.dtype)
  4575. helper.append_op(
  4576. type='logit',
  4577. inputs={'X': x},
  4578. outputs={'Out': out},
  4579. attrs={'eps': eps},
  4580. )
  4581. return out
  4582. @inplace_apis_in_dygraph_only
  4583. def logit_(x, eps=None, name=None):
  4584. r"""
  4585. Inplace version of ``logit`` API, the output Tensor will be inplaced with input ``x``.
  4586. Please refer to :ref:`api_paddle_logit`.
  4587. """
  4588. if eps is None:
  4589. eps = 0.0
  4590. if in_dynamic_mode():
  4591. return _C_ops.logit_(x, eps)
  4592. def lerp(x, y, weight, name=None):
  4593. r"""
  4594. Does a linear interpolation between x and y based on weight.
  4595. Equation:
  4596. .. math::
  4597. lerp(x, y, weight) = x + weight * (y - x).
  4598. Args:
  4599. x (Tensor): An N-D Tensor with starting points, the data type is bfloat16, float16, float32, float64.
  4600. y (Tensor): An N-D Tensor with ending points, the data type is bfloat16, float16, float32, float64.
  4601. weight (float|Tensor): The weight for the interpolation formula. When weight is Tensor, the data type is bfloat16, float16, float32, float64.
  4602. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4603. Returns:
  4604. out (Tensor): An N-D Tensor, the shape and data type is the same with input.
  4605. Example:
  4606. .. code-block:: python
  4607. >>> import paddle
  4608. >>> x = paddle.arange(1., 5., dtype='float32')
  4609. >>> y = paddle.empty([4], dtype='float32')
  4610. >>> y.fill_(10.)
  4611. >>> out = paddle.lerp(x, y, 0.5)
  4612. >>> out
  4613. Tensor(shape=[4], dtype=float32, place=Place(cpu), stop_gradient=True,
  4614. [5.50000000, 6. , 6.50000000, 7. ])
  4615. """
  4616. if isinstance(weight, float):
  4617. weight = paddle.full(shape=[], fill_value=weight, dtype=x.dtype)
  4618. if in_dynamic_or_pir_mode():
  4619. return _C_ops.lerp(x, y, weight)
  4620. else:
  4621. check_variable_and_dtype(
  4622. x, 'x', ['uint16', 'float16', 'float32', 'float64'], 'lerp'
  4623. )
  4624. check_variable_and_dtype(
  4625. y, 'y', ['uint16', 'float16', 'float32', 'float64'], 'lerp'
  4626. )
  4627. check_variable_and_dtype(
  4628. weight,
  4629. 'weight',
  4630. ['uint16', 'float16', 'float32', 'float64'],
  4631. 'lerp',
  4632. )
  4633. helper = LayerHelper('lerp', **locals())
  4634. inputs = {'X': x, 'Y': y, 'Weight': weight}
  4635. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  4636. helper.append_op(type='lerp', inputs=inputs, outputs={'Out': out})
  4637. return out
  4638. @inplace_apis_in_dygraph_only
  4639. def lerp_(x, y, weight, name=None):
  4640. r"""
  4641. Inplace version of ``lerp`` API, the output Tensor will be inplaced with input ``x``.
  4642. Please refer to :ref:`api_paddle_lerp`.
  4643. """
  4644. out_shape = broadcast_shape(x.shape, y.shape)
  4645. check_type(weight, 'weight', (float, paddle.Tensor, Variable), 'lerp')
  4646. if isinstance(weight, float):
  4647. weight = paddle.to_tensor([weight], dtype=x.dtype)
  4648. elif isinstance(weight, (paddle.Tensor, Variable)):
  4649. out_shape = broadcast_shape(out_shape, weight.shape)
  4650. if out_shape != x.shape:
  4651. raise ValueError(
  4652. f"The shape of broadcast output {out_shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  4653. )
  4654. return _C_ops.lerp_(x, y, weight)
  4655. def erfinv(x, name=None):
  4656. r"""
  4657. The inverse error function of x. Please refer to :ref:`api_paddle_erf`
  4658. .. math::
  4659. erfinv(erf(x)) = x.
  4660. Args:
  4661. x (Tensor): An N-D Tensor, the data type is float16, bfloat16, float32, float64.
  4662. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4663. Returns:
  4664. out (Tensor), an N-D Tensor, the shape and data type is the same with input.
  4665. Example:
  4666. .. code-block:: python
  4667. >>> import paddle
  4668. >>> x = paddle.to_tensor([0, 0.5, -1.], dtype="float32")
  4669. >>> out = paddle.erfinv(x)
  4670. >>> out
  4671. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  4672. [ 0. , 0.47693631, -inf. ])
  4673. """
  4674. if in_dynamic_or_pir_mode():
  4675. return _C_ops.erfinv(x)
  4676. else:
  4677. check_variable_and_dtype(
  4678. x, 'x', ['float32', 'float64', 'float16', 'uint16'], 'erfinv'
  4679. )
  4680. helper = LayerHelper('erfinv', **locals())
  4681. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  4682. helper.append_op(type='erfinv', inputs={'X': x}, outputs={'Out': out})
  4683. return out
  4684. @inplace_apis_in_dygraph_only
  4685. def erfinv_(x, name=None):
  4686. r"""
  4687. Inplace version of ``erfinv`` API, the output Tensor will be inplaced with input ``x``.
  4688. Please refer to :ref:`api_paddle_erfinv`.
  4689. """
  4690. check_type(x, 'x', (paddle.Tensor, Variable), 'erfinv')
  4691. return _C_ops.erfinv_(x)
  4692. def rad2deg(x, name=None):
  4693. r"""
  4694. Convert each of the elements of input x from angles in radians to degrees.
  4695. Equation:
  4696. .. math::
  4697. rad2deg(x)=180/ \pi * x
  4698. Args:
  4699. x (Tensor): An N-D Tensor, the data type is float32, float64, int32, int64.
  4700. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4701. Returns:
  4702. out (Tensor): An N-D Tensor, the shape and data type is the same with input (The output data type is float32 when the input data type is int).
  4703. Examples:
  4704. .. code-block:: python
  4705. >>> import paddle
  4706. >>> import math
  4707. >>> x1 = paddle.to_tensor([3.142, -3.142, 6.283, -6.283, 1.570, -1.570])
  4708. >>> result1 = paddle.rad2deg(x1)
  4709. >>> result1
  4710. Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
  4711. [ 180.02334595, -180.02334595, 359.98937988, -359.98937988,
  4712. 89.95437622 , -89.95437622 ])
  4713. >>> x2 = paddle.to_tensor(math.pi/2)
  4714. >>> result2 = paddle.rad2deg(x2)
  4715. >>> result2
  4716. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  4717. 90.)
  4718. >>> x3 = paddle.to_tensor(1)
  4719. >>> result3 = paddle.rad2deg(x3)
  4720. >>> result3
  4721. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  4722. 57.29578018)
  4723. """
  4724. rad2deg_scale = 180 / np.pi
  4725. if in_dynamic_or_pir_mode():
  4726. if convert_dtype(x.dtype) in ['int32', 'int64']:
  4727. x = cast(x, dtype="float32")
  4728. return _C_ops.scale(x, rad2deg_scale, 0.0, True)
  4729. else:
  4730. check_variable_and_dtype(
  4731. x, 'x', ['int32', 'int64', 'float32', 'float64'], 'rad2deg'
  4732. )
  4733. helper = LayerHelper('rad2deg', **locals())
  4734. out_cast = x
  4735. if convert_dtype(x.dtype) in ['int32', 'int64']:
  4736. out_cast = helper.create_variable_for_type_inference(
  4737. dtype=paddle.float32
  4738. )
  4739. helper.append_op(
  4740. type='cast',
  4741. inputs={'X': x},
  4742. outputs={'Out': out_cast},
  4743. attrs={'in_dtype': x.dtype, 'out_dtype': paddle.float32},
  4744. )
  4745. out = helper.create_variable_for_type_inference(dtype=out_cast.dtype)
  4746. helper.append_op(
  4747. type='scale',
  4748. inputs={'X': out_cast},
  4749. outputs={'Out': out},
  4750. attrs={'scale': rad2deg_scale},
  4751. )
  4752. return out
  4753. def deg2rad(x, name=None):
  4754. r"""
  4755. Convert each of the elements of input x from degrees to angles in radians.
  4756. .. math::
  4757. deg2rad(x)=\pi * x / 180
  4758. Args:
  4759. x (Tensor): An N-D Tensor, the data type is float32, float64, int32, int64.
  4760. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4761. Returns:
  4762. out (Tensor): An N-D Tensor, the shape and data type is the same with input (The output data type is float32 when the input data type is int).
  4763. Examples:
  4764. .. code-block:: python
  4765. >>> import paddle
  4766. >>> x1 = paddle.to_tensor([180.0, -180.0, 360.0, -360.0, 90.0, -90.0])
  4767. >>> result1 = paddle.deg2rad(x1)
  4768. >>> result1
  4769. Tensor(shape=[6], dtype=float32, place=Place(cpu), stop_gradient=True,
  4770. [3.14159274, -3.14159274, 6.28318548, -6.28318548, 1.57079637,
  4771. -1.57079637])
  4772. >>> x2 = paddle.to_tensor(180)
  4773. >>> result2 = paddle.deg2rad(x2)
  4774. >>> result2
  4775. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  4776. 3.14159274)
  4777. """
  4778. deg2rad_scale = np.pi / 180.0
  4779. if in_dynamic_or_pir_mode():
  4780. if convert_dtype(x.dtype) in ['int32', 'int64']:
  4781. x = cast(x, dtype="float32")
  4782. return _C_ops.scale(x, deg2rad_scale, 0.0, True)
  4783. else:
  4784. check_variable_and_dtype(
  4785. x, 'x', ['int32', 'int64', 'float32', 'float64'], 'deg2rad'
  4786. )
  4787. helper = LayerHelper('deg2rad', **locals())
  4788. out_cast = x
  4789. if convert_dtype(x.dtype) in ['int32', 'int64']:
  4790. out_cast = helper.create_variable_for_type_inference(
  4791. dtype=paddle.float32
  4792. )
  4793. helper.append_op(
  4794. type='cast',
  4795. inputs={'X': x},
  4796. outputs={'Out': out_cast},
  4797. attrs={'in_dtype': x.dtype, 'out_dtype': paddle.float32},
  4798. )
  4799. out = helper.create_variable_for_type_inference(dtype=out_cast.dtype)
  4800. helper.append_op(
  4801. type='scale',
  4802. inputs={'X': out_cast},
  4803. outputs={'Out': out},
  4804. attrs={'scale': deg2rad_scale},
  4805. )
  4806. return out
  4807. def gcd(x, y, name=None):
  4808. """
  4809. Computes the element-wise greatest common divisor (GCD) of input |x| and |y|.
  4810. Both x and y must have integer types.
  4811. Note:
  4812. gcd(0,0)=0, gcd(0, y)=|y|
  4813. If x.shape != y.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
  4814. Args:
  4815. x (Tensor): An N-D Tensor, the data type is int32, int64.
  4816. y (Tensor): An N-D Tensor, the data type is int32, int64.
  4817. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4818. Returns:
  4819. out (Tensor): An N-D Tensor, the data type is the same with input.
  4820. Examples:
  4821. .. code-block:: python
  4822. >>> import paddle
  4823. >>> x1 = paddle.to_tensor(12)
  4824. >>> x2 = paddle.to_tensor(20)
  4825. >>> paddle.gcd(x1, x2)
  4826. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  4827. 4)
  4828. >>> x3 = paddle.arange(6)
  4829. >>> paddle.gcd(x3, x2)
  4830. Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
  4831. [20, 1 , 2 , 1 , 4 , 5])
  4832. >>> x4 = paddle.to_tensor(0)
  4833. >>> paddle.gcd(x4, x2)
  4834. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  4835. 20)
  4836. >>> paddle.gcd(x4, x4)
  4837. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  4838. 0)
  4839. >>> x5 = paddle.to_tensor(-20)
  4840. >>> paddle.gcd(x1, x5)
  4841. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  4842. 4)
  4843. """
  4844. shape = paddle.broadcast_shape(x.shape, y.shape)
  4845. x = paddle.broadcast_to(x, shape)
  4846. y = paddle.broadcast_to(y, shape)
  4847. x = paddle.abs(x)
  4848. y = paddle.abs(y)
  4849. def _gcd_cond_fn(x, y):
  4850. return paddle.any(y != 0)
  4851. def _gcd_body_fn(x, y):
  4852. # paddle.mod will raise an error when any element of y is 0. To avoid
  4853. # that, we change those zeros to ones. Their values don't matter because
  4854. # they won't be used.
  4855. y_not_equal_0 = y != 0
  4856. y_safe = paddle.where(y_not_equal_0, y, paddle.ones(y.shape, y.dtype))
  4857. x, y = (
  4858. paddle.where(y_not_equal_0, y, x),
  4859. paddle.where(
  4860. y_not_equal_0,
  4861. paddle.mod(x, y_safe),
  4862. paddle.zeros(y.shape, y.dtype),
  4863. ),
  4864. )
  4865. return (paddle.where(x < y, y, x), paddle.where(x < y, x, y))
  4866. if in_dynamic_mode():
  4867. while _gcd_cond_fn(x, y):
  4868. x, y = _gcd_body_fn(x, y)
  4869. return x
  4870. else:
  4871. check_variable_and_dtype(x, 'x', ['int32', 'int64'], 'gcd')
  4872. check_variable_and_dtype(y, 'y', ['int32', 'int64'], 'gcd')
  4873. out, _ = paddle.static.nn.while_loop(_gcd_cond_fn, _gcd_body_fn, [x, y])
  4874. return out
  4875. def gcd_(x, y, name=None):
  4876. r"""
  4877. Inplace version of ``gcd`` API, the output Tensor will be inplaced with input ``x``.
  4878. Please refer to :ref:`api_paddle_gcd`.
  4879. """
  4880. shape = paddle.broadcast_shape(x.shape, y.shape)
  4881. if shape != x.shape:
  4882. raise ValueError(
  4883. f"The shape of broadcast output {shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  4884. )
  4885. y = paddle.broadcast_to(y, shape)
  4886. x = paddle.abs_(x)
  4887. y = paddle.abs(y)
  4888. def _gcd_cond_fn(x, y):
  4889. return paddle.any(y != 0)
  4890. def _gcd_body_fn(x, y):
  4891. # paddle.mod will raise an error when any element of y is 0. To avoid
  4892. # that, we change those zeros to ones. Their values don't matter because
  4893. # they won't be used.
  4894. y_equal_0 = y == 0
  4895. y_safe = paddle.where(y_equal_0, paddle.ones(y.shape, y.dtype), y)
  4896. y, x = (
  4897. paddle.where(
  4898. y_equal_0,
  4899. paddle.zeros(y.shape, y.dtype),
  4900. paddle.mod(x, y_safe),
  4901. ),
  4902. paddle.where_(y_equal_0, x, y),
  4903. )
  4904. return (
  4905. paddle.where(x < y, x, y),
  4906. paddle.where_(x >= y, x, y),
  4907. )
  4908. if in_dynamic_mode():
  4909. while _gcd_cond_fn(x, y):
  4910. y, x = _gcd_body_fn(x, y)
  4911. return x
  4912. def lcm(x, y, name=None):
  4913. """
  4914. Computes the element-wise least common multiple (LCM) of input |x| and |y|.
  4915. Both x and y must have integer types.
  4916. Note:
  4917. lcm(0,0)=0, lcm(0, y)=0
  4918. If x.shape != y.shape, they must be broadcastable to a common shape (which becomes the shape of the output).
  4919. Args:
  4920. x (Tensor): An N-D Tensor, the data type is int32, int64.
  4921. y (Tensor): An N-D Tensor, the data type is int32, int64.
  4922. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4923. Returns:
  4924. out (Tensor): An N-D Tensor, the data type is the same with input.
  4925. Examples:
  4926. .. code-block:: python
  4927. >>> import paddle
  4928. >>> x1 = paddle.to_tensor(12)
  4929. >>> x2 = paddle.to_tensor(20)
  4930. >>> paddle.lcm(x1, x2)
  4931. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  4932. 60)
  4933. >>> x3 = paddle.arange(6)
  4934. >>> paddle.lcm(x3, x2)
  4935. Tensor(shape=[6], dtype=int64, place=Place(cpu), stop_gradient=True,
  4936. [0, 20, 20, 60, 20, 20])
  4937. >>> x4 = paddle.to_tensor(0)
  4938. >>> paddle.lcm(x4, x2)
  4939. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  4940. 0)
  4941. >>> paddle.lcm(x4, x4)
  4942. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  4943. 0)
  4944. >>> x5 = paddle.to_tensor(-20)
  4945. >>> paddle.lcm(x1, x5)
  4946. Tensor(shape=[], dtype=int64, place=Place(cpu), stop_gradient=True,
  4947. 60)
  4948. """
  4949. d = paddle.gcd(x, y)
  4950. # paddle.mod will raise an error when any element of y is 0. To avoid
  4951. # that, we change those zeros to ones. Their values don't matter because
  4952. # they won't be used.
  4953. d_equal_0 = paddle.equal(d, 0)
  4954. d_safe = paddle.where(d_equal_0, paddle.ones(d.shape, d.dtype), d)
  4955. out = paddle.where(
  4956. d_equal_0, paddle.zeros(d.shape, d.dtype), paddle.abs(x * y) // d_safe
  4957. )
  4958. return out
  4959. def lcm_(x, y, name=None):
  4960. r"""
  4961. Inplace version of ``lcm`` API, the output Tensor will be inplaced with input ``x``.
  4962. Please refer to :ref:`api_paddle_lcm`.
  4963. """
  4964. d = paddle.gcd(x, y)
  4965. # paddle.mod will raise an error when any element of y is 0. To avoid
  4966. # that, we change those zeros to ones. Their values don't matter because
  4967. # they won't be used.
  4968. d_not_equal_0 = d != 0
  4969. d_safe = paddle.where(d_not_equal_0, d, paddle.ones(d.shape, d.dtype))
  4970. out = paddle.where_(
  4971. d_not_equal_0,
  4972. paddle.abs_(x.multiply_(y)).floor_divide_(d_safe),
  4973. paddle.zeros(d.shape, d.dtype),
  4974. )
  4975. return out
  4976. def diff(x, n=1, axis=-1, prepend=None, append=None, name=None):
  4977. r"""
  4978. Computes the n-th forward difference along the given axis.
  4979. The first-order differences is computed by using the following formula:
  4980. .. math::
  4981. out[i] = x[i+1] - x[i]
  4982. Higher-order differences are computed by using paddle.diff() recursively.
  4983. The number of n supports any positive integer value.
  4984. Args:
  4985. x (Tensor): The input tensor to compute the forward difference on, the data type is float16, float32, float64, bool, int32, int64.
  4986. n (int, optional): The number of times to recursively compute the difference.
  4987. Supports any positive integer value. Default:1
  4988. axis (int, optional): The axis to compute the difference along. Default:-1
  4989. prepend (Tensor, optional): The tensor to prepend to input along axis before computing the difference.
  4990. It's dimensions must be equivalent to that of x,
  4991. and its shapes must match x's shape except on axis.
  4992. append (Tensor, optional): The tensor to append to input along axis before computing the difference,
  4993. It's dimensions must be equivalent to that of x,
  4994. and its shapes must match x's shape except on axis.
  4995. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  4996. Returns:
  4997. Tensor: The output tensor with same dtype with x.
  4998. Examples:
  4999. .. code-block:: python
  5000. >>> import paddle
  5001. >>> x = paddle.to_tensor([1, 4, 5, 2])
  5002. >>> out = paddle.diff(x)
  5003. >>> out
  5004. Tensor(shape=[3], dtype=int64, place=Place(cpu), stop_gradient=True,
  5005. [ 3, 1, -3])
  5006. >>> x_2 = paddle.to_tensor([1, 4, 5, 2])
  5007. >>> out = paddle.diff(x_2, n=2)
  5008. >>> out
  5009. Tensor(shape=[2], dtype=int64, place=Place(cpu), stop_gradient=True,
  5010. [ -2, -4])
  5011. >>> y = paddle.to_tensor([7, 9])
  5012. >>> out = paddle.diff(x, append=y)
  5013. >>> out
  5014. Tensor(shape=[5], dtype=int64, place=Place(cpu), stop_gradient=True,
  5015. [ 3, 1, -3, 5, 2])
  5016. >>> z = paddle.to_tensor([[1, 2, 3], [4, 5, 6]])
  5017. >>> out = paddle.diff(z, axis=0)
  5018. >>> out
  5019. Tensor(shape=[1, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  5020. [[3, 3, 3]])
  5021. >>> out = paddle.diff(z, axis=1)
  5022. >>> out
  5023. Tensor(shape=[2, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
  5024. [[1, 1],
  5025. [1, 1]])
  5026. """
  5027. if n < 1:
  5028. raise ValueError(
  5029. f"Diff expects input to be at least one-dimensional but got {n}"
  5030. )
  5031. def _diff_handler(x, n=1, axis=-1, prepend=None, append=None, name=None):
  5032. if axis < 0:
  5033. axis = axis + len(x.shape)
  5034. if axis > len(x.shape):
  5035. axis = len(x.shape)
  5036. if axis < 0:
  5037. axis = 0
  5038. dtype = x.dtype
  5039. axes = [axis]
  5040. infer_flags = [1 for i in range(len(axes))]
  5041. if in_dynamic_or_pir_mode():
  5042. has_pend = False
  5043. input_list = []
  5044. if prepend is not None and append is not None:
  5045. input_list = [prepend, x, append]
  5046. has_pend = True
  5047. elif prepend is not None:
  5048. input_list = [prepend, x]
  5049. has_pend = True
  5050. elif append is not None:
  5051. input_list = [x, append]
  5052. has_pend = True
  5053. if has_pend:
  5054. new_input = _C_ops.concat(input_list, axis)
  5055. else:
  5056. new_input = x
  5057. attrs_1 = ()
  5058. attrs_2 = ()
  5059. dim_len = new_input.shape[axis]
  5060. starts_1 = [0]
  5061. attrs_1 += ('starts', starts_1)
  5062. ends_1 = [dim_len - 1]
  5063. attrs_1 += ('ends', ends_1)
  5064. input_front = _C_ops.slice(
  5065. new_input, axes, starts_1, ends_1, infer_flags, []
  5066. )
  5067. starts_2 = [1]
  5068. attrs_2 += ('starts', starts_2)
  5069. ends_2 = [dim_len]
  5070. attrs_2 += ('ends', ends_2)
  5071. input_back = _C_ops.slice(
  5072. new_input, axes, starts_2, ends_2, infer_flags, []
  5073. )
  5074. if x.dtype == paddle.bool or x.dtype == core.DataType.BOOL:
  5075. return _C_ops.logical_xor(input_back, input_front)
  5076. else:
  5077. return _C_ops.subtract(input_back, input_front)
  5078. else:
  5079. check_variable_and_dtype(
  5080. x,
  5081. 'x',
  5082. ['float16', 'float32', 'float64', 'bool', 'int32', 'int64'],
  5083. 'diff',
  5084. )
  5085. check_type(axis, 'axis', (int), 'diff')
  5086. helper = LayerHelper('diff', **locals())
  5087. has_pend = False
  5088. input_list = []
  5089. if prepend is not None and append is not None:
  5090. input_list = [prepend, x, append]
  5091. has_pend = True
  5092. elif prepend is not None:
  5093. input_list = [prepend, x]
  5094. has_pend = True
  5095. elif append is not None:
  5096. input_list = [x, append]
  5097. has_pend = True
  5098. if has_pend:
  5099. new_input = helper.create_variable_for_type_inference(dtype)
  5100. helper.append_op(
  5101. type='concat',
  5102. inputs={'X': input_list},
  5103. outputs={'Out': [new_input]},
  5104. attrs={'axis': axis},
  5105. )
  5106. else:
  5107. new_input = x
  5108. dim_len = new_input.shape[axis]
  5109. attrs_1 = {'axes': axes}
  5110. starts_1 = [0]
  5111. ends_1 = [dim_len - 1]
  5112. attrs_1['starts'] = starts_1
  5113. attrs_1['ends'] = ends_1
  5114. input_front = helper.create_variable_for_type_inference(dtype)
  5115. helper.append_op(
  5116. type='slice',
  5117. inputs={'Input': new_input},
  5118. attrs=attrs_1,
  5119. outputs={'Out': input_front},
  5120. )
  5121. attrs_2 = {'axes': axes}
  5122. starts_2 = [1]
  5123. ends_2 = [dim_len]
  5124. attrs_2['starts'] = starts_2
  5125. attrs_2['ends'] = ends_2
  5126. input_back = helper.create_variable_for_type_inference(dtype)
  5127. helper.append_op(
  5128. type='slice',
  5129. inputs={'Input': new_input},
  5130. attrs=attrs_2,
  5131. outputs={'Out': input_back},
  5132. )
  5133. if dtype == paddle.bool:
  5134. out = helper.create_variable_for_type_inference(dtype)
  5135. helper.append_op(
  5136. type='logical_xor',
  5137. inputs={"X": input_back, "Y": input_front},
  5138. outputs={"Out": out},
  5139. )
  5140. else:
  5141. out = paddle.tensor.math.subtract(input_back, input_front)
  5142. return out
  5143. out = _diff_handler(
  5144. x, n=1, axis=axis, prepend=prepend, append=append, name=name
  5145. )
  5146. if n > 1:
  5147. for _ in range(n - 1):
  5148. out = _diff_handler(
  5149. out, n=1, axis=axis, prepend=prepend, append=append, name=name
  5150. )
  5151. return out
  5152. def angle(x, name=None):
  5153. r"""
  5154. Element-wise angle of complex numbers. For non-negative real numbers, the angle is 0 while
  5155. for negative real numbers, the angle is :math:`\pi`.
  5156. Equation:
  5157. .. math::
  5158. angle(x)=arctan2(x.imag, x.real)
  5159. Args:
  5160. x (Tensor): An N-D Tensor, the data type is complex64, complex128, or float32, float64 .
  5161. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  5162. Returns:
  5163. Tensor: An N-D Tensor of real data type with the same precision as that of x's data type.
  5164. Examples:
  5165. .. code-block:: python
  5166. >>> import paddle
  5167. >>> x = paddle.to_tensor([-2, -1, 0, 1]).unsqueeze(-1).astype('float32')
  5168. >>> y = paddle.to_tensor([-2, -1, 0, 1]).astype('float32')
  5169. >>> z = x + 1j * y
  5170. >>> z
  5171. Tensor(shape=[4, 4], dtype=complex64, place=Place(cpu), stop_gradient=True,
  5172. [[(-2-2j), (-2-1j), (-2+0j), (-2+1j)],
  5173. [(-1-2j), (-1-1j), (-1+0j), (-1+1j)],
  5174. [-2j , -1j , 0j , 1j ],
  5175. [ (1-2j), (1-1j), (1+0j), (1+1j)]])
  5176. >>> theta = paddle.angle(z)
  5177. >>> theta
  5178. Tensor(shape=[4, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  5179. [[-2.35619450, -2.67794514, 3.14159274, 2.67794514],
  5180. [-2.03444386, -2.35619450, 3.14159274, 2.35619450],
  5181. [-1.57079637, -1.57079637, 0. , 1.57079637],
  5182. [-1.10714877, -0.78539819, 0. , 0.78539819]])
  5183. """
  5184. if in_dynamic_or_pir_mode():
  5185. return _C_ops.angle(x)
  5186. else:
  5187. check_variable_and_dtype(
  5188. x,
  5189. 'x',
  5190. [
  5191. 'float16',
  5192. 'float32',
  5193. 'float64',
  5194. 'complex64',
  5195. 'complex128',
  5196. 'uint16',
  5197. ],
  5198. 'angle',
  5199. )
  5200. op_type = "angle"
  5201. helper = LayerHelper(op_type, **locals())
  5202. inputs = {"X": x}
  5203. out = helper.create_variable_for_type_inference(
  5204. dtype=_complex_to_real_dtype(x.dtype)
  5205. )
  5206. outputs = {"Out": out}
  5207. helper.append_op(type=op_type, inputs=inputs, outputs=outputs)
  5208. return out
  5209. def heaviside(x, y, name=None):
  5210. r"""
  5211. Computes the Heaviside step function determined by corresponding element in y for each element in x. The equation is
  5212. .. math::
  5213. heaviside(x, y)=
  5214. \left\{
  5215. \begin{array}{lcl}
  5216. 0,& &\text{if} \ x < 0, \\
  5217. y,& &\text{if} \ x = 0, \\
  5218. 1,& &\text{if} \ x > 0.
  5219. \end{array}
  5220. \right.
  5221. Note:
  5222. ``paddle.heaviside`` supports broadcasting. If you want know more about broadcasting, please refer to `Introduction to Tensor`_ .
  5223. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  5224. Args:
  5225. x (Tensor): The input tensor of Heaviside step function, it's data type should be float16, float32, float64, int32 or int64.
  5226. y (Tensor): The tensor that determines a Heaviside step function, it's data type should be float16, float32, float64, int32 or int64.
  5227. name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`.
  5228. Returns:
  5229. N-D Tensor. A location into which the result is stored. If x and y have different shapes and are broadcastable, the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y.
  5230. Examples:
  5231. .. code-block:: python
  5232. >>> import paddle
  5233. >>> x = paddle.to_tensor([-0.5, 0, 0.5])
  5234. >>> y = paddle.to_tensor([0.1])
  5235. >>> paddle.heaviside(x, y)
  5236. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  5237. [0. , 0.10000000, 1. ])
  5238. >>> x = paddle.to_tensor([[-0.5, 0, 0.5], [-0.5, 0.5, 0]])
  5239. >>> y = paddle.to_tensor([0.1, 0.2, 0.3])
  5240. >>> paddle.heaviside(x, y)
  5241. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  5242. [[0. , 0.20000000, 1. ],
  5243. [0. , 1. , 0.30000001]])
  5244. """
  5245. if in_dynamic_or_pir_mode():
  5246. return _C_ops.heaviside(x, y)
  5247. else:
  5248. op_type = 'elementwise_heaviside'
  5249. return _elementwise_op(LayerHelper(op_type, **locals()))
  5250. def frac(x, name=None):
  5251. """
  5252. This API is used to return the fractional portion of each element in input.
  5253. Args:
  5254. x (Tensor): The input tensor, which data type should be int32, int64, float32, float64.
  5255. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  5256. Returns:
  5257. Tensor: The output Tensor of frac.
  5258. Examples:
  5259. .. code-block:: python
  5260. >>> import paddle
  5261. >>> input = paddle.to_tensor([[12.22000003, -1.02999997],
  5262. ... [-0.54999995, 0.66000003]])
  5263. >>> output = paddle.frac(input)
  5264. >>> output
  5265. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  5266. [[ 0.22000003, -0.02999997],
  5267. [-0.54999995, 0.66000003]])
  5268. """
  5269. if x.dtype not in [
  5270. paddle.int32,
  5271. paddle.int64,
  5272. paddle.float32,
  5273. paddle.float64,
  5274. DataType.INT32,
  5275. DataType.INT64,
  5276. DataType.FLOAT32,
  5277. DataType.FLOAT64,
  5278. ]:
  5279. raise TypeError(
  5280. f"The data type of input must be one of ['int32', 'int64', 'float32', 'float64'], but got {x.dtype}"
  5281. )
  5282. if in_dynamic_or_pir_mode():
  5283. y = _C_ops.trunc(x)
  5284. return _C_ops.subtract(x, y)
  5285. else:
  5286. inputs = {"X": x}
  5287. attrs = {}
  5288. helper = LayerHelper("trunc", **locals())
  5289. check_variable_and_dtype(
  5290. x, "X", ['int32', 'int64', 'float32', 'float64'], 'trunc'
  5291. )
  5292. y = helper.create_variable_for_type_inference(dtype=x.dtype)
  5293. helper.append_op(
  5294. type="trunc", inputs=inputs, attrs=attrs, outputs={"Out": y}
  5295. )
  5296. return _elementwise_op(LayerHelper('elementwise_sub', **locals()))
  5297. @inplace_apis_in_dygraph_only
  5298. def frac_(x, name=None):
  5299. r"""
  5300. Inplace version of ``frac`` API, the output Tensor will be inplaced with input ``x``.
  5301. Please refer to :ref:`api_paddle_frac`.
  5302. """
  5303. if x.dtype not in [
  5304. paddle.int32,
  5305. paddle.int64,
  5306. paddle.float32,
  5307. paddle.float64,
  5308. ]:
  5309. raise TypeError(
  5310. f"The data type of input must be one of ['int32', 'int64', 'float32', 'float64'], but got {x.dtype}"
  5311. )
  5312. if in_dynamic_mode():
  5313. y = _C_ops.trunc(x)
  5314. return _C_ops.subtract_(x, y)
  5315. def sgn(x, name=None):
  5316. """
  5317. For complex tensor, this API returns a new tensor whose elements have the same angles as the corresponding
  5318. elements of input and absolute values of one.
  5319. For other float dtype tensor,
  5320. this API returns sign of every element in `x`: 1 for positive, -1 for negative and 0 for zero, same as paddle.sign.
  5321. Args:
  5322. x (Tensor): The input tensor, which data type should be float16, float32, float64, complex64, complex128.
  5323. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  5324. Returns:
  5325. Tensor: A sign Tensor for real input, or normalized Tensor for complex input, shape and data type are same as input.
  5326. Examples:
  5327. .. code-block:: python
  5328. >>> import paddle
  5329. >>> x = paddle.to_tensor([[3 + 4j, 7 - 24j, 0, 1 + 2j], [6 + 8j, 3, 0, -2]])
  5330. >>> paddle.sgn(x)
  5331. Tensor(shape=[2, 4], dtype=complex64, place=Place(cpu), stop_gradient=True,
  5332. [[ (0.6000000238418579+0.800000011920929j),
  5333. (0.2800000011920929-0.9599999785423279j),
  5334. 0j ,
  5335. (0.4472135901451111+0.8944271802902222j)],
  5336. [ (0.6000000238418579+0.800000011920929j),
  5337. (1+0j) ,
  5338. 0j ,
  5339. (-1+0j) ]])
  5340. """
  5341. if x.dtype not in [
  5342. paddle.float16,
  5343. paddle.float32,
  5344. paddle.float64,
  5345. paddle.complex64,
  5346. paddle.complex128,
  5347. DataType.FLOAT16,
  5348. DataType.FLOAT32,
  5349. DataType.FLOAT64,
  5350. DataType.COMPLEX64,
  5351. DataType.COMPLEX128,
  5352. ]:
  5353. raise TypeError(
  5354. f"The data type of input must be one of ['float16', 'float32', 'float64', 'complex64', 'complex128'], but got {x.dtype}"
  5355. )
  5356. if paddle.is_complex(x):
  5357. expand_x = paddle.as_real(x)
  5358. x_abs = paddle.abs(x)
  5359. x_abs = paddle.unsqueeze(x_abs, axis=-1)
  5360. output = expand_x / x_abs
  5361. zeros = paddle.zeros_like(output)
  5362. output = paddle.where(paddle.isnan(output), zeros, output)
  5363. return paddle.as_complex(output)
  5364. else:
  5365. return paddle.sign(x)
  5366. def take(x, index, mode='raise', name=None):
  5367. """
  5368. Returns a new tensor with the elements of input tensor x at the given index.
  5369. The input tensor is treated as if it were viewed as a 1-D tensor.
  5370. The result takes the same shape as the index.
  5371. Args:
  5372. x (Tensor): An N-D Tensor, its data type should be int32, int64, float32, float64.
  5373. index (Tensor): An N-D Tensor, its data type should be int32, int64.
  5374. mode (str, optional): Specifies how out-of-bounds index will behave. the candidates are ``'raise'``, ``'wrap'`` and ``'clip'``.
  5375. - ``'raise'``: raise an error (default);
  5376. - ``'wrap'``: wrap around;
  5377. - ``'clip'``: clip to the range. ``'clip'`` mode means that all indices that are too large are replaced by the index that addresses the last element. Note that this disables indexing with negative numbers.
  5378. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  5379. Returns:
  5380. Tensor, Tensor with the same shape as index, the data type is the same with input.
  5381. Examples:
  5382. .. code-block:: python
  5383. >>> import paddle
  5384. >>> x_int = paddle.arange(0, 12).reshape([3, 4])
  5385. >>> x_float = x_int.astype(paddle.float64)
  5386. >>> idx_pos = paddle.arange(4, 10).reshape([2, 3]) # positive index
  5387. >>> idx_neg = paddle.arange(-2, 4).reshape([2, 3]) # negative index
  5388. >>> idx_err = paddle.arange(-2, 13).reshape([3, 5]) # index out of range
  5389. >>> paddle.take(x_int, idx_pos)
  5390. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  5391. [[4, 5, 6],
  5392. [7, 8, 9]])
  5393. >>> paddle.take(x_int, idx_neg)
  5394. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  5395. [[10, 11, 0 ],
  5396. [1 , 2 , 3 ]])
  5397. >>> paddle.take(x_float, idx_pos)
  5398. Tensor(shape=[2, 3], dtype=float64, place=Place(cpu), stop_gradient=True,
  5399. [[4., 5., 6.],
  5400. [7., 8., 9.]])
  5401. >>> x_int.take(idx_pos)
  5402. Tensor(shape=[2, 3], dtype=int64, place=Place(cpu), stop_gradient=True,
  5403. [[4, 5, 6],
  5404. [7, 8, 9]])
  5405. >>> paddle.take(x_int, idx_err, mode='wrap')
  5406. Tensor(shape=[3, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
  5407. [[10, 11, 0 , 1 , 2 ],
  5408. [3 , 4 , 5 , 6 , 7 ],
  5409. [8 , 9 , 10, 11, 0 ]])
  5410. >>> paddle.take(x_int, idx_err, mode='clip')
  5411. Tensor(shape=[3, 5], dtype=int64, place=Place(cpu), stop_gradient=True,
  5412. [[0 , 0 , 0 , 1 , 2 ],
  5413. [3 , 4 , 5 , 6 , 7 ],
  5414. [8 , 9 , 10, 11, 11]])
  5415. """
  5416. if mode not in ['raise', 'wrap', 'clip']:
  5417. raise ValueError(
  5418. f"'mode' in 'take' should be 'raise', 'wrap', 'clip', but received {mode}."
  5419. )
  5420. if in_dynamic_or_pir_mode():
  5421. if not isinstance(index, (paddle.Tensor, Variable, paddle.pir.Value)):
  5422. raise TypeError(
  5423. f"The type of 'index' must be Tensor, but got {type(index)}"
  5424. )
  5425. if index.dtype not in [
  5426. paddle.int32,
  5427. paddle.int64,
  5428. DataType.INT32,
  5429. DataType.INT64,
  5430. ]:
  5431. raise TypeError(
  5432. f"The data type of 'index' must be one of ['int32', 'int64'], but got {index.dtype}"
  5433. )
  5434. else:
  5435. check_variable_and_dtype(index, 'index', ['int32', 'int64'], 'take')
  5436. input_1d = x.flatten()
  5437. index_1d = index.flatten()
  5438. max_index = input_1d.shape[-1]
  5439. if mode == 'raise':
  5440. # This processing enables 'take' to handle negative indexes within the correct range.
  5441. index_1d = paddle.where(index_1d < 0, index_1d + max_index, index_1d)
  5442. elif mode == 'wrap':
  5443. # The out of range indices are constrained by taking the remainder.
  5444. index_1d = paddle.where(index_1d < 0, index_1d % max_index, index_1d)
  5445. index_1d = paddle.where(
  5446. index_1d >= max_index, index_1d % max_index, index_1d
  5447. )
  5448. elif mode == 'clip':
  5449. # 'clip' mode disables indexing with negative numbers.
  5450. index_1d = clip(index_1d, 0, max_index - 1)
  5451. out = input_1d.index_select(index_1d).reshape(index.shape)
  5452. return out
  5453. def frexp(x, name=None):
  5454. """
  5455. The function used to decompose a floating point number into mantissa and exponent.
  5456. Args:
  5457. x (Tensor): The input tensor, it's data type should be float32, float64.
  5458. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  5459. Returns:
  5460. - mantissa (Tensor), A mantissa Tensor. The shape and data type of mantissa tensor and exponential tensor are
  5461. the same as those of input.
  5462. - exponent (Tensor), A exponent Tensor. The shape and data type of mantissa tensor and exponential tensor are
  5463. the same as those of input.
  5464. Examples:
  5465. .. code-block:: python
  5466. >>> import paddle
  5467. >>> x = paddle.to_tensor([[1, 2, 3, 4]], dtype="float32")
  5468. >>> mantissa, exponent = paddle.tensor.math.frexp(x)
  5469. >>> mantissa
  5470. Tensor(shape=[1, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  5471. [[0.50000000, 0.50000000, 0.75000000, 0.50000000]])
  5472. >>> exponent
  5473. Tensor(shape=[1, 4], dtype=float32, place=Place(cpu), stop_gradient=True,
  5474. [[1., 2., 2., 3.]])
  5475. """
  5476. if x.dtype not in [
  5477. paddle.float32,
  5478. paddle.float64,
  5479. DataType.FLOAT32,
  5480. DataType.FLOAT64,
  5481. ]:
  5482. raise TypeError(
  5483. f"The data type of input must be one of ['float32', 'float64'], but got {x.dtype}"
  5484. )
  5485. input_x = paddle.abs(x)
  5486. exponent = paddle.floor(paddle.log2(input_x))
  5487. exponent = paddle.where(
  5488. paddle.isinf(exponent), paddle.full_like(exponent, 0), exponent
  5489. )
  5490. # 0填充
  5491. mantissa = paddle.divide(input_x, 2**exponent)
  5492. # 计算exponent
  5493. exponent = paddle.where(
  5494. (mantissa >= 1),
  5495. paddle.add(exponent, paddle.ones_like(exponent)),
  5496. exponent,
  5497. )
  5498. mantissa = paddle.where(
  5499. (mantissa >= 1),
  5500. paddle.divide(mantissa, 2 ** paddle.ones_like(exponent)),
  5501. mantissa,
  5502. )
  5503. mantissa = paddle.where((x < 0), mantissa * -1, mantissa)
  5504. return mantissa, exponent
  5505. def _trapezoid(y, x=None, dx=None, axis=-1, mode='sum'):
  5506. """
  5507. Integrate along the given axis using the composite trapezoidal rule.
  5508. Args:
  5509. y (Tensor): Input tensor to integrate. It's data type should be float16, float32, float64.
  5510. x (Tensor, optional): The sample points corresponding to the :attr:`y` values, the same type as :attr:`y`.
  5511. It is known that the size of :attr:`y` is `[d_1, d_2, ... , d_n]` and :math:`axis=k`, then the size of :attr:`x` can only be `[d_k]` or `[d_1, d_2, ... , d_n ]`.
  5512. If :attr:`x` is None, the sample points are assumed to be evenly spaced :attr:`dx` apart. The default is None.
  5513. dx (float, optional): The spacing between sample points when :attr:`x` is None. If neither :attr:`x` nor :attr:`dx` is provided then the default is :math:`dx = 1`.
  5514. axis (int, optional): The axis along which to integrate. The default is -1.
  5515. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  5516. sum_mode (str): use a different summation. The default is `sum`.
  5517. Returns:
  5518. Tensor, Definite integral of :attr:`y` is N-D tensor as approximated along a single axis by the trapezoidal rule.
  5519. """
  5520. if mode == 'sum':
  5521. sum_mode = paddle.sum
  5522. elif mode == 'cumsum':
  5523. sum_mode = paddle.cumsum
  5524. if not (x is None or dx is None):
  5525. raise ValueError("Not permitted to specify both x and dx input args.")
  5526. if y.dtype not in [
  5527. paddle.float16,
  5528. paddle.float32,
  5529. paddle.float64,
  5530. paddle.base.core.DataType.FLOAT16,
  5531. paddle.base.core.DataType.FLOAT32,
  5532. paddle.base.core.DataType.FLOAT64,
  5533. ]:
  5534. raise TypeError(
  5535. f"The data type of input must be Tensor, and dtype should be one of ['paddle.float16', 'paddle.float32', 'paddle.float64', 'paddle.base.core.DataType.FLOAT16', 'paddle.base.core.DataType.FLOAT32', 'paddle.base.core.DataType.FLOAT64'], but got {y.dtype}"
  5536. )
  5537. y_shape = y.shape
  5538. length = y_shape[axis]
  5539. if axis < 0:
  5540. axis += y.dim()
  5541. if x is None:
  5542. if dx is None:
  5543. dx = 1.0
  5544. dx = paddle.to_tensor(dx)
  5545. if dx.dim() > 1:
  5546. raise ValueError(f'Expected dx to be a scalar, got dx={dx}')
  5547. else:
  5548. if x.dtype not in [
  5549. paddle.float16,
  5550. paddle.float32,
  5551. paddle.float64,
  5552. paddle.base.core.DataType.FLOAT16,
  5553. paddle.base.core.DataType.FLOAT32,
  5554. paddle.base.core.DataType.FLOAT64,
  5555. ]:
  5556. raise TypeError(
  5557. f"The data type of input must be Tensor, and dtype should be one of ['paddle.float16', 'paddle.float32', 'paddle.float64', 'paddle.base.core.DataType.FLOAT16', 'paddle.base.core.DataType.FLOAT32', 'paddle.base.core.DataType.FLOAT64'], but got {x.dtype}"
  5558. )
  5559. # Reshape to correct shape
  5560. if x.dim() == 1:
  5561. dx = paddle.diff(x)
  5562. shape = [1] * y.dim()
  5563. shape[axis] = dx.shape[0]
  5564. dx = dx.reshape(shape)
  5565. else:
  5566. dx = paddle.diff(x, axis=axis)
  5567. return 0.5 * sum_mode(
  5568. (
  5569. paddle.gather(y, paddle.arange(1, length), axis=axis)
  5570. + paddle.gather(y, paddle.arange(0, length - 1), axis=axis)
  5571. )
  5572. * dx,
  5573. axis=axis,
  5574. )
  5575. def trapezoid(y, x=None, dx=None, axis=-1, name=None):
  5576. """
  5577. Integrate along the given axis using the composite trapezoidal rule. Use the sum method.
  5578. Args:
  5579. y (Tensor): Input tensor to integrate. It's data type should be float16, float32, float64.
  5580. x (Tensor, optional): The sample points corresponding to the :attr:`y` values, the same type as :attr:`y`.
  5581. It is known that the size of :attr:`y` is `[d_1, d_2, ... , d_n]` and :math:`axis=k`, then the size of :attr:`x` can only be `[d_k]` or `[d_1, d_2, ... , d_n ]`.
  5582. If :attr:`x` is None, the sample points are assumed to be evenly spaced :attr:`dx` apart. The default is None.
  5583. dx (float, optional): The spacing between sample points when :attr:`x` is None. If neither :attr:`x` nor :attr:`dx` is provided then the default is :math:`dx = 1`.
  5584. axis (int, optional): The axis along which to integrate. The default is -1.
  5585. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  5586. Returns:
  5587. Tensor, Definite integral of :attr:`y` is N-D tensor as approximated along a single axis by the trapezoidal rule.
  5588. If :attr:`y` is a 1D tensor, then the result is a float. If N is greater than 1, then the result is an (N-1)-D tensor.
  5589. Examples:
  5590. .. code-block:: python
  5591. >>> import paddle
  5592. >>> y = paddle.to_tensor([4, 5, 6], dtype='float32')
  5593. >>> paddle.trapezoid(y)
  5594. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  5595. 10.)
  5596. >>> paddle.trapezoid(y, dx=2.)
  5597. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  5598. 20.)
  5599. >>> y = paddle.to_tensor([4, 5, 6], dtype='float32')
  5600. >>> x = paddle.to_tensor([1, 2, 3], dtype='float32')
  5601. >>> paddle.trapezoid(y, x)
  5602. Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True,
  5603. 10.)
  5604. >>> y = paddle.to_tensor([1, 2, 3], dtype='float64')
  5605. >>> x = paddle.to_tensor([8, 6, 4], dtype='float64')
  5606. >>> paddle.trapezoid(y, x)
  5607. Tensor(shape=[], dtype=float64, place=Place(cpu), stop_gradient=True,
  5608. -8.)
  5609. >>> y = paddle.arange(6).reshape((2, 3)).astype('float32')
  5610. >>> paddle.trapezoid(y, axis=0)
  5611. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  5612. [1.50000000, 2.50000000, 3.50000000])
  5613. >>> paddle.trapezoid(y, axis=1)
  5614. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  5615. [2., 8.])
  5616. """
  5617. return _trapezoid(y, x, dx, axis, mode='sum')
  5618. def cumulative_trapezoid(y, x=None, dx=None, axis=-1, name=None):
  5619. """
  5620. Integrate along the given axis using the composite trapezoidal rule. Use the cumsum method
  5621. Args:
  5622. y (Tensor): Input tensor to integrate. It's data type should be float16, float32, float64.
  5623. x (Tensor, optional): The sample points corresponding to the :attr:`y` values, the same type as :attr:`y`.
  5624. It is known that the size of :attr:`y` is `[d_1, d_2, ... , d_n]` and :math:`axis=k`, then the size of :attr:`x` can only be `[d_k]` or `[d_1, d_2, ... , d_n ]`.
  5625. If :attr:`x` is None, the sample points are assumed to be evenly spaced :attr:`dx` apart. The default is None.
  5626. dx (float, optional): The spacing between sample points when :attr:`x` is None. If neither :attr:`x` nor :attr:`dx` is provided then the default is :math:`dx = 1`.
  5627. axis (int, optional): The axis along which to integrate. The default is -1.
  5628. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  5629. Returns:
  5630. Tensor, Definite integral of :attr:`y` is N-D tensor as approximated along a single axis by the trapezoidal rule.
  5631. The result is an N-D tensor.
  5632. Examples:
  5633. .. code-block:: python
  5634. >>> import paddle
  5635. >>> y = paddle.to_tensor([4, 5, 6], dtype='float32')
  5636. >>> paddle.cumulative_trapezoid(y)
  5637. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  5638. [4.50000000, 10. ])
  5639. >>> paddle.cumulative_trapezoid(y, dx=2.)
  5640. >>> # Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  5641. >>> # [9. , 20.])
  5642. >>> y = paddle.to_tensor([4, 5, 6], dtype='float32')
  5643. >>> x = paddle.to_tensor([1, 2, 3], dtype='float32')
  5644. >>> paddle.cumulative_trapezoid(y, x)
  5645. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  5646. [4.50000000, 10. ])
  5647. >>> y = paddle.to_tensor([1, 2, 3], dtype='float64')
  5648. >>> x = paddle.to_tensor([8, 6, 4], dtype='float64')
  5649. >>> paddle.cumulative_trapezoid(y, x)
  5650. Tensor(shape=[2], dtype=float64, place=Place(cpu), stop_gradient=True,
  5651. [-3., -8.])
  5652. >>> y = paddle.arange(6).reshape((2, 3)).astype('float32')
  5653. >>> paddle.cumulative_trapezoid(y, axis=0)
  5654. Tensor(shape=[1, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  5655. [[1.50000000, 2.50000000, 3.50000000]])
  5656. >>> paddle.cumulative_trapezoid(y, axis=1)
  5657. Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  5658. [[0.50000000, 2. ],
  5659. [3.50000000, 8. ]])
  5660. """
  5661. return _trapezoid(y, x, dx, axis, mode='cumsum')
  5662. def vander(x, n=None, increasing=False, name=None):
  5663. """
  5664. Generate a Vandermonde matrix.
  5665. The columns of the output matrix are powers of the input vector. Order of the powers is
  5666. determined by the increasing Boolean parameter. Specifically, when the increment is
  5667. "false", the ith output column is a step-up in the order of the elements of the input
  5668. vector to the N - i - 1 power. Such a matrix with a geometric progression in each row
  5669. is named after Alexandre-Theophile Vandermonde.
  5670. Args:
  5671. x (Tensor): The input tensor, it must be 1-D Tensor, and it's data type should be ['complex64', 'complex128', 'float32', 'float64', 'int32', 'int64'].
  5672. n (int): Number of columns in the output. If n is not specified, a square array is returned (n = len(x)).
  5673. increasing(bool): Order of the powers of the columns. If True, the powers increase from left to right, if False (the default) they are reversed.
  5674. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  5675. Returns:
  5676. Tensor, A vandermonde matrix with shape (len(x), N). If increasing is False, the first column is :math:`x^{(N-1)}`, the second :math:`x^{(N-2)}` and so forth.
  5677. If increasing is True, the columns are :math:`x^0`, :math:`x^1`, ..., :math:`x^{(N-1)}`.
  5678. Examples:
  5679. .. code-block:: python
  5680. >>> import paddle
  5681. >>> x = paddle.to_tensor([1., 2., 3.], dtype="float32")
  5682. >>> out = paddle.vander(x)
  5683. >>> out
  5684. Tensor(shape=[3, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  5685. [[1., 1., 1.],
  5686. [4., 2., 1.],
  5687. [9., 3., 1.]])
  5688. >>> out1 = paddle.vander(x,2)
  5689. >>> out1
  5690. Tensor(shape=[3, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
  5691. [[1., 1.],
  5692. [2., 1.],
  5693. [3., 1.]])
  5694. >>> out2 = paddle.vander(x, increasing = True)
  5695. >>> out2
  5696. Tensor(shape=[3, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  5697. [[1., 1., 1.],
  5698. [1., 2., 4.],
  5699. [1., 3., 9.]])
  5700. >>> real = paddle.to_tensor([2., 4.])
  5701. >>> imag = paddle.to_tensor([1., 3.])
  5702. >>> complex = paddle.complex(real, imag)
  5703. >>> out3 = paddle.vander(complex)
  5704. >>> out3
  5705. Tensor(shape=[2, 2], dtype=complex64, place=Place(cpu), stop_gradient=True,
  5706. [[(2+1j), (1+0j)],
  5707. [(4+3j), (1+0j)]])
  5708. """
  5709. check_variable_and_dtype(
  5710. x,
  5711. 'x',
  5712. ['complex64', 'complex128', 'float32', 'float64', 'int32', 'int64'],
  5713. 'vander',
  5714. )
  5715. if x.dim() != 1:
  5716. raise ValueError(
  5717. "The input of x is expected to be a 1-D Tensor."
  5718. "But now the dims of Input(X) is %d." % x.dim()
  5719. )
  5720. if n is None:
  5721. n = x.shape[0]
  5722. if n < 0:
  5723. raise ValueError("N must be non-negative.")
  5724. res = paddle.empty([x.shape[0], n], dtype=x.dtype)
  5725. if paddle.in_dynamic_mode():
  5726. if n > 0:
  5727. res[:, 0] = paddle.to_tensor([1], dtype=x.dtype)
  5728. if n > 1:
  5729. res[:, 1:] = x[:, None]
  5730. res[:, 1:] = paddle.cumprod(res[:, 1:], dim=-1)
  5731. else:
  5732. if n > 0:
  5733. res = paddle.static.setitem(
  5734. res, (slice(None), 0), paddle.to_tensor([1], dtype=x.dtype)
  5735. )
  5736. if n > 1:
  5737. res = paddle.static.setitem(
  5738. res, (slice(None), slice(1, None)), x[:, None]
  5739. )
  5740. res = paddle.static.setitem(
  5741. res,
  5742. (slice(None), slice(1, None)),
  5743. paddle.cumprod(res[:, 1:], dim=-1),
  5744. )
  5745. res = res[:, ::-1] if not increasing else res
  5746. return res
  5747. def nextafter(x, y, name=None):
  5748. r"""
  5749. Return the next floating-point value after input towards other, elementwise.
  5750. The shapes of input and other must be broadcastable.
  5751. Args:
  5752. x (Tensor): An N-D Tensor, the data type is float32, float64.
  5753. y (Tensor): An N-D Tensor, the data type is float32, float64.
  5754. name(str, optional):Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  5755. Returns:
  5756. out (Tensor): An N-D Tensor, the shape and data type is the same with input.
  5757. Examples:
  5758. .. code-block:: python
  5759. >>> import paddle
  5760. >>> out = paddle.nextafter(paddle.to_tensor([1.0,2.0]),paddle.to_tensor([2.0,1.0]))
  5761. >>> out
  5762. Tensor(shape=[2], dtype=float32, place=Place(cpu), stop_gradient=True,
  5763. [1.00000012, 1.99999988])
  5764. """
  5765. if in_dynamic_or_pir_mode():
  5766. return _C_ops.nextafter(x, y)
  5767. else:
  5768. check_variable_and_dtype(x, 'x', ['float32', 'float64'], 'nextafter')
  5769. check_variable_and_dtype(y, 'y', ['float32', 'float64'], 'nextafter')
  5770. op_type = "nextafter"
  5771. helper = LayerHelper(op_type, **locals())
  5772. inputs = {"x": x, "y": y}
  5773. out = helper.create_variable_for_type_inference(dtype=paddle.float32)
  5774. outputs = {"out": out}
  5775. helper.append_op(type=op_type, inputs=inputs, outputs=outputs)
  5776. return out
  5777. def i0(x, name=None):
  5778. r"""
  5779. The function used to calculate modified bessel function of order 0.
  5780. Equation:
  5781. .. math::
  5782. I_0(x) = \sum^{\infty}_{k=0}\frac{(x^2/4)^k}{(k!)^2}
  5783. Args:
  5784. x (Tensor): The input tensor, it's data type should be float32, float64.
  5785. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  5786. Returns:
  5787. - out (Tensor), A Tensor. the value of the modified bessel function of order 0 at x.
  5788. Examples:
  5789. .. code-block:: python
  5790. >>> import paddle
  5791. >>> x = paddle.to_tensor([0, 1, 2, 3, 4], dtype="float32")
  5792. >>> paddle.i0(x)
  5793. Tensor(shape=[5], dtype=float32, place=Place(cpu), stop_gradient=True,
  5794. [0.99999994 , 1.26606596 , 2.27958512 , 4.88079262 , 11.30192089])
  5795. """
  5796. if in_dynamic_or_pir_mode():
  5797. return _C_ops.i0(x)
  5798. else:
  5799. check_variable_and_dtype(x, "x", ["float32", "float64"], "i0")
  5800. helper = LayerHelper("i0", **locals())
  5801. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  5802. helper.append_op(type='i0', inputs={'x': x}, outputs={'out': out})
  5803. return out
  5804. @inplace_apis_in_dygraph_only
  5805. def i0_(x, name=None):
  5806. r"""
  5807. Inplace version of ``i0`` API, the output Tensor will be inplaced with input ``x``.
  5808. Please refer to :ref:`api_paddle_i0`.
  5809. """
  5810. if in_dynamic_mode():
  5811. return _C_ops.i0_(x)
  5812. def i0e(x, name=None):
  5813. r"""
  5814. The function used to calculate exponentially scaled modified Bessel function of order 0.
  5815. Equation:
  5816. .. math::
  5817. I_0(x) = \sum^{\infty}_{k=0}\frac{(x^2/4)^k}{(k!)^2} \\
  5818. I_{0e}(x) = e^{-|x|}I_0(x)
  5819. Args:
  5820. x (Tensor): The input tensor, it's data type should be float32, float64.
  5821. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  5822. Returns:
  5823. - out (Tensor), A Tensor. the value of the exponentially scaled modified Bessel function of order 0 at x.
  5824. Examples:
  5825. .. code-block:: python
  5826. >>> import paddle
  5827. >>> x = paddle.to_tensor([0, 1, 2, 3, 4], dtype="float32")
  5828. >>> print(paddle.i0e(x))
  5829. Tensor(shape=[5], dtype=float32, place=Place(cpu), stop_gradient=True,
  5830. [0.99999994, 0.46575963, 0.30850831, 0.24300036, 0.20700191])
  5831. """
  5832. if in_dynamic_or_pir_mode():
  5833. return _C_ops.i0e(x)
  5834. else:
  5835. check_variable_and_dtype(x, "x", ["float32", "float64"], "i0e")
  5836. helper = LayerHelper("i0e", **locals())
  5837. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  5838. helper.append_op(type='i0e', inputs={'x': x}, outputs={'out': out})
  5839. return out
  5840. def i1(x, name=None):
  5841. """
  5842. The function is used to calculate modified bessel function of order 1.
  5843. Args:
  5844. x (Tensor): The input tensor, it's data type should be float32, float64.
  5845. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  5846. Returns:
  5847. - out (Tensor), A Tensor. the value of the modified bessel function of order 1 at x.
  5848. Examples:
  5849. .. code-block:: python
  5850. >>> import paddle
  5851. >>> x = paddle.to_tensor([0, 1, 2, 3, 4], dtype="float32")
  5852. >>> print(paddle.i1(x))
  5853. Tensor(shape=[5], dtype=float32, place=Place(cpu), stop_gradient=True,
  5854. [0. , 0.56515908, 1.59063685, 3.95337057, 9.75946712])
  5855. """
  5856. if in_dynamic_or_pir_mode():
  5857. return _C_ops.i1(x)
  5858. else:
  5859. check_variable_and_dtype(x, "x", ["float32", "float64"], "i1")
  5860. helper = LayerHelper("i1", **locals())
  5861. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  5862. helper.append_op(
  5863. type='i1', inputs={'x': x}, outputs={'out': out}, attrs={}
  5864. )
  5865. return out
  5866. def i1e(x, name=None):
  5867. """
  5868. The function is used to calculate exponentially scaled modified Bessel function of order 1.
  5869. Args:
  5870. x (Tensor): The input tensor, it's data type should be float32, float64.
  5871. name (str, optional): For details, please refer to :ref:`api_guide_Name`. Generally, no setting is required. Default: None.
  5872. Returns:
  5873. - out (Tensor), A Tensor. the value of the exponentially scaled modified Bessel function of order 1 at x.
  5874. Examples:
  5875. .. code-block:: python
  5876. >>> import paddle
  5877. >>> x = paddle.to_tensor([0, 1, 2, 3, 4], dtype="float32")
  5878. >>> print(paddle.i1e(x))
  5879. Tensor(shape=[5], dtype=float32, place=Place(cpu), stop_gradient=True,
  5880. [0. , 0.20791042, 0.21526928, 0.19682673, 0.17875087])
  5881. """
  5882. if in_dynamic_or_pir_mode():
  5883. return _C_ops.i1e(x)
  5884. else:
  5885. check_variable_and_dtype(x, "x", ["float32", "float64"], "i1e")
  5886. helper = LayerHelper("i1e", **locals())
  5887. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  5888. helper.append_op(
  5889. type='i1e', inputs={'x': x}, outputs={'out': out}, attrs={}
  5890. )
  5891. return out
  5892. def polygamma(x, n, name=None):
  5893. r"""
  5894. Calculates the polygamma of the given input tensor, element-wise.
  5895. The equation is:
  5896. .. math::
  5897. \Phi^n(x) = \frac{d^n}{dx^n} [\ln(\Gamma(x))]
  5898. Args:
  5899. x (Tensor): Input Tensor. Must be one of the following types: float32, float64.
  5900. n (int): Order of the derivative. Must be integral.
  5901. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  5902. Returns:
  5903. - out (Tensor), A Tensor. the polygamma of the input Tensor, the shape and data type is the same with input.
  5904. Examples:
  5905. .. code-block:: python
  5906. >>> import paddle
  5907. >>> data = paddle.to_tensor([2, 3, 25.5], dtype='float32')
  5908. >>> res = paddle.polygamma(data, 1)
  5909. >>> print(res)
  5910. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  5911. [0.64493412, 0.39493406, 0.03999467])
  5912. """
  5913. if not isinstance(n, int):
  5914. raise TypeError(
  5915. "The input of n must be int type, but received: %s " % (type(n))
  5916. )
  5917. if n < 0:
  5918. raise ValueError(
  5919. "The input of n must be greater than or equal to 0. But received n = %s"
  5920. % (n)
  5921. )
  5922. if n == 0:
  5923. return digamma(x)
  5924. else:
  5925. if in_dynamic_or_pir_mode():
  5926. return _C_ops.polygamma(x, n)
  5927. else:
  5928. check_variable_and_dtype(
  5929. x, "x", ["float32", "float64"], "polygamma"
  5930. )
  5931. helper = LayerHelper("polygamma", **locals())
  5932. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  5933. helper.append_op(
  5934. type='polygamma',
  5935. inputs={'x': x},
  5936. outputs={'out': out},
  5937. attrs={'n': n},
  5938. )
  5939. return out
  5940. @inplace_apis_in_dygraph_only
  5941. def polygamma_(x, n, name=None):
  5942. r"""
  5943. Inplace version of ``polygamma`` API, the output Tensor will be inplaced with input ``x``.
  5944. Please refer to :ref:`api_paddle_polygamma`.
  5945. """
  5946. if not isinstance(n, int):
  5947. raise TypeError(
  5948. "The input of n must be int type, but received: %s " % (type(n))
  5949. )
  5950. if n < 0:
  5951. raise ValueError(
  5952. "The input of n must be greater than or equal to 0. But received n = %s"
  5953. % (n)
  5954. )
  5955. if n == 0:
  5956. return digamma_(x)
  5957. else:
  5958. if in_dynamic_mode():
  5959. return _C_ops.polygamma_(x, n)
  5960. def ldexp(x, y, name=None):
  5961. """
  5962. Compute the result of multiplying x by 2 to the power of y. The equation is:
  5963. .. math::
  5964. out = x * 2^{y}
  5965. Args:
  5966. x (Tensor): The input Tensor, the data type is float32, float64, int32 or int64.
  5967. y (Tensor): A Tensor of exponents, typically integers.
  5968. name (str, optional): Name for the operation (optional, default is None).For more information, please refer to :ref:`api_guide_Name`.
  5969. Returns:
  5970. out (Tensor): An N-D Tensor. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. And the data type is float32 or float64.
  5971. Examples:
  5972. .. code-block:: python
  5973. >>> import paddle
  5974. >>> # example1
  5975. >>> x = paddle.to_tensor([1, 2, 3], dtype='float32')
  5976. >>> y = paddle.to_tensor([2, 3, 4], dtype='int32')
  5977. >>> res = paddle.ldexp(x, y)
  5978. >>> print(res)
  5979. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  5980. [4. , 16., 48.])
  5981. >>> # example2
  5982. >>> x = paddle.to_tensor([1, 2, 3], dtype='float32')
  5983. >>> y = paddle.to_tensor([2], dtype='int32')
  5984. >>> res = paddle.ldexp(x, y)
  5985. >>> print(res)
  5986. Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
  5987. [4. , 8. , 12.])
  5988. """
  5989. if not isinstance(x, (paddle.Tensor, Variable, paddle.pir.Value)):
  5990. raise TypeError(f"x must be tensor type, but got {type(x)}")
  5991. if not isinstance(y, (paddle.Tensor, Variable, paddle.pir.Value)):
  5992. raise TypeError(f"y must be tensor type, but got {type(y)}")
  5993. if x.dtype == paddle.float64 or y.dtype == paddle.float64:
  5994. out_dtype = paddle.float64
  5995. elif x.dtype == DataType.FLOAT64 or y.dtype == DataType.FLOAT64:
  5996. out_dtype = DataType.FLOAT64
  5997. else:
  5998. out_dtype = paddle.get_default_dtype()
  5999. x = paddle.cast(x, dtype=out_dtype)
  6000. y = paddle.cast(y, dtype=out_dtype)
  6001. two = paddle.to_tensor(2, dtype=out_dtype)
  6002. return paddle.multiply(x, paddle.pow(two, y))
  6003. def ldexp_(x, y, name=None):
  6004. r"""
  6005. Inplace version of ``polygamma`` API, the output Tensor will be inplaced with input ``x``.
  6006. Please refer to :ref:`api_paddle_polygamma`.
  6007. """
  6008. if not isinstance(x, (paddle.Tensor, Variable)):
  6009. raise TypeError(f"x must be tensor type, but got {type(x)}")
  6010. if not isinstance(y, (paddle.Tensor, Variable)):
  6011. raise TypeError(f"y must be tensor type, but got {type(y)}")
  6012. if x.dtype == paddle.float64 or y.dtype == paddle.float64:
  6013. out_dtype = paddle.float64
  6014. else:
  6015. out_dtype = paddle.get_default_dtype()
  6016. x = paddle.cast_(x, dtype=out_dtype)
  6017. y = paddle.cast(y, dtype=out_dtype)
  6018. two = paddle.to_tensor(2, dtype=out_dtype)
  6019. return paddle.multiply_(x, paddle.pow(two, y))
  6020. def _bitwise_op(op_name, x, y, is_arithmetic, out=None, name=None):
  6021. check_variable_and_dtype(
  6022. x,
  6023. "x",
  6024. ["uint8", "int8", "int16", "int32", "int64"],
  6025. op_name,
  6026. )
  6027. if y is not None:
  6028. check_variable_and_dtype(
  6029. y,
  6030. "y",
  6031. ["uint8", "int8", "int16", "int32", "int64"],
  6032. op_name,
  6033. )
  6034. helper = LayerHelper(op_name, **locals())
  6035. assert x.dtype == y.dtype
  6036. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  6037. helper.append_op(
  6038. type=op_name,
  6039. inputs={"x": x, "y": y},
  6040. outputs={"out": out},
  6041. attrs={'is_arithmetic': is_arithmetic},
  6042. )
  6043. return out
  6044. def bitwise_left_shift(x, y, is_arithmetic=True, out=None, name=None):
  6045. r"""
  6046. Apply ``bitwise_left_shift`` on Tensor ``X`` and ``Y`` .
  6047. .. math::
  6048. Out = X \ll Y
  6049. .. note::
  6050. ``paddle.bitwise_left_shift`` supports broadcasting. If you want know more about broadcasting, please refer to please refer to `Introduction to Tensor`_ .
  6051. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  6052. Args:
  6053. x (Tensor): Input Tensor of ``bitwise_left_shift`` . It is a N-D Tensor of uint8, int8, int16, int32, int64.
  6054. y (Tensor): Input Tensor of ``bitwise_left_shift`` . It is a N-D Tensor of uint8, int8, int16, int32, int64.
  6055. is_arithmetic (bool, optional): A boolean indicating whether to choose arithmetic shift, if False, means logic shift. Default True.
  6056. out (Tensor, optional): Result of ``bitwise_left_shift`` . It is a N-D Tensor with the same data type of input Tensor. Default: None.
  6057. name (str, optional): The default value is None. Normally there is no need for
  6058. user to set this property. For more information, please refer to :ref:`api_guide_Name`.
  6059. Returns:
  6060. Tensor: Result of ``bitwise_left_shift`` . It is a N-D Tensor with the same data type of input Tensor.
  6061. Examples:
  6062. .. code-block:: python
  6063. :name: bitwise_left_shift_example1
  6064. >>> import paddle
  6065. >>> x = paddle.to_tensor([[1,2,4,8],[16,17,32,65]])
  6066. >>> y = paddle.to_tensor([[1,2,3,4,], [2,3,2,1]])
  6067. >>> paddle.bitwise_left_shift(x, y, is_arithmetic=True)
  6068. Tensor(shape=[2, 4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
  6069. [[2 , 8 , 32 , 128],
  6070. [64 , 136, 128, 130]])
  6071. .. code-block:: python
  6072. :name: bitwise_left_shift_example2
  6073. >>> import paddle
  6074. >>> x = paddle.to_tensor([[1,2,4,8],[16,17,32,65]])
  6075. >>> y = paddle.to_tensor([[1,2,3,4,], [2,3,2,1]])
  6076. >>> paddle.bitwise_left_shift(x, y, is_arithmetic=False)
  6077. Tensor(shape=[2, 4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
  6078. [[2 , 8 , 32 , 128],
  6079. [64 , 136, 128, 130]])
  6080. """
  6081. if in_dynamic_mode() and out is None:
  6082. return _C_ops.bitwise_left_shift(x, y, is_arithmetic)
  6083. return _bitwise_op(
  6084. op_name="bitwise_left_shift",
  6085. x=x,
  6086. y=y,
  6087. is_arithmetic=is_arithmetic,
  6088. name=name,
  6089. out=out,
  6090. )
  6091. @inplace_apis_in_dygraph_only
  6092. def bitwise_left_shift_(x, y, is_arithmetic=True, out=None, name=None):
  6093. r"""
  6094. Inplace version of ``bitwise_left_shift`` API, the output Tensor will be inplaced with input ``x``.
  6095. Please refer to :ref:`api_paddle_bitwise_left_shift`.
  6096. """
  6097. out_shape = broadcast_shape(x.shape, y.shape)
  6098. if out_shape != x.shape:
  6099. raise ValueError(
  6100. f"The shape of broadcast output {out_shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  6101. )
  6102. if in_dynamic_or_pir_mode():
  6103. return _C_ops.bitwise_left_shift_(x, y, is_arithmetic)
  6104. def bitwise_right_shift(x, y, is_arithmetic=True, out=None, name=None):
  6105. r"""
  6106. Apply ``bitwise_right_shift`` on Tensor ``X`` and ``Y`` .
  6107. .. math::
  6108. Out = X \gg Y
  6109. .. note::
  6110. ``paddle.bitwise_right_shift`` supports broadcasting. If you want know more about broadcasting, please refer to please refer to `Introduction to Tensor`_ .
  6111. .. _Introduction to Tensor: ../../guides/beginner/tensor_en.html#chapter5-broadcasting-of-tensor
  6112. Args:
  6113. x (Tensor): Input Tensor of ``bitwise_right_shift`` . It is a N-D Tensor of uint8, int8, int16, int32, int64.
  6114. y (Tensor): Input Tensor of ``bitwise_right_shift`` . It is a N-D Tensor of uint8, int8, int16, int32, int64.
  6115. is_arithmetic (bool, optional): A boolean indicating whether to choose arithmetic shift, if False, means logic shift. Default True.
  6116. out (Tensor, optional): Result of ``bitwise_right_shift`` . It is a N-D Tensor with the same data type of input Tensor. Default: None.
  6117. name (str, optional): The default value is None. Normally there is no need for
  6118. user to set this property. For more information, please refer to :ref:`api_guide_Name`.
  6119. Returns:
  6120. Tensor: Result of ``bitwise_right_shift`` . It is a N-D Tensor with the same data type of input Tensor.
  6121. Examples:
  6122. .. code-block:: python
  6123. :name: bitwise_right_shift_example1
  6124. >>> import paddle
  6125. >>> x = paddle.to_tensor([[10,20,40,80],[16,17,32,65]])
  6126. >>> y = paddle.to_tensor([[1,2,3,4,], [2,3,2,1]])
  6127. >>> paddle.bitwise_right_shift(x, y, is_arithmetic=True)
  6128. Tensor(shape=[2, 4], dtype=int64, place=Place(gpu:0), stop_gradient=True,
  6129. [[5 , 5 , 5 , 5 ],
  6130. [4 , 2 , 8 , 32]])
  6131. .. code-block:: python
  6132. :name: bitwise_right_shift_example2
  6133. >>> import paddle
  6134. >>> x = paddle.to_tensor([[-10,-20,-40,-80],[-16,-17,-32,-65]], dtype=paddle.int8)
  6135. >>> y = paddle.to_tensor([[1,2,3,4,], [2,3,2,1]], dtype=paddle.int8)
  6136. >>> paddle.bitwise_right_shift(x, y, is_arithmetic=False) # logic shift
  6137. Tensor(shape=[2, 4], dtype=int8, place=Place(gpu:0), stop_gradient=True,
  6138. [[123, 59 , 27 , 11 ],
  6139. [60 , 29 , 56 , 95 ]])
  6140. """
  6141. if in_dynamic_mode() and out is None:
  6142. return _C_ops.bitwise_right_shift(x, y, is_arithmetic)
  6143. return _bitwise_op(
  6144. op_name="bitwise_right_shift",
  6145. x=x,
  6146. y=y,
  6147. is_arithmetic=is_arithmetic,
  6148. name=name,
  6149. out=out,
  6150. )
  6151. @inplace_apis_in_dygraph_only
  6152. def bitwise_right_shift_(x, y, is_arithmetic=True, out=None, name=None):
  6153. r"""
  6154. Inplace version of ``bitwise_right_shift`` API, the output Tensor will be inplaced with input ``x``.
  6155. Please refer to :ref:`api_paddle_bitwise_left_shift`.
  6156. """
  6157. out_shape = broadcast_shape(x.shape, y.shape)
  6158. if out_shape != x.shape:
  6159. raise ValueError(
  6160. f"The shape of broadcast output {out_shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  6161. )
  6162. if in_dynamic_or_pir_mode():
  6163. return _C_ops.bitwise_right_shift_(x, y, is_arithmetic)
  6164. def copysign(x, y, name=None):
  6165. r"""
  6166. Create a new floating-point tensor with the magnitude of input ``x`` and the sign of ``y``, elementwise.
  6167. Equation:
  6168. .. math::
  6169. copysign(x_{i},y_{i})=\left\{\begin{matrix}
  6170. & -|x_{i}| & if \space y_{i} <= -0.0\\
  6171. & |x_{i}| & if \space y_{i} >= 0.0
  6172. \end{matrix}\right.
  6173. Args:
  6174. x (Tensor): The input Tensor, magnitudes, the data type is bool, uint8, int8, int16, int32, int64, bfloat16, float16, float32, float64.
  6175. y (Tensor, number): contains value(s) whose signbit(s) are applied to the magnitudes in input.
  6176. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  6177. Returns:
  6178. out (Tensor), the output tensor. The data type is the same as the input tensor.
  6179. Examples:
  6180. .. code-block:: python
  6181. :name: example1
  6182. >>> import paddle
  6183. >>> x = paddle.to_tensor([1, 2, 3], dtype='float64')
  6184. >>> y = paddle.to_tensor([-1, 1, -1], dtype='float64')
  6185. >>> out = paddle.copysign(x, y)
  6186. >>> print(out)
  6187. Tensor(shape=[3], dtype=float64, place=Place(gpu:0), stop_gradient=True,
  6188. [-1., 2., -3.])
  6189. .. code-block:: python
  6190. :name: example2
  6191. >>> x = paddle.to_tensor([1, 2, 3], dtype='float64')
  6192. >>> y = paddle.to_tensor([-2], dtype='float64')
  6193. >>> res = paddle.copysign(x, y)
  6194. >>> print(res)
  6195. Tensor(shape=[3], dtype=float64, place=Place(gpu:0), stop_gradient=True,
  6196. [-1., -2., -3.])
  6197. .. code-block:: python
  6198. :name: example_zero1
  6199. >>> x = paddle.to_tensor([1, 2, 3], dtype='float64')
  6200. >>> y = paddle.to_tensor([0.0], dtype='float64')
  6201. >>> out = paddle.copysign(x, y)
  6202. >>> print(out)
  6203. Tensor(shape=[3], dtype=float64, place=Place(gpu:0), stop_gradient=True,
  6204. [1., 2., 3.])
  6205. .. code-block:: python
  6206. :name: example_zero2
  6207. >>> x = paddle.to_tensor([1, 2, 3], dtype='float64')
  6208. >>> y = paddle.to_tensor([-0.0], dtype='float64')
  6209. >>> out = paddle.copysign(x, y)
  6210. >>> print(out)
  6211. Tensor(shape=[3], dtype=float64, place=Place(gpu:0), stop_gradient=True,
  6212. [-1., -2., -3.])
  6213. """
  6214. if isinstance(y, (float, int)):
  6215. y = paddle.to_tensor(y, dtype=x.dtype)
  6216. out_shape = broadcast_shape(x.shape, y.shape)
  6217. if out_shape != x.shape:
  6218. warnings.warn(
  6219. f"The shape of broadcast output {out_shape} is different from the input tensor x with shape: {x.shape}, please make sure you are using copysign api correctly."
  6220. )
  6221. if in_dynamic_or_pir_mode():
  6222. return _C_ops.copysign(x, y)
  6223. else:
  6224. helper = LayerHelper("copysign", **locals())
  6225. out = helper.create_variable_for_type_inference(dtype=x.dtype)
  6226. helper.append_op(
  6227. type='copysign', inputs={'x': x, 'y': y}, outputs={'out': out}
  6228. )
  6229. return out
  6230. @inplace_apis_in_dygraph_only
  6231. def copysign_(x, y, name=None):
  6232. r"""
  6233. Inplace version of ``copysign`` API, the output Tensor will be inplaced with input ``x``.
  6234. Please refer to :ref:`api_paddle_copysign`.
  6235. """
  6236. if isinstance(y, (float, int)):
  6237. y = paddle.to_tensor(y, dtype=x.dtype)
  6238. out_shape = broadcast_shape(x.shape, y.shape)
  6239. if out_shape != x.shape:
  6240. raise ValueError(
  6241. f"The shape of broadcast output {out_shape} is different from that of inplace tensor {x.shape} in the Inplace operation."
  6242. )
  6243. return _C_ops.copysign_(x, y)
  6244. def hypot(x, y, name=None):
  6245. """
  6246. Calculate the length of the hypotenuse of a right-angle triangle. The equation is:
  6247. .. math::
  6248. out = {\\sqrt{x^2 + y^2}}
  6249. Args:
  6250. x (Tensor): The input Tensor, the data type is float32, float64, int32 or int64.
  6251. y (Tensor): The input Tensor, the data type is float32, float64, int32 or int64.
  6252. name (str, optional): Name for the operation (optional, default is None).For more information, please refer to :ref:`api_guide_Name`.
  6253. Returns:
  6254. out (Tensor): An N-D Tensor. If x, y have different shapes and are "broadcastable", the resulting tensor shape is the shape of x and y after broadcasting. If x, y have the same shape, its shape is the same as x and y. And the data type is float32 or float64.
  6255. Examples:
  6256. .. code-block:: python
  6257. >>> import paddle
  6258. >>> x = paddle.to_tensor([3], dtype='float32')
  6259. >>> y = paddle.to_tensor([4], dtype='float32')
  6260. >>> res = paddle.hypot(x, y)
  6261. >>> print(res)
  6262. Tensor(shape=[1], dtype=float32, place=Place(cpu), stop_gradient=True,
  6263. [5.])
  6264. """
  6265. if not isinstance(x, (paddle.Tensor, Variable)):
  6266. raise TypeError(f"x must be tensor type, but got {type(x)}")
  6267. if not isinstance(y, (paddle.Tensor, Variable)):
  6268. raise TypeError(f"y must be tensor type, but got {type(y)}")
  6269. out = (paddle.pow(x, 2) + paddle.pow(y, 2)).sqrt()
  6270. return out
  6271. @inplace_apis_in_dygraph_only
  6272. def hypot_(x, y, name=None):
  6273. r"""
  6274. Inplace version of ``hypot`` API, the output Tensor will be inplaced with input ``x``.
  6275. Please refer to :ref:`api_paddle_hypot`.
  6276. """
  6277. if not isinstance(x, (paddle.Tensor, Variable)):
  6278. raise TypeError(f"x must be tensor type, but got {type(x)}")
  6279. if not isinstance(y, (paddle.Tensor, Variable)):
  6280. raise TypeError(f"y must be tensor type, but got {type(y)}")
  6281. out = x.pow_(2).add_(y.pow(2)).sqrt_()
  6282. return out
  6283. def combinations(x, r=2, with_replacement=False, name=None):
  6284. """
  6285. Compute combinations of length r of the given tensor. The behavior is similar to python's itertools.combinations
  6286. when with_replacement is set to False, and itertools.combinations_with_replacement when with_replacement is set to True.
  6287. Args:
  6288. x (Tensor): 1-D input Tensor, the data type is float16, float32, float64, int32 or int64.
  6289. r (int, optional): number of elements to combine, default value is 2.
  6290. with_replacement (bool, optional): whether to allow duplication in combination, default value is False.
  6291. name (str, optional): Name for the operation (optional, default is None).For more information, please refer to :ref:`api_guide_Name`.
  6292. Returns:
  6293. out (Tensor). Tensor concatenated by combinations, same dtype with x.
  6294. Examples:
  6295. .. code-block:: python
  6296. >>> import paddle
  6297. >>> x = paddle.to_tensor([1, 2, 3], dtype='int32')
  6298. >>> res = paddle.combinations(x)
  6299. >>> print(res)
  6300. Tensor(shape=[3, 2], dtype=int32, place=Place(gpu:0), stop_gradient=True,
  6301. [[1, 2],
  6302. [1, 3],
  6303. [2, 3]])
  6304. """
  6305. if len(x.shape) != 1:
  6306. raise TypeError(f"Expect a 1-D vector, but got x shape {x.shape}")
  6307. if not isinstance(r, int) or r < 0:
  6308. raise ValueError(f"Expect a non-negative int, but got r={r}")
  6309. if r == 0:
  6310. return paddle.empty(shape=[0], dtype=x.dtype)
  6311. if (r > x.shape[0] and not with_replacement) or (
  6312. x.shape[0] == 0 and with_replacement
  6313. ):
  6314. return paddle.empty(shape=[0, r], dtype=x.dtype)
  6315. if r > 1:
  6316. t_l = [x for i in range(r)]
  6317. grids = paddle.meshgrid(t_l)
  6318. else:
  6319. grids = [x]
  6320. num_elements = x.numel()
  6321. t_range = paddle.arange(num_elements, dtype='int64')
  6322. if r > 1:
  6323. t_l = [t_range for i in range(r)]
  6324. index_grids = paddle.meshgrid(t_l)
  6325. else:
  6326. index_grids = [t_range]
  6327. mask = paddle.full(x.shape * r, True, dtype='bool')
  6328. if with_replacement:
  6329. for i in range(r - 1):
  6330. mask *= index_grids[i] <= index_grids[i + 1]
  6331. else:
  6332. for i in range(r - 1):
  6333. mask *= index_grids[i] < index_grids[i + 1]
  6334. for i in range(r):
  6335. grids[i] = grids[i].masked_select(mask)
  6336. return paddle.stack(grids, 1)
  6337. def signbit(x, name=None):
  6338. r"""
  6339. Tests if each element of input has its sign bit set or not.
  6340. Args:
  6341. x (Tensor): The input Tensor. Must be one of the following types: float16, float32, float64, bfloat16, uint8, int8, int16, int32, int64.
  6342. name (str, optional): Name for the operation (optional, default is None).For more information, please refer to :ref:`api_guide_Name`.
  6343. Returns:
  6344. out (Tensor): The output Tensor. The sign bit of the corresponding element of the input tensor, True means negative, False means positive.
  6345. Examples:
  6346. .. code-block:: python
  6347. :name: signbit-example-1
  6348. >>> import paddle
  6349. >>> paddle.set_device('cpu')
  6350. >>> x = paddle.to_tensor([-0., 1.1, -2.1, 0., 2.5], dtype='float32')
  6351. >>> res = paddle.signbit(x)
  6352. >>> print(res)
  6353. Tensor(shape=[5], dtype=bool, place=Place(cpu), stop_gradient=True,
  6354. [True, False, True, False, False])
  6355. .. code-block:: python
  6356. :name: signbit-example-2
  6357. >>> import paddle
  6358. >>> paddle.set_device('cpu')
  6359. >>> x = paddle.to_tensor([-5, -2, 3], dtype='int32')
  6360. >>> res = paddle.signbit(x)
  6361. >>> print(res)
  6362. Tensor(shape=[3], dtype=bool, place=Place(cpu), stop_gradient=True,
  6363. [True , True , False])
  6364. """
  6365. if not isinstance(x, (paddle.Tensor, Variable, paddle.pir.Value)):
  6366. raise TypeError(f"x must be tensor type, but got {type(x)}")
  6367. check_variable_and_dtype(
  6368. x,
  6369. "x",
  6370. [
  6371. 'float16',
  6372. 'float32',
  6373. 'float64',
  6374. 'bfloat16',
  6375. 'uint8',
  6376. 'int8',
  6377. 'int16',
  6378. 'int32',
  6379. 'int64',
  6380. ],
  6381. "signbit",
  6382. )
  6383. ones = [1.0] * math.prod(x.shape)
  6384. ones = paddle.to_tensor(ones, x.dtype).reshape(x.shape)
  6385. neg_zero_x = paddle.copysign(ones, x)
  6386. x = paddle.sign(neg_zero_x)
  6387. out = paddle.cast(x < 0, dtype='bool')
  6388. return out
  6389. def isposinf(x, name=None):
  6390. r"""
  6391. Tests if each element of input is positive infinity or not.
  6392. Args:
  6393. x (Tensor): The input Tensor. Must be one of the following types: bfloat16, float16, float32, float64, int8, int16, int32, int64, uint8.
  6394. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  6395. Returns:
  6396. out (Tensor), The output Tensor. Each element of output indicates whether the input element is positive infinity or not.
  6397. Examples:
  6398. .. code-block:: python
  6399. >>> import paddle
  6400. >>> paddle.set_device('cpu')
  6401. >>> x = paddle.to_tensor([-0., float('inf'), -2.1, -float('inf'), 2.5], dtype='float32')
  6402. >>> res = paddle.isposinf(x)
  6403. >>> print(res)
  6404. Tensor(shape=[5], dtype=bool, place=Place(cpu), stop_gradient=True,
  6405. [False, True, False, False, False])
  6406. """
  6407. if not isinstance(x, (paddle.Tensor, Variable, paddle.pir.Value)):
  6408. raise TypeError(f"x must be tensor type, but got {type(x)}")
  6409. check_variable_and_dtype(
  6410. x,
  6411. "x",
  6412. [
  6413. 'bfloat16',
  6414. 'float16',
  6415. 'float32',
  6416. 'float64',
  6417. 'int8',
  6418. 'int16',
  6419. 'int32',
  6420. 'int64',
  6421. 'uint8',
  6422. ],
  6423. "isposinf",
  6424. ) ## dtype is the intersection of dtypes supported by isinf and signbit
  6425. is_inf = paddle.isinf(x)
  6426. signbit = ~paddle.signbit(x)
  6427. return paddle.logical_and(is_inf, signbit)
  6428. def isneginf(x, name=None):
  6429. r"""
  6430. Tests if each element of input is negative infinity or not.
  6431. Args:
  6432. x (Tensor): The input Tensor. Must be one of the following types: bfloat16, float16, float32, float64, int8, int16, int32, int64, uint8.
  6433. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  6434. Returns:
  6435. out (Tensor), The output Tensor. Each element of output indicates whether the input element is negative infinity or not.
  6436. Examples:
  6437. .. code-block:: python
  6438. >>> import paddle
  6439. >>> paddle.set_device('cpu')
  6440. >>> x = paddle.to_tensor([-0., float('inf'), -2.1, -float('inf'), 2.5], dtype='float32')
  6441. >>> res = paddle.isneginf(x)
  6442. >>> print(res)
  6443. Tensor(shape=[5], dtype=bool, place=Place(cpu), stop_gradient=True,
  6444. [False, False, False, True, False])
  6445. """
  6446. if not isinstance(x, (paddle.Tensor, Variable, paddle.pir.Value)):
  6447. raise TypeError(f"x must be tensor type, but got {type(x)}")
  6448. check_variable_and_dtype(
  6449. x,
  6450. "x",
  6451. [
  6452. 'bfloat16',
  6453. 'float16',
  6454. 'float32',
  6455. 'float64',
  6456. 'int8',
  6457. 'int16',
  6458. 'int32',
  6459. 'int64',
  6460. 'uint8',
  6461. ],
  6462. "isneginf",
  6463. )
  6464. is_inf = paddle.isinf(x)
  6465. signbit = paddle.signbit(x)
  6466. return paddle.logical_and(is_inf, signbit)
  6467. def isreal(x, name=None):
  6468. r"""
  6469. Tests if each element of input is a real number or not.
  6470. Args:
  6471. x (Tensor): The input Tensor.
  6472. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  6473. Returns:
  6474. out (Tensor), The output Tensor. Each element of output indicates whether the input element is a real number or not.
  6475. Examples:
  6476. .. code-block:: python
  6477. >>> import paddle
  6478. >>> paddle.set_device('cpu')
  6479. >>> x = paddle.to_tensor([-0., -2.1, 2.5], dtype='float32')
  6480. >>> res = paddle.isreal(x)
  6481. >>> print(res)
  6482. Tensor(shape=[3], dtype=bool, place=Place(cpu), stop_gradient=True,
  6483. [True, True, True])
  6484. >>> x = paddle.to_tensor([(-0.+1j), (-2.1+0.2j), (2.5-3.1j)])
  6485. >>> res = paddle.isreal(x)
  6486. >>> print(res)
  6487. Tensor(shape=[3], dtype=bool, place=Place(cpu), stop_gradient=True,
  6488. [False, False, False])
  6489. >>> x = paddle.to_tensor([(-0.+1j), (-2.1+0j), (2.5-0j)])
  6490. >>> res = paddle.isreal(x)
  6491. >>> print(res)
  6492. Tensor(shape=[3], dtype=bool, place=Place(cpu), stop_gradient=True,
  6493. [False, True, True])
  6494. """
  6495. if not isinstance(x, (paddle.Tensor, Variable, paddle.pir.Value)):
  6496. raise TypeError(f"x must be tensor type, but got {type(x)}")
  6497. dtype = x.dtype
  6498. is_real_dtype = not (
  6499. dtype == core.VarDesc.VarType.COMPLEX64
  6500. or dtype == core.VarDesc.VarType.COMPLEX128
  6501. or dtype == core.DataType.COMPLEX64
  6502. or dtype == core.DataType.COMPLEX128
  6503. )
  6504. if is_real_dtype:
  6505. return paddle.ones_like(x, dtype='bool')
  6506. return paddle.equal(paddle.imag(x), 0)
  6507. def sinc(x, name=None):
  6508. r"""
  6509. Calculate the normalized sinc of ``x`` elementwise.
  6510. .. math::
  6511. out_i =
  6512. \left\{
  6513. \begin{aligned}
  6514. &1 & \text{ if $x_i = 0$} \\
  6515. &\frac{\sin(\pi x_i)}{\pi x_i} & \text{ otherwise}
  6516. \end{aligned}
  6517. \right.
  6518. Args:
  6519. x (Tensor): The input Tensor. Must be one of the following types: bfloat16, float16, float32, float64.
  6520. name (str, optional): Name for the operation (optional, default is None). For more information, please refer to :ref:`api_guide_Name`.
  6521. Returns:
  6522. out (Tensor), The Tensor of elementwise-computed normalized sinc result.
  6523. Examples:
  6524. .. code-block:: python
  6525. >>> import paddle
  6526. >>> paddle.set_device('cpu')
  6527. >>> paddle.seed(100)
  6528. >>> x = paddle.rand([2,3], dtype='float32')
  6529. >>> res = paddle.sinc(x)
  6530. >>> print(res)
  6531. Tensor(shape=[2, 3], dtype=float32, place=Place(cpu), stop_gradient=True,
  6532. [[0.56691176, 0.93089867, 0.99977750],
  6533. [0.61639023, 0.79618412, 0.89171958]])
  6534. """
  6535. if not isinstance(x, (paddle.Tensor, Variable, paddle.pir.Value)):
  6536. raise TypeError(f"x must be tensor type, but got {type(x)}")
  6537. check_variable_and_dtype(
  6538. x,
  6539. "x",
  6540. [
  6541. 'uint16',
  6542. 'float16',
  6543. 'float32',
  6544. 'float64',
  6545. ],
  6546. "sinc",
  6547. )
  6548. tmp = paddle.where(x != 0, x, paddle.full_like(x, 1.0e-20))
  6549. tmp = paddle.multiply(tmp, paddle.to_tensor(math.pi, dtype=x.dtype))
  6550. tmp = paddle.divide(tmp.sin(), tmp)
  6551. return paddle.where(~paddle.isnan(tmp), tmp, paddle.full_like(x, 1.0))
  6552. @inplace_apis_in_dygraph_only
  6553. def sinc_(x, name=None):
  6554. r"""
  6555. Inplace version of ``sinc`` API, the output Tensor will be inplaced with input ``x``.
  6556. Please refer to :ref:`api_paddle_sinc`.
  6557. """
  6558. if not isinstance(x, (paddle.Tensor, Variable)):
  6559. raise TypeError(f"x must be tensor type, but got {type(x)}")
  6560. check_variable_and_dtype(
  6561. x,
  6562. "x",
  6563. [
  6564. 'uint16',
  6565. 'float16',
  6566. 'float32',
  6567. 'float64',
  6568. ],
  6569. "sinc_",
  6570. )
  6571. paddle.where_(x != 0, x, paddle.full_like(x, 1.0e-20))
  6572. paddle.multiply_(x, paddle.to_tensor(math.pi, dtype=x.dtype))
  6573. tmp = paddle.clone(x)
  6574. paddle.sin_(x)
  6575. paddle.divide_(x, tmp)
  6576. return paddle.where(~paddle.isnan(x), x, paddle.full_like(x, 1.0))
  6577. def isin(x, test_x, assume_unique=False, invert=False, name=None):
  6578. r"""
  6579. Tests if each element of `x` is in `test_x`.
  6580. Args:
  6581. x (Tensor): The input Tensor. Supported data type: 'bfloat16', 'float16', 'float32', 'float64', 'int32', 'int64'.
  6582. test_x (Tensor): Tensor values against which to test for each input element. Supported data type: 'bfloat16', 'float16', 'float32', 'float64', 'int32', 'int64'.
  6583. assume_unique (bool, optional): If True, indicates both `x` and `test_x` contain unique elements, which could make the calculation faster. Default: False.
  6584. invert (bool, optional): Indicate whether to invert the boolean return tensor. If True, invert the results. Default: False.
  6585. name (str, optional): Name for the operation (optional, default is None).For more information, please refer to :ref:`api_guide_Name`.
  6586. Returns:
  6587. out (Tensor), The output Tensor with the same shape as `x`.
  6588. Examples:
  6589. .. code-block:: python
  6590. >>> import paddle
  6591. >>> paddle.set_device('cpu')
  6592. >>> x = paddle.to_tensor([-0., -2.1, 2.5, 1.0, -2.1], dtype='float32')
  6593. >>> test_x = paddle.to_tensor([-2.1, 2.5], dtype='float32')
  6594. >>> res = paddle.isin(x, test_x)
  6595. >>> print(res)
  6596. Tensor(shape=[5], dtype=bool, place=Place(cpu), stop_gradient=True,
  6597. [False, True, True, False, True])
  6598. >>> x = paddle.to_tensor([-0., -2.1, 2.5, 1.0, -2.1], dtype='float32')
  6599. >>> test_x = paddle.to_tensor([-2.1, 2.5], dtype='float32')
  6600. >>> res = paddle.isin(x, test_x, invert=True)
  6601. >>> print(res)
  6602. Tensor(shape=[5], dtype=bool, place=Place(cpu), stop_gradient=True,
  6603. [True, False, False, True, False])
  6604. >>> # Set `assume_unique` to True only when `x` and `test_x` contain unique values, otherwise the result may be incorrect.
  6605. >>> x = paddle.to_tensor([0., 1., 2.]*20).reshape([20, 3])
  6606. >>> test_x = paddle.to_tensor([0., 1.]*20)
  6607. >>> correct_result = paddle.isin(x, test_x, assume_unique=False)
  6608. >>> print(correct_result)
  6609. Tensor(shape=[20, 3], dtype=bool, place=Place(cpu), stop_gradient=True,
  6610. [[True , True , False],
  6611. [True , True , False],
  6612. [True , True , False],
  6613. [True , True , False],
  6614. [True , True , False],
  6615. [True , True , False],
  6616. [True , True , False],
  6617. [True , True , False],
  6618. [True , True , False],
  6619. [True , True , False],
  6620. [True , True , False],
  6621. [True , True , False],
  6622. [True , True , False],
  6623. [True , True , False],
  6624. [True , True , False],
  6625. [True , True , False],
  6626. [True , True , False],
  6627. [True , True , False],
  6628. [True , True , False],
  6629. [True , True , False]])
  6630. >>> incorrect_result = paddle.isin(x, test_x, assume_unique=True)
  6631. >>> print(incorrect_result)
  6632. Tensor(shape=[20, 3], dtype=bool, place=Place(gpu:0), stop_gradient=True,
  6633. [[True , True , True ],
  6634. [True , True , True ],
  6635. [True , True , True ],
  6636. [True , True , True ],
  6637. [True , True , True ],
  6638. [True , True , True ],
  6639. [True , True , True ],
  6640. [True , True , True ],
  6641. [True , True , True ],
  6642. [True , True , True ],
  6643. [True , True , True ],
  6644. [True , True , True ],
  6645. [True , True , True ],
  6646. [True , True , True ],
  6647. [True , True , True ],
  6648. [True , True , True ],
  6649. [True , True , True ],
  6650. [True , True , True ],
  6651. [True , True , True ],
  6652. [True , True , False]])
  6653. """
  6654. if not isinstance(x, (paddle.Tensor, Variable, paddle.pir.Value)):
  6655. raise TypeError(f"x must be tensor type, but got {type(x)}")
  6656. if not isinstance(test_x, (paddle.Tensor, Variable, paddle.pir.Value)):
  6657. raise TypeError(f"x must be tensor type, but got {type(test_x)}")
  6658. check_variable_and_dtype(
  6659. x,
  6660. "x",
  6661. [
  6662. 'uint16',
  6663. 'float16',
  6664. 'float32',
  6665. 'float64',
  6666. 'int32',
  6667. 'int64',
  6668. ],
  6669. "isin",
  6670. )
  6671. check_variable_and_dtype(
  6672. test_x,
  6673. "test_x",
  6674. [
  6675. 'uint16',
  6676. 'float16',
  6677. 'float32',
  6678. 'float64',
  6679. 'int32',
  6680. 'int64',
  6681. ],
  6682. "isin",
  6683. )
  6684. x_zero_dim = False
  6685. if len(x.shape) == 0:
  6686. x = x.reshape([1])
  6687. x_zero_dim = True
  6688. size_x = math.prod(x.shape)
  6689. size_t = math.prod(test_x.shape)
  6690. if size_t < math.pow(size_x, 0.145) * 10.0:
  6691. # use brute-force searching if the test_x size is small
  6692. if len(x.shape) == 0:
  6693. return paddle.zeros([], dtype='bool')
  6694. tmp = x.reshape(tuple(x.shape) + ((1,) * test_x.ndim))
  6695. cmp = tmp == test_x
  6696. dim = tuple(range(-1, -test_x.ndim - 1, -1))
  6697. cmp = cmp.any(axis=dim)
  6698. if invert:
  6699. cmp = ~cmp
  6700. else:
  6701. x_flat = x.flatten()
  6702. test_x_flat = test_x.flatten()
  6703. if assume_unique:
  6704. # if x and test_x both contain unique elements, use stable argsort method which could be faster
  6705. all_elements = paddle.concat([x_flat, test_x_flat])
  6706. sorted_index = paddle.argsort(all_elements, stable=True)
  6707. sorted_x = all_elements[sorted_index]
  6708. duplicate_mask = paddle.full_like(sorted_index, False, dtype='bool')
  6709. if not in_dynamic_mode():
  6710. duplicate_mask = paddle.static.setitem(
  6711. duplicate_mask,
  6712. paddle.arange(duplicate_mask.numel() - 1),
  6713. sorted_x[1:] == sorted_x[:-1],
  6714. )
  6715. else:
  6716. duplicate_mask[:-1] = sorted_x[1:] == sorted_x[:-1]
  6717. if invert:
  6718. duplicate_mask = duplicate_mask.logical_not()
  6719. mask = paddle.empty_like(duplicate_mask)
  6720. if not in_dynamic_or_pir_mode():
  6721. mask = paddle.static.setitem(mask, sorted_index, duplicate_mask)
  6722. else:
  6723. mask[sorted_index] = duplicate_mask
  6724. cmp = mask[0 : x.numel()].reshape(x.shape)
  6725. else:
  6726. # otherwise use searchsorted method
  6727. sorted_test_x = paddle.sort(test_x_flat)
  6728. idx = paddle.searchsorted(sorted_test_x, x_flat)
  6729. test_idx = paddle.where(
  6730. idx < sorted_test_x.numel(),
  6731. idx,
  6732. paddle.zeros_like(idx, 'int64'),
  6733. )
  6734. cmp = sorted_test_x[test_idx] == x_flat
  6735. cmp = cmp.logical_not() if invert else cmp
  6736. cmp = cmp.reshape(x.shape)
  6737. if x_zero_dim:
  6738. return cmp.reshape([])
  6739. else:
  6740. return cmp