functional.py 255 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912
  1. """Functional interface."""
  2. import importlib
  3. import math
  4. import warnings
  5. from collections.abc import Callable
  6. from typing import Any as _Any, Optional, TYPE_CHECKING
  7. import torch
  8. from torch import _VF, sym_int as _sym_int, Tensor
  9. from torch._C import (
  10. _add_docstr,
  11. _infer_size,
  12. _ScalingType as ScalingType, # pyrefly: ignore [missing-module-attribute]
  13. _SwizzleType as SwizzleType, # pyrefly: ignore [missing-module-attribute]
  14. )
  15. from torch._jit_internal import (
  16. _overload,
  17. boolean_dispatch,
  18. BroadcastingList1,
  19. BroadcastingList2, # pyrefly: ignore [missing-module-attribute]
  20. BroadcastingList3, # pyrefly: ignore [missing-module-attribute]
  21. )
  22. from torch._torch_docs import reproducibility_notes, sparse_support_notes, tf32_notes
  23. from torch.nn import _reduction as _Reduction, grad # noqa: F401
  24. from torch.nn.modules.utils import _list_with_default, _pair, _single, _triple
  25. from torch.overrides import (
  26. handle_torch_function,
  27. has_torch_function,
  28. has_torch_function_unary,
  29. has_torch_function_variadic,
  30. )
  31. # Set visibility of the bound enums to this module
  32. ScalingType.__module__ = "torch.nn.functional"
  33. SwizzleType.__module__ = "torch.nn.functional"
  34. if TYPE_CHECKING:
  35. from torch.types import _dtype as DType
  36. else:
  37. # The JIT doesn't understand Union, nor torch.dtype here
  38. DType = int
  39. try:
  40. import numpy as np
  41. except ModuleNotFoundError:
  42. np = None
  43. conv1d = _add_docstr(
  44. torch.conv1d,
  45. r"""
  46. conv1d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> Tensor
  47. Applies a 1D convolution over an input signal composed of several input
  48. planes.
  49. {tf32_note}
  50. See :class:`~torch.nn.Conv1d` for details and output shape.
  51. Note:
  52. {cudnn_reproducibility_note}
  53. Note:
  54. This operator supports complex data types i.e. ``complex32, complex64, complex128``.
  55. """.format(**reproducibility_notes, **tf32_notes)
  56. + r"""
  57. Args:
  58. input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`
  59. weight: filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kW)`
  60. bias: optional bias of shape :math:`(\text{out\_channels})`. Default: ``None``
  61. stride: the stride of the convolving kernel. Can be a single number or
  62. a one-element tuple `(sW,)`. Default: 1
  63. padding: implicit paddings on both sides of the input. Can be a string {'valid', 'same'},
  64. single number or a one-element tuple `(padW,)`. Default: 0
  65. ``padding='valid'`` is the same as no padding. ``padding='same'`` pads
  66. the input so the output has the same shape as the input. However, this mode
  67. doesn't support any stride values other than 1.
  68. .. warning::
  69. For ``padding='same'``, if the ``weight`` is even-length and
  70. ``dilation`` is odd in any dimension, a full :func:`pad` operation
  71. may be needed internally. Lowering performance.
  72. dilation: the spacing between kernel elements. Can be a single number or
  73. a one-element tuple `(dW,)`. Default: 1
  74. groups: split input into groups, :math:`\text{in\_channels}` should be divisible by
  75. the number of groups. Default: 1
  76. Examples::
  77. >>> inputs = torch.randn(33, 16, 30)
  78. >>> filters = torch.randn(20, 16, 5)
  79. >>> F.conv1d(inputs, filters)
  80. """,
  81. )
  82. conv2d = _add_docstr(
  83. torch.conv2d,
  84. r"""
  85. conv2d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> Tensor
  86. Applies a 2D convolution over an input image composed of several input
  87. planes.
  88. {tf32_note}
  89. See :class:`~torch.nn.Conv2d` for details and output shape.
  90. Note:
  91. {cudnn_reproducibility_note}
  92. Note:
  93. This operator supports complex data types i.e. ``complex32, complex64, complex128``.
  94. """.format(**reproducibility_notes, **tf32_notes)
  95. + r"""
  96. Args:
  97. input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
  98. weight: filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kH , kW)`
  99. bias: optional bias tensor of shape :math:`(\text{out\_channels})`. Default: ``None``
  100. stride: the stride of the convolving kernel. Can be a single number or a
  101. tuple `(sH, sW)`. Default: 1
  102. padding: implicit paddings on both sides of the input. Can be a string {'valid', 'same'},
  103. single number or a tuple `(padH, padW)`. Default: 0
  104. ``padding='valid'`` is the same as no padding. ``padding='same'`` pads
  105. the input so the output has the same shape as the input. However, this mode
  106. doesn't support any stride values other than 1.
  107. .. warning::
  108. For ``padding='same'``, if the ``weight`` is even-length and
  109. ``dilation`` is odd in any dimension, a full :func:`pad` operation
  110. may be needed internally. Lowering performance.
  111. dilation: the spacing between kernel elements. Can be a single number or
  112. a tuple `(dH, dW)`. Default: 1
  113. groups: split input into groups, both :math:`\text{in\_channels}` and :math:`\text{out\_channels}`
  114. should be divisible by the number of groups. Default: 1
  115. Examples::
  116. >>> # With square kernels and equal stride
  117. >>> filters = torch.randn(8, 4, 3, 3)
  118. >>> inputs = torch.randn(1, 4, 5, 5)
  119. >>> F.conv2d(inputs, filters, padding=1)
  120. """,
  121. ) # noqa: E501
  122. conv3d = _add_docstr(
  123. torch.conv3d,
  124. r"""
  125. conv3d(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1) -> Tensor
  126. Applies a 3D convolution over an input image composed of several input
  127. planes.
  128. {tf32_note}
  129. See :class:`~torch.nn.Conv3d` for details and output shape.
  130. Note:
  131. {cudnn_reproducibility_note}
  132. Note:
  133. This operator supports complex data types i.e. ``complex32, complex64, complex128``.
  134. """.format(**reproducibility_notes, **tf32_notes)
  135. + r"""
  136. Args:
  137. input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iT , iH , iW)`
  138. weight: filters of shape :math:`(\text{out\_channels} , \frac{\text{in\_channels}}{\text{groups}} , kT , kH , kW)`
  139. bias: optional bias tensor of shape :math:`(\text{out\_channels})`. Default: None
  140. stride: the stride of the convolving kernel. Can be a single number or a
  141. tuple `(sT, sH, sW)`. Default: 1
  142. padding: implicit paddings on both sides of the input. Can be a string {'valid', 'same'},
  143. single number or a tuple `(padT, padH, padW)`. Default: 0
  144. ``padding='valid'`` is the same as no padding. ``padding='same'`` pads
  145. the input so the output has the same shape as the input. However, this mode
  146. doesn't support any stride values other than 1.
  147. .. warning::
  148. For ``padding='same'``, if the ``weight`` is even-length and
  149. ``dilation`` is odd in any dimension, a full :func:`pad` operation
  150. may be needed internally. Lowering performance.
  151. dilation: the spacing between kernel elements. Can be a single number or
  152. a tuple `(dT, dH, dW)`. Default: 1
  153. groups: split input into groups, :math:`\text{in\_channels}` should be divisible by
  154. the number of groups. Default: 1
  155. Examples::
  156. >>> filters = torch.randn(33, 16, 3, 3, 3)
  157. >>> inputs = torch.randn(20, 16, 50, 10, 20)
  158. >>> F.conv3d(inputs, filters)
  159. """,
  160. ) # noqa: E501
  161. conv_transpose1d = _add_docstr(
  162. torch.conv_transpose1d,
  163. r"""
  164. conv_transpose1d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1) -> Tensor
  165. Applies a 1D transposed convolution operator over an input signal
  166. composed of several input planes, sometimes also called "deconvolution".
  167. {tf32_note}
  168. See :class:`~torch.nn.ConvTranspose1d` for details and output shape.
  169. Note:
  170. {cudnn_reproducibility_note}
  171. """.format(**reproducibility_notes, **tf32_notes)
  172. + r"""
  173. Args:
  174. input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`
  175. weight: filters of shape :math:`(\text{in\_channels} , \frac{\text{out\_channels}}{\text{groups}} , kW)`
  176. bias: optional bias of shape :math:`(\text{out\_channels})`. Default: None
  177. stride: the stride of the convolving kernel. Can be a single number or a
  178. tuple ``(sW,)``. Default: 1
  179. padding: ``dilation * (kernel_size - 1) - padding`` zero-padding will be added to both
  180. sides of each dimension in the input. Can be a single number or a tuple
  181. ``(padW,)``. Default: 0
  182. output_padding: additional size added to one side of each dimension in the
  183. output shape. Can be a single number or a tuple ``(out_padW)``. Default: 0
  184. groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
  185. number of groups. Default: 1
  186. dilation: the spacing between kernel elements. Can be a single number or
  187. a tuple ``(dW,)``. Default: 1
  188. Examples::
  189. >>> inputs = torch.randn(20, 16, 50)
  190. >>> weights = torch.randn(16, 33, 5)
  191. >>> F.conv_transpose1d(inputs, weights)
  192. """,
  193. )
  194. conv_transpose2d = _add_docstr(
  195. torch.conv_transpose2d,
  196. r"""
  197. conv_transpose2d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1) -> Tensor
  198. Applies a 2D transposed convolution operator over an input image
  199. composed of several input planes, sometimes also called "deconvolution".
  200. {tf32_note}
  201. See :class:`~torch.nn.ConvTranspose2d` for details and output shape.
  202. Note:
  203. {cudnn_reproducibility_note}
  204. """.format(**reproducibility_notes, **tf32_notes)
  205. + r"""
  206. Args:
  207. input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
  208. weight: filters of shape :math:`(\text{in\_channels} , \frac{\text{out\_channels}}{\text{groups}} , kH , kW)`
  209. bias: optional bias of shape :math:`(\text{out\_channels})`. Default: None
  210. stride: the stride of the convolving kernel. Can be a single number or a
  211. tuple ``(sH, sW)``. Default: 1
  212. padding: ``dilation * (kernel_size - 1) - padding`` zero-padding will be added to both
  213. sides of each dimension in the input. Can be a single number or a tuple
  214. ``(padH, padW)``. Default: 0
  215. output_padding: additional size added to one side of each dimension in the
  216. output shape. Can be a single number or a tuple ``(out_padH, out_padW)``.
  217. Default: 0
  218. groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
  219. number of groups. Default: 1
  220. dilation: the spacing between kernel elements. Can be a single number or
  221. a tuple ``(dH, dW)``. Default: 1
  222. Examples::
  223. >>> # With square kernels and equal stride
  224. >>> inputs = torch.randn(1, 4, 5, 5)
  225. >>> weights = torch.randn(4, 8, 3, 3)
  226. >>> F.conv_transpose2d(inputs, weights, padding=1)
  227. """,
  228. ) # noqa: E501
  229. conv_transpose3d = _add_docstr(
  230. torch.conv_transpose3d,
  231. r"""
  232. conv_transpose3d(input, weight, bias=None, stride=1, padding=0, output_padding=0, groups=1, dilation=1) -> Tensor
  233. Applies a 3D transposed convolution operator over an input image
  234. composed of several input planes, sometimes also called "deconvolution"
  235. {tf32_note}
  236. See :class:`~torch.nn.ConvTranspose3d` for details and output shape.
  237. Note:
  238. {cudnn_reproducibility_note}
  239. """.format(**reproducibility_notes, **tf32_notes)
  240. + r"""
  241. Args:
  242. input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iT , iH , iW)`
  243. weight: filters of shape :math:`(\text{in\_channels} , \frac{\text{out\_channels}}{\text{groups}} , kT , kH , kW)`
  244. bias: optional bias of shape :math:`(\text{out\_channels})`. Default: None
  245. stride: the stride of the convolving kernel. Can be a single number or a
  246. tuple ``(sT, sH, sW)``. Default: 1
  247. padding: ``dilation * (kernel_size - 1) - padding`` zero-padding will be added to both
  248. sides of each dimension in the input. Can be a single number or a tuple
  249. ``(padT, padH, padW)``. Default: 0
  250. output_padding: additional size added to one side of each dimension in the
  251. output shape. Can be a single number or a tuple
  252. ``(out_padT, out_padH, out_padW)``. Default: 0
  253. groups: split input into groups, :math:`\text{in\_channels}` should be divisible by the
  254. number of groups. Default: 1
  255. dilation: the spacing between kernel elements. Can be a single number or
  256. a tuple `(dT, dH, dW)`. Default: 1
  257. Examples::
  258. >>> inputs = torch.randn(20, 16, 50, 10, 20)
  259. >>> weights = torch.randn(16, 33, 3, 3, 3)
  260. >>> F.conv_transpose3d(inputs, weights)
  261. """,
  262. ) # noqa: E501
  263. conv_tbc = _add_docstr(
  264. torch.conv_tbc,
  265. r"""
  266. Applies a 1-dimensional sequence convolution over an input sequence.
  267. Input and output dimensions are (Time, Batch, Channels) - hence TBC.
  268. Args:
  269. input: input tensor of shape :math:`(\text{sequence length} \times batch \times \text{in\_channels})`
  270. weight: filter of shape (:math:`\text{kernel width} \times \text{in\_channels} \times \text{out\_channels}`)
  271. bias: bias of shape (:math:`\text{out\_channels}`)
  272. pad: number of timesteps to pad. Default: 0
  273. """,
  274. )
  275. # Pooling
  276. avg_pool1d = _add_docstr(
  277. torch.avg_pool1d,
  278. r"""
  279. avg_pool1d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True) -> Tensor
  280. Applies a 1D average pooling over an input signal composed of several
  281. input planes.
  282. See :class:`~torch.nn.AvgPool1d` for details and output shape.
  283. Args:
  284. input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`
  285. kernel_size: the size of the window. Can be a single number or a
  286. tuple `(kW,)`
  287. stride: the stride of the window. Can be a single number or a tuple
  288. `(sW,)`. Default: :attr:`kernel_size`
  289. padding: implicit zero paddings on both sides of the input. Can be a single
  290. number or a tuple `(padW,)`. Should be at most half of effective kernel
  291. size, that is :math:`((kernelSize - 1) * dilation + 1) / 2`. Default: 0
  292. ceil_mode: when True, will use `ceil` instead of `floor` to compute the
  293. output shape. Default: ``False``
  294. count_include_pad: when True, will include the zero-padding in the
  295. averaging calculation. Default: ``True``
  296. Examples::
  297. >>> # pool of square window of size=3, stride=2
  298. >>> input = torch.tensor([[[1, 2, 3, 4, 5, 6, 7]]], dtype=torch.float32)
  299. >>> F.avg_pool1d(input, kernel_size=3, stride=2)
  300. tensor([[[ 2., 4., 6.]]])
  301. """,
  302. )
  303. avg_pool2d = _add_docstr(
  304. torch._C._nn.avg_pool2d,
  305. r"""
  306. avg_pool2d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=None) -> Tensor
  307. Applies 2D average-pooling operation in :math:`kH \times kW` regions by step size
  308. :math:`sH \times sW` steps. The number of output features is equal to the number of
  309. input planes.
  310. See :class:`~torch.nn.AvgPool2d` for details and output shape.
  311. Args:
  312. input: input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`
  313. kernel_size: size of the pooling region. Can be a single number, a single-element tuple or a
  314. tuple `(kH, kW)`
  315. stride: stride of the pooling operation. Can be a single number, a single-element tuple or a
  316. tuple `(sH, sW)`. Default: :attr:`kernel_size`
  317. padding: implicit zero paddings on both sides of the input. Can be a
  318. single number, a single-element tuple or a tuple `(padH, padW)`.
  319. Should be at most half of effective kernel size, that
  320. is :math:`((kernelSize - 1) * dilation + 1) / 2`. Default: 0
  321. ceil_mode: when True, will use `ceil` instead of `floor` in the formula
  322. to compute the output shape. Default: ``False``
  323. count_include_pad: when True, will include the zero-padding in the
  324. averaging calculation. Default: ``True``
  325. divisor_override: if specified, it will be used as divisor, otherwise
  326. size of the pooling region will be used. Default: None
  327. """,
  328. )
  329. avg_pool3d = _add_docstr(
  330. torch._C._nn.avg_pool3d,
  331. r"""
  332. avg_pool3d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True, divisor_override=None) -> Tensor
  333. Applies 3D average-pooling operation in :math:`kT \times kH \times kW` regions by step
  334. size :math:`sT \times sH \times sW` steps. The number of output features is equal to
  335. :math:`\lfloor\frac{\text{input planes}}{sT}\rfloor`.
  336. See :class:`~torch.nn.AvgPool3d` for details and output shape.
  337. Args:
  338. input: input tensor :math:`(\text{minibatch} , \text{in\_channels} , iT \times iH , iW)`
  339. kernel_size: size of the pooling region. Can be a single number or a
  340. tuple `(kT, kH, kW)`
  341. stride: stride of the pooling operation. Can be a single number or a
  342. tuple `(sT, sH, sW)`. Default: :attr:`kernel_size`
  343. padding: implicit zero paddings on both sides of the input. Can be a
  344. single number or a tuple `(padT, padH, padW)`. Should be at most half
  345. of effective kernel size, that is :math:`((kernelSize - 1) * dilation + 1) / 2`.
  346. Default: 0
  347. ceil_mode: when True, will use `ceil` instead of `floor` in the formula
  348. to compute the output shape
  349. count_include_pad: when True, will include the zero-padding in the
  350. averaging calculation
  351. divisor_override: if specified, it will be used as divisor, otherwise
  352. size of the pooling region will be used. Default: None
  353. """,
  354. )
  355. def fractional_max_pool2d_with_indices(
  356. input: Tensor,
  357. kernel_size: BroadcastingList2[int],
  358. output_size: Optional[BroadcastingList2[int]] = None,
  359. output_ratio: Optional[BroadcastingList2[float]] = None,
  360. return_indices: bool = False,
  361. _random_samples: Optional[Tensor] = None,
  362. ) -> tuple[Tensor, Tensor]: # noqa: D400
  363. r"""
  364. fractional_max_pool2d(input, kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None)
  365. Applies 2D fractional max pooling over an input signal composed of several input planes.
  366. Fractional MaxPooling is described in detail in the paper `Fractional MaxPooling`_ by Ben Graham
  367. The max-pooling operation is applied in :math:`kH \times kW` regions by a stochastic
  368. step size determined by the target output size.
  369. The number of output features is equal to the number of input planes.
  370. Args:
  371. kernel_size: the size of the window to take a max over.
  372. Can be a single number :math:`k` (for a square kernel of :math:`k \times k`)
  373. or a tuple `(kH, kW)`
  374. output_size: the target output size of the image of the form :math:`oH \times oW`.
  375. Can be a tuple `(oH, oW)` or a single number :math:`oH` for a square image :math:`oH \times oH`
  376. output_ratio: If one wants to have an output size as a ratio of the input size, this option can be given.
  377. This has to be a number or tuple in the range (0, 1)
  378. return_indices: if ``True``, will return the indices along with the outputs.
  379. Useful to pass to :func:`~torch.nn.functional.max_unpool2d`.
  380. Examples::
  381. >>> input = torch.randn(20, 16, 50, 32)
  382. >>> # pool of square window of size=3, and target output size 13x12
  383. >>> F.fractional_max_pool2d(input, 3, output_size=(13, 12))
  384. >>> # pool of square window and target output size being half of input image size
  385. >>> F.fractional_max_pool2d(input, 3, output_ratio=(0.5, 0.5))
  386. .. _Fractional MaxPooling:
  387. http://arxiv.org/abs/1412.6071
  388. """
  389. if has_torch_function_variadic(input, _random_samples):
  390. return handle_torch_function(
  391. fractional_max_pool2d_with_indices,
  392. (input, _random_samples),
  393. input,
  394. kernel_size,
  395. output_size=output_size,
  396. output_ratio=output_ratio,
  397. return_indices=return_indices,
  398. _random_samples=_random_samples,
  399. )
  400. if output_size is None and output_ratio is None:
  401. raise ValueError(
  402. "fractional_max_pool2d requires specifying either an output_size or an output_ratio"
  403. )
  404. if output_size is None:
  405. if output_ratio is None:
  406. raise AssertionError("output_ratio is unexpectedly None")
  407. if len(output_ratio) > 2:
  408. raise ValueError(
  409. "fractional_max_pool2d requires output_ratio to either be a single Int or tuple of Ints."
  410. )
  411. _output_ratio = _pair(output_ratio)
  412. output_size = [
  413. int(input.size(-2) * _output_ratio[0]),
  414. int(input.size(-1) * _output_ratio[1]),
  415. ]
  416. if _random_samples is None:
  417. n_batch = 1 if input.dim() == 3 else input.size(0)
  418. _random_samples = torch.rand(
  419. n_batch, input.size(-3), 2, dtype=input.dtype, device=input.device
  420. )
  421. return torch._C._nn.fractional_max_pool2d(
  422. input, kernel_size, output_size, _random_samples
  423. )
  424. def _fractional_max_pool2d(
  425. input: Tensor,
  426. kernel_size: BroadcastingList2[int],
  427. output_size: Optional[BroadcastingList2[int]] = None,
  428. output_ratio: Optional[BroadcastingList2[float]] = None,
  429. return_indices: bool = False,
  430. _random_samples: Optional[Tensor] = None,
  431. ) -> Tensor:
  432. if has_torch_function_variadic(input, _random_samples):
  433. return handle_torch_function(
  434. fractional_max_pool2d,
  435. (input, _random_samples),
  436. input,
  437. kernel_size,
  438. output_size=output_size,
  439. output_ratio=output_ratio,
  440. return_indices=return_indices,
  441. _random_samples=_random_samples,
  442. )
  443. return fractional_max_pool2d_with_indices(
  444. input, kernel_size, output_size, output_ratio, return_indices, _random_samples
  445. )[0]
  446. fractional_max_pool2d = boolean_dispatch(
  447. arg_name="return_indices",
  448. arg_index=4,
  449. default=False,
  450. if_true=fractional_max_pool2d_with_indices,
  451. if_false=_fractional_max_pool2d,
  452. module_name=__name__,
  453. func_name="fractional_max_pool2d",
  454. )
  455. def fractional_max_pool3d_with_indices(
  456. input: Tensor,
  457. kernel_size: BroadcastingList3[int],
  458. output_size: Optional[BroadcastingList3[int]] = None,
  459. output_ratio: Optional[BroadcastingList3[float]] = None,
  460. return_indices: bool = False,
  461. _random_samples: Optional[Tensor] = None,
  462. ) -> tuple[Tensor, Tensor]: # noqa: D400
  463. r"""
  464. fractional_max_pool3d(input, kernel_size, output_size=None, output_ratio=None, return_indices=False, _random_samples=None)
  465. Applies 3D fractional max pooling over an input signal composed of several input planes.
  466. Fractional MaxPooling is described in detail in the paper `Fractional MaxPooling`_ by Ben Graham
  467. The max-pooling operation is applied in :math:`kT \times kH \times kW` regions by a stochastic
  468. step size determined by the target output size.
  469. The number of output features is equal to the number of input planes.
  470. Args:
  471. kernel_size: the size of the window to take a max over.
  472. Can be a single number :math:`k` (for a square kernel of :math:`k \times k \times k`)
  473. or a tuple `(kT, kH, kW)`
  474. output_size: the target output size of the form :math:`oT \times oH \times oW`.
  475. Can be a tuple `(oT, oH, oW)` or a single number :math:`oH` for a cubic output
  476. :math:`oH \times oH \times oH`
  477. output_ratio: If one wants to have an output size as a ratio of the input size, this option can be given.
  478. This has to be a number or tuple in the range (0, 1)
  479. return_indices: if ``True``, will return the indices along with the outputs.
  480. Useful to pass to :func:`~torch.nn.functional.max_unpool3d`.
  481. Shape:
  482. - Input: :math:`(N, C, T_{in}, H_{in}, W_{in})` or :math:`(C, T_{in}, H_{in}, W_{in})`.
  483. - Output: :math:`(N, C, T_{out}, H_{out}, W_{out})` or :math:`(C, T_{out}, H_{out}, W_{out})`, where
  484. :math:`(T_{out}, H_{out}, W_{out})=\text{output\_size}` or
  485. :math:`(T_{out}, H_{out}, W_{out})=\text{output\_ratio} \times (T_{in}, H_{in}, W_{in})`
  486. Examples::
  487. >>> input = torch.randn(20, 16, 50, 32, 16)
  488. >>> # pool of cubic window of size=3, and target output size 13x12x11
  489. >>> F.fractional_max_pool3d(input, 3, output_size=(13, 12, 11))
  490. >>> # pool of cubic window and target output size being half of input size
  491. >>> F.fractional_max_pool3d(input, 3, output_ratio=(0.5, 0.5, 0.5))
  492. .. _Fractional MaxPooling:
  493. http://arxiv.org/abs/1412.6071
  494. """
  495. if has_torch_function_variadic(input, _random_samples):
  496. return handle_torch_function(
  497. fractional_max_pool3d_with_indices,
  498. (input, _random_samples),
  499. input,
  500. kernel_size,
  501. output_size=output_size,
  502. output_ratio=output_ratio,
  503. return_indices=return_indices,
  504. _random_samples=_random_samples,
  505. )
  506. if output_size is None and output_ratio is None:
  507. raise ValueError(
  508. "fractional_max_pool3d requires specifying either an output_size or an output_ratio"
  509. )
  510. if output_size is None:
  511. if output_ratio is None:
  512. raise AssertionError("output_ratio is unexpectedly None")
  513. _output_ratio = _triple(output_ratio)
  514. output_size = [
  515. int(input.size(-3) * _output_ratio[0]),
  516. int(input.size(-2) * _output_ratio[1]),
  517. int(input.size(-1) * _output_ratio[2]),
  518. ]
  519. if _random_samples is None:
  520. n_batch = 1 if input.dim() == 4 else input.size(0)
  521. _random_samples = torch.rand(
  522. n_batch, input.size(-4), 3, dtype=input.dtype, device=input.device
  523. )
  524. return torch._C._nn.fractional_max_pool3d(
  525. input, kernel_size, output_size, _random_samples
  526. )
  527. def _fractional_max_pool3d(
  528. input: Tensor,
  529. kernel_size: BroadcastingList3[int],
  530. output_size: Optional[BroadcastingList3[int]] = None,
  531. output_ratio: Optional[BroadcastingList3[float]] = None,
  532. return_indices: bool = False,
  533. _random_samples: Optional[Tensor] = None,
  534. ) -> Tensor:
  535. if has_torch_function_variadic(input, _random_samples):
  536. return handle_torch_function(
  537. fractional_max_pool3d,
  538. (input, _random_samples),
  539. input,
  540. kernel_size,
  541. output_size=output_size,
  542. output_ratio=output_ratio,
  543. return_indices=return_indices,
  544. _random_samples=_random_samples,
  545. )
  546. return fractional_max_pool3d_with_indices(
  547. input, kernel_size, output_size, output_ratio, return_indices, _random_samples
  548. )[0]
  549. fractional_max_pool3d = boolean_dispatch(
  550. arg_name="return_indices",
  551. arg_index=4,
  552. default=False,
  553. if_true=fractional_max_pool3d_with_indices,
  554. if_false=_fractional_max_pool3d,
  555. module_name=__name__,
  556. func_name="fractional_max_pool3d",
  557. )
  558. def max_pool1d_with_indices(
  559. input: Tensor,
  560. kernel_size: BroadcastingList1[int],
  561. stride: Optional[BroadcastingList1[int]] = None,
  562. padding: BroadcastingList1[int] = 0,
  563. dilation: BroadcastingList1[int] = 1,
  564. ceil_mode: bool = False,
  565. return_indices: bool = False,
  566. ) -> tuple[Tensor, Tensor]: # noqa: D400
  567. r"""
  568. max_pool1d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False)
  569. Applies a 1D max pooling over an input signal composed of several input
  570. planes.
  571. .. note::
  572. The order of :attr:`ceil_mode` and :attr:`return_indices` is different from
  573. what seen in :class:`~torch.nn.MaxPool1d`, and will change in a future release.
  574. See :class:`~torch.nn.MaxPool1d` for details.
  575. Args:
  576. input: input tensor of shape :math:`(\text{minibatch} , \text{in\_channels} , iW)`, minibatch dim optional.
  577. kernel_size: the size of the window. Can be a single number or a
  578. tuple `(kW,)`
  579. stride: the stride of the window. Can be a single number or a tuple
  580. `(sW,)`. Default: :attr:`kernel_size`
  581. padding: Implicit negative infinity padding to be added on both sides, must be >= 0 and <= kernel_size / 2.
  582. dilation: The stride between elements within a sliding window, must be > 0.
  583. ceil_mode: If ``True``, will use `ceil` instead of `floor` to compute the output shape. This
  584. ensures that every element in the input tensor is covered by a sliding window.
  585. return_indices: If ``True``, will return the argmax along with the max values.
  586. Useful for :class:`torch.nn.functional.max_unpool1d` later
  587. """
  588. if has_torch_function_unary(input):
  589. return handle_torch_function(
  590. max_pool1d_with_indices,
  591. (input,),
  592. input,
  593. kernel_size,
  594. stride=stride,
  595. padding=padding,
  596. dilation=dilation,
  597. ceil_mode=ceil_mode,
  598. return_indices=return_indices,
  599. )
  600. if stride is None:
  601. stride = torch.jit.annotate(list[int], [])
  602. return torch.max_pool1d_with_indices(
  603. input, kernel_size, stride, padding, dilation, ceil_mode
  604. )
  605. def _max_pool1d(
  606. input: Tensor,
  607. kernel_size: BroadcastingList1[int],
  608. stride: Optional[BroadcastingList1[int]] = None,
  609. padding: BroadcastingList1[int] = 0,
  610. dilation: BroadcastingList1[int] = 1,
  611. ceil_mode: bool = False,
  612. return_indices: bool = False,
  613. ) -> Tensor:
  614. if has_torch_function_unary(input):
  615. return handle_torch_function(
  616. max_pool1d,
  617. (input,),
  618. input,
  619. kernel_size,
  620. stride=stride,
  621. padding=padding,
  622. dilation=dilation,
  623. ceil_mode=ceil_mode,
  624. return_indices=return_indices,
  625. )
  626. if stride is None:
  627. stride = torch.jit.annotate(list[int], [])
  628. return torch.max_pool1d(input, kernel_size, stride, padding, dilation, ceil_mode)
  629. max_pool1d = boolean_dispatch(
  630. arg_name="return_indices",
  631. arg_index=6,
  632. default=False,
  633. if_true=max_pool1d_with_indices,
  634. if_false=_max_pool1d,
  635. module_name=__name__,
  636. func_name="max_pool1d",
  637. )
  638. def max_pool2d_with_indices(
  639. input: Tensor,
  640. kernel_size: BroadcastingList2[int],
  641. stride: Optional[BroadcastingList2[int]] = None,
  642. padding: BroadcastingList2[int] = 0,
  643. dilation: BroadcastingList2[int] = 1,
  644. ceil_mode: bool = False,
  645. return_indices: bool = False,
  646. ) -> tuple[Tensor, Tensor]: # noqa: D400
  647. r"""
  648. max_pool2d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False)
  649. Applies a 2D max pooling over an input signal composed of several input
  650. planes.
  651. .. note::
  652. The order of :attr:`ceil_mode` and :attr:`return_indices` is different from
  653. what seen in :class:`~torch.nn.MaxPool2d`, and will change in a future release.
  654. See :class:`~torch.nn.MaxPool2d` for details.
  655. Args:
  656. input: input tensor :math:`(\text{minibatch} , \text{in\_channels} , iH , iW)`, minibatch dim optional.
  657. kernel_size: size of the pooling region. Can be a single number or a
  658. tuple `(kH, kW)`
  659. stride: stride of the pooling operation. Can be a single number or a
  660. tuple `(sH, sW)`. Default: :attr:`kernel_size`
  661. padding: Implicit negative infinity padding to be added on both sides, must be >= 0 and <= kernel_size / 2.
  662. dilation: The stride between elements within a sliding window, must be > 0.
  663. ceil_mode: If ``True``, will use `ceil` instead of `floor` to compute the output shape. This
  664. ensures that every element in the input tensor is covered by a sliding window.
  665. return_indices: If ``True``, will return the argmax along with the max values.
  666. Useful for :class:`torch.nn.functional.max_unpool2d` later
  667. """
  668. if has_torch_function_unary(input):
  669. return handle_torch_function(
  670. max_pool2d_with_indices,
  671. (input,),
  672. input,
  673. kernel_size,
  674. stride=stride,
  675. padding=padding,
  676. dilation=dilation,
  677. ceil_mode=ceil_mode,
  678. return_indices=return_indices,
  679. )
  680. if stride is None:
  681. stride = torch.jit.annotate(list[int], [])
  682. return torch._C._nn.max_pool2d_with_indices(
  683. input, kernel_size, stride, padding, dilation, ceil_mode
  684. )
  685. def _max_pool2d(
  686. input: Tensor,
  687. kernel_size: BroadcastingList2[int],
  688. stride: Optional[BroadcastingList2[int]] = None,
  689. padding: BroadcastingList2[int] = 0,
  690. dilation: BroadcastingList2[int] = 1,
  691. ceil_mode: bool = False,
  692. return_indices: bool = False,
  693. ) -> Tensor:
  694. if has_torch_function_unary(input):
  695. return handle_torch_function(
  696. max_pool2d,
  697. (input,),
  698. input,
  699. kernel_size,
  700. stride=stride,
  701. padding=padding,
  702. dilation=dilation,
  703. ceil_mode=ceil_mode,
  704. return_indices=return_indices,
  705. )
  706. if stride is None:
  707. stride = torch.jit.annotate(list[int], [])
  708. return torch.max_pool2d(input, kernel_size, stride, padding, dilation, ceil_mode)
  709. max_pool2d = boolean_dispatch(
  710. arg_name="return_indices",
  711. arg_index=6,
  712. default=False,
  713. if_true=max_pool2d_with_indices,
  714. if_false=_max_pool2d,
  715. module_name=__name__,
  716. func_name="max_pool2d",
  717. )
  718. def max_pool3d_with_indices(
  719. input: Tensor,
  720. kernel_size: BroadcastingList3[int],
  721. stride: Optional[BroadcastingList3[int]] = None,
  722. padding: BroadcastingList3[int] = 0,
  723. dilation: BroadcastingList3[int] = 1,
  724. ceil_mode: bool = False,
  725. return_indices: bool = False,
  726. ) -> tuple[Tensor, Tensor]: # noqa: D400
  727. r"""
  728. max_pool3d(input, kernel_size, stride=None, padding=0, dilation=1, ceil_mode=False, return_indices=False)
  729. Applies a 3D max pooling over an input signal composed of several input
  730. planes.
  731. .. note::
  732. The order of :attr:`ceil_mode` and :attr:`return_indices` is different from
  733. what seen in :class:`~torch.nn.MaxPool3d`, and will change in a future release.
  734. See :class:`~torch.nn.MaxPool3d` for details.
  735. Args:
  736. input: input tensor :math:`(\text{minibatch} , \text{in\_channels} , iD, iH , iW)`, minibatch dim optional.
  737. kernel_size: size of the pooling region. Can be a single number or a
  738. tuple `(kT, kH, kW)`
  739. stride: stride of the pooling operation. Can be a single number or a
  740. tuple `(sT, sH, sW)`. Default: :attr:`kernel_size`
  741. padding: Implicit negative infinity padding to be added on both sides, must be >= 0 and <= kernel_size / 2.
  742. dilation: The stride between elements within a sliding window, must be > 0.
  743. ceil_mode: If ``True``, will use `ceil` instead of `floor` to compute the output shape. This
  744. ensures that every element in the input tensor is covered by a sliding window.
  745. return_indices: If ``True``, will return the argmax along with the max values.
  746. Useful for :class:`torch.nn.functional.max_unpool3d` later
  747. """
  748. if has_torch_function_unary(input):
  749. return handle_torch_function(
  750. max_pool3d_with_indices,
  751. (input,),
  752. input,
  753. kernel_size,
  754. stride=stride,
  755. padding=padding,
  756. dilation=dilation,
  757. ceil_mode=ceil_mode,
  758. return_indices=return_indices,
  759. )
  760. if stride is None:
  761. stride = torch.jit.annotate(list[int], [])
  762. return torch._C._nn.max_pool3d_with_indices(
  763. input, kernel_size, stride, padding, dilation, ceil_mode
  764. )
  765. def _max_pool3d(
  766. input: Tensor,
  767. kernel_size: BroadcastingList3[int],
  768. stride: Optional[BroadcastingList3[int]] = None,
  769. padding: BroadcastingList3[int] = 0,
  770. dilation: BroadcastingList3[int] = 1,
  771. ceil_mode: bool = False,
  772. return_indices: bool = False,
  773. ) -> Tensor:
  774. if has_torch_function_unary(input):
  775. return handle_torch_function(
  776. max_pool3d,
  777. (input,),
  778. input,
  779. kernel_size,
  780. stride=stride,
  781. padding=padding,
  782. dilation=dilation,
  783. ceil_mode=ceil_mode,
  784. return_indices=return_indices,
  785. )
  786. if stride is None:
  787. stride = torch.jit.annotate(list[int], [])
  788. return torch.max_pool3d(input, kernel_size, stride, padding, dilation, ceil_mode)
  789. max_pool3d = boolean_dispatch(
  790. arg_name="return_indices",
  791. arg_index=6,
  792. default=False,
  793. if_true=max_pool3d_with_indices,
  794. if_false=_max_pool3d,
  795. module_name=__name__,
  796. func_name="max_pool3d",
  797. )
  798. def _unpool_output_size(
  799. input: Tensor,
  800. kernel_size: list[int],
  801. stride: list[int],
  802. padding: list[int],
  803. output_size: Optional[list[int]],
  804. ) -> list[int]:
  805. input_size = input.size()
  806. default_size = torch.jit.annotate(list[int], [])
  807. for d in range(len(kernel_size)):
  808. default_size.append(
  809. (input_size[-len(kernel_size) + d] - 1) * stride[d]
  810. + kernel_size[d]
  811. - 2 * padding[d]
  812. )
  813. if output_size is None:
  814. ret = default_size
  815. else:
  816. if len(output_size) == len(kernel_size) + 2:
  817. output_size = output_size[2:]
  818. if len(output_size) != len(kernel_size):
  819. raise ValueError(
  820. "output_size should be a sequence containing "
  821. f"{len(kernel_size)} or {len(kernel_size) + 2} elements, but it has a length of '{len(output_size)}'"
  822. )
  823. for d in range(len(kernel_size)):
  824. min_size = default_size[d] - stride[d]
  825. max_size = default_size[d] + stride[d]
  826. if not (min_size < output_size[d] < max_size):
  827. raise ValueError(
  828. f'invalid output_size "{output_size}" (dim {d} must be between {min_size} and {max_size})'
  829. )
  830. ret = output_size
  831. return ret
  832. def max_unpool1d(
  833. input: Tensor,
  834. indices: Tensor,
  835. kernel_size: BroadcastingList1[int],
  836. stride: Optional[BroadcastingList1[int]] = None,
  837. padding: BroadcastingList1[int] = 0,
  838. output_size: Optional[BroadcastingList1[int]] = None,
  839. ) -> Tensor:
  840. r"""Compute a partial inverse of :class:`MaxPool1d`.
  841. See :class:`~torch.nn.MaxUnpool1d` for details.
  842. """
  843. if has_torch_function_unary(input):
  844. return handle_torch_function(
  845. max_unpool1d,
  846. (input,),
  847. input,
  848. indices,
  849. kernel_size,
  850. stride=stride,
  851. padding=padding,
  852. output_size=output_size,
  853. )
  854. kernel_size = _single(kernel_size)
  855. if stride is not None:
  856. _stride = _single(stride)
  857. else:
  858. _stride = kernel_size
  859. padding = _single(padding)
  860. output_size = _unpool_output_size(input, kernel_size, _stride, padding, output_size)
  861. if isinstance(output_size, list):
  862. output_size = output_size + [1]
  863. else:
  864. output_size = output_size + (1,)
  865. return torch._C._nn.max_unpool2d(
  866. input.unsqueeze(-1), indices.unsqueeze(-1), output_size
  867. ).squeeze(-1)
  868. def max_unpool2d(
  869. input: Tensor,
  870. indices: Tensor,
  871. kernel_size: BroadcastingList2[int],
  872. stride: Optional[BroadcastingList2[int]] = None,
  873. padding: BroadcastingList2[int] = 0,
  874. output_size: Optional[BroadcastingList2[int]] = None,
  875. ) -> Tensor:
  876. r"""Compute a partial inverse of :class:`MaxPool2d`.
  877. See :class:`~torch.nn.MaxUnpool2d` for details.
  878. """
  879. if has_torch_function_unary(input):
  880. return handle_torch_function(
  881. max_unpool2d,
  882. (input,),
  883. input,
  884. indices,
  885. kernel_size,
  886. stride=stride,
  887. padding=padding,
  888. output_size=output_size,
  889. )
  890. kernel_size = _pair(kernel_size)
  891. if stride is not None:
  892. _stride = _pair(stride)
  893. else:
  894. _stride = kernel_size
  895. padding = _pair(padding)
  896. output_size = _unpool_output_size(input, kernel_size, _stride, padding, output_size)
  897. return torch._C._nn.max_unpool2d(input, indices, output_size)
  898. def max_unpool3d(
  899. input: Tensor,
  900. indices: Tensor,
  901. kernel_size: BroadcastingList3[int],
  902. stride: Optional[BroadcastingList3[int]] = None,
  903. padding: BroadcastingList3[int] = 0,
  904. output_size: Optional[BroadcastingList3[int]] = None,
  905. ) -> Tensor:
  906. r"""Compute a partial inverse of :class:`MaxPool3d`.
  907. See :class:`~torch.nn.MaxUnpool3d` for details.
  908. """
  909. if has_torch_function_unary(input):
  910. return handle_torch_function(
  911. max_unpool3d,
  912. (input,),
  913. input,
  914. indices,
  915. kernel_size,
  916. stride=stride,
  917. padding=padding,
  918. output_size=output_size,
  919. )
  920. kernel_size = _triple(kernel_size)
  921. if stride is not None:
  922. _stride = _triple(stride)
  923. else:
  924. _stride = kernel_size
  925. padding = _triple(padding)
  926. output_size = _unpool_output_size(input, kernel_size, _stride, padding, output_size)
  927. return torch._C._nn.max_unpool3d(input, indices, output_size, _stride, padding)
  928. def lp_pool3d(
  929. input: Tensor,
  930. norm_type: int | float,
  931. kernel_size: BroadcastingList3[int],
  932. stride: Optional[BroadcastingList3[int]] = None,
  933. ceil_mode: bool = False,
  934. ) -> Tensor:
  935. r"""
  936. Apply a 3D power-average pooling over an input signal composed of several input planes.
  937. If the sum of all inputs to the power of `p` is
  938. zero, the gradient is set to zero as well.
  939. When ``ceil_mode`` is ``True``, sliding windows may go off-bounds if they start within the left
  940. padding or the input. Sliding windows that would start in the right padded region are ignored.
  941. See :class:`~torch.nn.LPPool3d` for details.
  942. """
  943. if has_torch_function_unary(input):
  944. return handle_torch_function(
  945. lp_pool3d,
  946. (input,),
  947. input,
  948. norm_type,
  949. kernel_size,
  950. stride=stride,
  951. ceil_mode=ceil_mode,
  952. )
  953. kd, kw, kh = _triple(kernel_size)
  954. if stride is not None:
  955. out = avg_pool3d(input.pow(norm_type), kernel_size, stride, 0, ceil_mode)
  956. else:
  957. out = avg_pool3d(
  958. input.pow(norm_type), kernel_size, padding=0, ceil_mode=ceil_mode
  959. )
  960. return (
  961. (torch.sign(out) * relu(torch.abs(out))).mul(kd * kw * kh).pow(1.0 / norm_type)
  962. )
  963. def lp_pool2d(
  964. input: Tensor,
  965. norm_type: int | float,
  966. kernel_size: BroadcastingList2[int],
  967. stride: Optional[BroadcastingList2[int]] = None,
  968. ceil_mode: bool = False,
  969. ) -> Tensor:
  970. r"""
  971. Apply a 2D power-average pooling over an input signal composed of several input planes.
  972. If the sum of all inputs to the power of `p` is
  973. zero, the gradient is set to zero as well.
  974. When ``ceil_mode`` is ``True``, sliding windows may go off-bounds if they start within the left
  975. padding or the input. Sliding windows that would start in the right padded region are ignored.
  976. See :class:`~torch.nn.LPPool2d` for details.
  977. """
  978. if has_torch_function_unary(input):
  979. return handle_torch_function(
  980. lp_pool2d,
  981. (input,),
  982. input,
  983. norm_type,
  984. kernel_size,
  985. stride=stride,
  986. ceil_mode=ceil_mode,
  987. )
  988. kw, kh = _pair(kernel_size)
  989. if stride is not None:
  990. out = avg_pool2d(input.pow(norm_type), kernel_size, stride, 0, ceil_mode)
  991. else:
  992. out = avg_pool2d(
  993. input.pow(norm_type), kernel_size, padding=0, ceil_mode=ceil_mode
  994. )
  995. return (torch.sign(out) * relu(torch.abs(out))).mul(kw * kh).pow(1.0 / norm_type)
  996. def lp_pool1d(
  997. input: Tensor,
  998. norm_type: int | float,
  999. kernel_size: int,
  1000. stride: Optional[BroadcastingList1[int]] = None,
  1001. ceil_mode: bool = False,
  1002. ) -> Tensor:
  1003. r"""Apply a 1D power-average pooling over an input signal composed of several input planes.
  1004. If the sum of all inputs to the power of `p` is
  1005. zero, the gradient is set to zero as well.
  1006. When ``ceil_mode`` is ``True``, sliding windows may go off-bounds if they start within the left
  1007. padding or the input. Sliding windows that would start in the right padded region are ignored.
  1008. See :class:`~torch.nn.LPPool1d` for details.
  1009. """
  1010. if has_torch_function_unary(input):
  1011. return handle_torch_function(
  1012. lp_pool1d,
  1013. (input,),
  1014. input,
  1015. norm_type,
  1016. kernel_size,
  1017. stride=stride,
  1018. ceil_mode=ceil_mode,
  1019. )
  1020. if stride is not None:
  1021. out = avg_pool1d(input.pow(norm_type), kernel_size, stride, 0, ceil_mode)
  1022. else:
  1023. out = avg_pool1d(
  1024. input.pow(norm_type), kernel_size, padding=0, ceil_mode=ceil_mode
  1025. )
  1026. return (
  1027. (torch.sign(out) * relu(torch.abs(out))).mul(kernel_size).pow(1.0 / norm_type)
  1028. )
  1029. def adaptive_max_pool1d_with_indices(
  1030. input: Tensor,
  1031. output_size: BroadcastingList1[int],
  1032. return_indices: bool = False,
  1033. ) -> tuple[Tensor, Tensor]: # noqa: D400
  1034. r"""
  1035. adaptive_max_pool1d(input, output_size, return_indices=False)
  1036. Applies a 1D adaptive max pooling over an input signal composed of
  1037. several input planes.
  1038. See :class:`~torch.nn.AdaptiveMaxPool1d` for details and output shape.
  1039. Args:
  1040. output_size: the target output size (single integer)
  1041. return_indices: whether to return pooling indices. Default: ``False``
  1042. """
  1043. if has_torch_function_unary(input):
  1044. return handle_torch_function(
  1045. adaptive_max_pool1d_with_indices,
  1046. (input,),
  1047. input,
  1048. output_size,
  1049. return_indices=return_indices,
  1050. )
  1051. return torch.adaptive_max_pool1d(input, output_size)
  1052. def _adaptive_max_pool1d(
  1053. input: Tensor,
  1054. output_size: BroadcastingList1[int],
  1055. return_indices: bool = False,
  1056. ) -> Tensor:
  1057. if has_torch_function_unary(input):
  1058. return handle_torch_function(
  1059. adaptive_max_pool1d,
  1060. (input,),
  1061. input,
  1062. output_size,
  1063. return_indices=return_indices,
  1064. )
  1065. return adaptive_max_pool1d_with_indices(input, output_size)[0]
  1066. adaptive_max_pool1d = boolean_dispatch(
  1067. arg_name="return_indices",
  1068. arg_index=2,
  1069. default=False,
  1070. if_true=adaptive_max_pool1d_with_indices,
  1071. if_false=_adaptive_max_pool1d,
  1072. module_name=__name__,
  1073. func_name="adaptive_max_pool1d",
  1074. )
  1075. def adaptive_max_pool2d_with_indices(
  1076. input: Tensor,
  1077. output_size: BroadcastingList2[int],
  1078. return_indices: bool = False,
  1079. ) -> tuple[Tensor, Tensor]: # noqa: D400
  1080. r"""adaptive_max_pool2d(input, output_size, return_indices=False)
  1081. Applies a 2D adaptive max pooling over an input signal composed of
  1082. several input planes.
  1083. See :class:`~torch.nn.AdaptiveMaxPool2d` for details and output shape.
  1084. Args:
  1085. output_size: the target output size (single integer or
  1086. double-integer tuple)
  1087. return_indices: whether to return pooling indices. Default: ``False``
  1088. """
  1089. if has_torch_function_unary(input):
  1090. return handle_torch_function(
  1091. adaptive_max_pool2d_with_indices,
  1092. (input,),
  1093. input,
  1094. output_size,
  1095. return_indices=return_indices,
  1096. )
  1097. # pyrefly: ignore [bad-argument-type]
  1098. output_size = _list_with_default(output_size, input.size())
  1099. return torch._C._nn.adaptive_max_pool2d(input, output_size)
  1100. def _adaptive_max_pool2d(
  1101. input: Tensor,
  1102. output_size: BroadcastingList2[int],
  1103. return_indices: bool = False,
  1104. ) -> Tensor:
  1105. if has_torch_function_unary(input):
  1106. return handle_torch_function(
  1107. adaptive_max_pool2d,
  1108. (input,),
  1109. input,
  1110. output_size,
  1111. return_indices=return_indices,
  1112. )
  1113. return adaptive_max_pool2d_with_indices(input, output_size)[0]
  1114. adaptive_max_pool2d = boolean_dispatch(
  1115. arg_name="return_indices",
  1116. arg_index=2,
  1117. default=False,
  1118. if_true=adaptive_max_pool2d_with_indices,
  1119. if_false=_adaptive_max_pool2d,
  1120. module_name=__name__,
  1121. func_name="adaptive_max_pool2d",
  1122. )
  1123. def adaptive_max_pool3d_with_indices(
  1124. input: Tensor,
  1125. output_size: BroadcastingList3[int],
  1126. return_indices: bool = False,
  1127. ) -> tuple[Tensor, Tensor]: # noqa: D400
  1128. r"""
  1129. adaptive_max_pool3d(input, output_size, return_indices=False)
  1130. Applies a 3D adaptive max pooling over an input signal composed of
  1131. several input planes.
  1132. See :class:`~torch.nn.AdaptiveMaxPool3d` for details and output shape.
  1133. Args:
  1134. output_size: the target output size (single integer or
  1135. triple-integer tuple)
  1136. return_indices: whether to return pooling indices. Default: ``False``
  1137. """
  1138. if has_torch_function_unary(input):
  1139. return handle_torch_function(
  1140. adaptive_max_pool3d_with_indices,
  1141. (input,),
  1142. input,
  1143. output_size,
  1144. return_indices=return_indices,
  1145. )
  1146. # pyrefly: ignore [bad-argument-type]
  1147. output_size = _list_with_default(output_size, input.size())
  1148. return torch._C._nn.adaptive_max_pool3d(input, output_size)
  1149. def _adaptive_max_pool3d(
  1150. input: Tensor,
  1151. output_size: BroadcastingList3[int],
  1152. return_indices: bool = False,
  1153. ) -> Tensor:
  1154. if has_torch_function_unary(input):
  1155. return handle_torch_function(
  1156. adaptive_max_pool3d,
  1157. (input,),
  1158. input,
  1159. output_size,
  1160. return_indices=return_indices,
  1161. )
  1162. return adaptive_max_pool3d_with_indices(input, output_size)[0]
  1163. adaptive_max_pool3d = boolean_dispatch(
  1164. arg_name="return_indices",
  1165. arg_index=2,
  1166. default=False,
  1167. if_true=adaptive_max_pool3d_with_indices,
  1168. if_false=_adaptive_max_pool3d,
  1169. module_name=__name__,
  1170. func_name="adaptive_max_pool3d",
  1171. )
  1172. adaptive_avg_pool1d = _add_docstr(
  1173. torch.adaptive_avg_pool1d,
  1174. r"""
  1175. adaptive_avg_pool1d(input, output_size) -> Tensor
  1176. Applies a 1D adaptive average pooling over an input signal composed of
  1177. several input planes.
  1178. See :class:`~torch.nn.AdaptiveAvgPool1d` for details and output shape.
  1179. Args:
  1180. output_size: the target output size (single integer)
  1181. """,
  1182. )
  1183. def adaptive_avg_pool2d(input: Tensor, output_size: BroadcastingList2[int]) -> Tensor:
  1184. r"""Apply a 2D adaptive average pooling over an input signal composed of several input planes.
  1185. See :class:`~torch.nn.AdaptiveAvgPool2d` for details and output shape.
  1186. Args:
  1187. output_size: the target output size (single integer or
  1188. double-integer tuple)
  1189. """
  1190. if has_torch_function_unary(input):
  1191. return handle_torch_function(adaptive_avg_pool2d, (input,), input, output_size)
  1192. # pyrefly: ignore [bad-argument-type]
  1193. _output_size = _list_with_default(output_size, input.size())
  1194. return torch._C._nn.adaptive_avg_pool2d(input, _output_size)
  1195. def adaptive_avg_pool3d(input: Tensor, output_size: BroadcastingList3[int]) -> Tensor:
  1196. r"""Apply a 3D adaptive average pooling over an input signal composed of several input planes.
  1197. See :class:`~torch.nn.AdaptiveAvgPool3d` for details and output shape.
  1198. Args:
  1199. output_size: the target output size (single integer or
  1200. triple-integer tuple)
  1201. """
  1202. if has_torch_function_unary(input):
  1203. return handle_torch_function(adaptive_avg_pool3d, (input,), input, output_size)
  1204. # pyrefly: ignore [bad-argument-type]
  1205. _output_size = _list_with_default(output_size, input.size())
  1206. return torch._C._nn.adaptive_avg_pool3d(input, _output_size)
  1207. # Activation functions
  1208. def dropout(
  1209. input: Tensor,
  1210. p: float = 0.5,
  1211. training: bool = True,
  1212. inplace: bool = False,
  1213. ) -> Tensor:
  1214. r"""During training, randomly zeroes some elements of the input tensor with probability :attr:`p`.
  1215. Uses samples from a Bernoulli distribution.
  1216. See :class:`~torch.nn.Dropout` for details.
  1217. Args:
  1218. p: probability of an element to be zeroed. Default: 0.5
  1219. training: apply dropout if is ``True``. Default: ``True``
  1220. inplace: If set to ``True``, will do this operation in-place. Default: ``False``
  1221. """
  1222. if has_torch_function_unary(input):
  1223. return handle_torch_function(
  1224. dropout, (input,), input, p=p, training=training, inplace=inplace
  1225. )
  1226. if p < 0.0 or p > 1.0:
  1227. raise ValueError(f"dropout probability has to be between 0 and 1, but got {p}")
  1228. return (
  1229. _VF.dropout_(input, p, training) if inplace else _VF.dropout(input, p, training)
  1230. )
  1231. def alpha_dropout(
  1232. input: Tensor,
  1233. p: float = 0.5,
  1234. training: bool = False,
  1235. inplace: bool = False,
  1236. ) -> Tensor:
  1237. r"""Apply alpha dropout to the input.
  1238. See :class:`~torch.nn.AlphaDropout` for details.
  1239. """
  1240. if has_torch_function_unary(input):
  1241. return handle_torch_function(
  1242. alpha_dropout, (input,), input, p=p, training=training, inplace=inplace
  1243. )
  1244. if p < 0.0 or p > 1.0:
  1245. raise ValueError(f"dropout probability has to be between 0 and 1, but got {p}")
  1246. return (
  1247. _VF.alpha_dropout_(input, p, training)
  1248. if inplace
  1249. else _VF.alpha_dropout(input, p, training)
  1250. )
  1251. def dropout1d(
  1252. input: Tensor,
  1253. p: float = 0.5,
  1254. training: bool = True,
  1255. inplace: bool = False,
  1256. ) -> Tensor:
  1257. r"""Randomly zero out entire channels (a channel is a 1D feature map).
  1258. For example, the :math:`j`-th channel of the :math:`i`-th sample in the
  1259. batched input is a 1D tensor :math:`\text{input}[i, j]` of the input tensor.
  1260. Each channel will be zeroed out independently on every forward call with
  1261. probability :attr:`p` using samples from a Bernoulli distribution.
  1262. See :class:`~torch.nn.Dropout1d` for details.
  1263. Args:
  1264. p: probability of a channel to be zeroed. Default: 0.5
  1265. training: apply dropout if is ``True``. Default: ``True``
  1266. inplace: If set to ``True``, will do this operation in-place. Default: ``False``
  1267. """
  1268. if has_torch_function_unary(input):
  1269. return handle_torch_function(
  1270. dropout1d, (input,), input, p=p, training=training, inplace=inplace
  1271. )
  1272. if p < 0.0 or p > 1.0:
  1273. raise ValueError(f"dropout probability has to be between 0 and 1, but got {p}")
  1274. inp_dim = input.dim()
  1275. if inp_dim not in (2, 3):
  1276. raise RuntimeError(
  1277. f"dropout1d: Expected 2D or 3D input, but received a {inp_dim}D input. "
  1278. "Note that dropout1d exists to provide channel-wise dropout on inputs with 1 "
  1279. "spatial dimension, a channel dimension, and an optional batch dimension "
  1280. "(i.e. 2D or 3D inputs)."
  1281. )
  1282. is_batched = inp_dim == 3
  1283. if not is_batched:
  1284. input = input.unsqueeze_(0) if inplace else input.unsqueeze(0)
  1285. result = (
  1286. _VF.feature_dropout_(input, p, training)
  1287. if inplace
  1288. else _VF.feature_dropout(input, p, training)
  1289. )
  1290. if not is_batched:
  1291. result = result.squeeze_(0) if inplace else result.squeeze(0)
  1292. return result
  1293. def dropout2d(
  1294. input: Tensor,
  1295. p: float = 0.5,
  1296. training: bool = True,
  1297. inplace: bool = False,
  1298. ) -> Tensor:
  1299. r"""Randomly zero out entire channels (a channel is a 2D feature map).
  1300. For example, the :math:`j`-th channel of the :math:`i`-th sample in the
  1301. batched input is a 2D tensor :math:`\text{input}[i, j]` of the input tensor.
  1302. Each channel will be zeroed out independently on every forward call with
  1303. probability :attr:`p` using samples from a Bernoulli distribution.
  1304. See :class:`~torch.nn.Dropout2d` for details.
  1305. Args:
  1306. p: probability of a channel to be zeroed. Default: 0.5
  1307. training: apply dropout if is ``True``. Default: ``True``
  1308. inplace: If set to ``True``, will do this operation in-place. Default: ``False``
  1309. """
  1310. if has_torch_function_unary(input):
  1311. return handle_torch_function(
  1312. dropout2d, (input,), input, p=p, training=training, inplace=inplace
  1313. )
  1314. if p < 0.0 or p > 1.0:
  1315. raise ValueError(f"dropout probability has to be between 0 and 1, but got {p}")
  1316. inp_dim = input.dim()
  1317. if inp_dim not in (3, 4):
  1318. warn_msg = (
  1319. f"dropout2d: Received a {inp_dim}-D input to dropout2d, which is deprecated "
  1320. "and will result in an error in a future release. To retain the behavior "
  1321. "and silence this warning, please use dropout instead. Note that dropout2d "
  1322. "exists to provide channel-wise dropout on inputs with 2 spatial dimensions, "
  1323. "a channel dimension, and an optional batch dimension (i.e. 3D or 4D inputs)."
  1324. )
  1325. warnings.warn(warn_msg, stacklevel=2)
  1326. # TODO: Properly support no-batch-dim inputs. For now, these are NOT supported; passing
  1327. # a 3D input will perform dropout1d behavior instead. This was done historically and the
  1328. # behavior is maintained here for now.
  1329. # See https://github.com/pytorch/pytorch/issues/77081
  1330. if inp_dim == 3:
  1331. warnings.warn(
  1332. "dropout2d: Received a 3D input to dropout2d and assuming that channel-wise "
  1333. "1D dropout behavior is desired - input is interpreted as shape (N, C, L), where C "
  1334. "is the channel dim. This behavior will change in a future release to interpret the "
  1335. "input as one without a batch dimension, i.e. shape (C, H, W). To maintain the 1D "
  1336. "channel-wise dropout behavior, please switch to using dropout1d instead.",
  1337. stacklevel=2,
  1338. )
  1339. result = (
  1340. _VF.feature_dropout_(input, p, training)
  1341. if inplace
  1342. else _VF.feature_dropout(input, p, training)
  1343. )
  1344. return result
  1345. def dropout3d(
  1346. input: Tensor,
  1347. p: float = 0.5,
  1348. training: bool = True,
  1349. inplace: bool = False,
  1350. ) -> Tensor:
  1351. r"""Randomly zero out entire channels (a channel is a 3D feature map).
  1352. For example, the :math:`j`-th channel of the :math:`i`-th sample in the
  1353. batched input is a 3D tensor :math:`\text{input}[i, j]` of the input tensor.
  1354. Each channel will be zeroed out independently on every forward call with
  1355. probability :attr:`p` using samples from a Bernoulli distribution.
  1356. See :class:`~torch.nn.Dropout3d` for details.
  1357. Args:
  1358. p: probability of a channel to be zeroed. Default: 0.5
  1359. training: apply dropout if is ``True``. Default: ``True``
  1360. inplace: If set to ``True``, will do this operation in-place. Default: ``False``
  1361. """
  1362. if has_torch_function_unary(input):
  1363. return handle_torch_function(
  1364. dropout3d, (input,), input, p=p, training=training, inplace=inplace
  1365. )
  1366. if p < 0.0 or p > 1.0:
  1367. raise ValueError(f"dropout probability has to be between 0 and 1, but got {p}")
  1368. inp_dim = input.dim()
  1369. if inp_dim not in (4, 5):
  1370. warn_msg = (
  1371. f"dropout3d: Received a {inp_dim}-D input to dropout3d, which is deprecated "
  1372. "and will result in an error in a future release. To retain the behavior "
  1373. "and silence this warning, please use dropout instead. Note that dropout3d "
  1374. "exists to provide channel-wise dropout on inputs with 3 spatial dimensions, "
  1375. "a channel dimension, and an optional batch dimension (i.e. 4D or 5D inputs)."
  1376. )
  1377. warnings.warn(warn_msg, stacklevel=2)
  1378. is_batched = inp_dim == 5
  1379. if not is_batched:
  1380. input = input.unsqueeze_(0) if inplace else input.unsqueeze(0)
  1381. result = (
  1382. _VF.feature_dropout_(input, p, training)
  1383. if inplace
  1384. else _VF.feature_dropout(input, p, training)
  1385. )
  1386. if not is_batched:
  1387. result = result.squeeze_(0) if inplace else result.squeeze(0)
  1388. return result
  1389. def feature_alpha_dropout(
  1390. input: Tensor,
  1391. p: float = 0.5,
  1392. training: bool = False,
  1393. inplace: bool = False,
  1394. ) -> Tensor:
  1395. r"""Randomly masks out entire channels (a channel is a feature map).
  1396. For example, the :math:`j`-th channel of the :math:`i`-th sample in the batch input
  1397. is a tensor :math:`\text{input}[i, j]` of the input tensor. Instead of
  1398. setting activations to zero, as in regular Dropout, the activations are set
  1399. to the negative saturation value of the SELU activation function.
  1400. Each element will be masked independently on every forward call with
  1401. probability :attr:`p` using samples from a Bernoulli distribution.
  1402. The elements to be masked are randomized on every forward call, and scaled
  1403. and shifted to maintain zero mean and unit variance.
  1404. See :class:`~torch.nn.FeatureAlphaDropout` for details.
  1405. Args:
  1406. p: dropout probability of a channel to be zeroed. Default: 0.5
  1407. training: apply dropout if is ``True``. Default: ``True``
  1408. inplace: If set to ``True``, will do this operation in-place. Default: ``False``
  1409. """
  1410. if has_torch_function_unary(input):
  1411. return handle_torch_function(
  1412. feature_alpha_dropout,
  1413. (input,),
  1414. input,
  1415. p=p,
  1416. training=training,
  1417. inplace=inplace,
  1418. )
  1419. if p < 0.0 or p > 1.0:
  1420. raise ValueError(f"dropout probability has to be between 0 and 1, but got {p}")
  1421. return (
  1422. _VF.feature_alpha_dropout_(input, p, training)
  1423. if inplace
  1424. else _VF.feature_alpha_dropout(input, p, training)
  1425. )
  1426. def _threshold(
  1427. input: Tensor,
  1428. threshold: float,
  1429. value: float,
  1430. inplace: bool = False,
  1431. ) -> Tensor:
  1432. r"""Apply a threshold to each element of the input Tensor.
  1433. See :class:`~torch.nn.Threshold` for more details.
  1434. """
  1435. if has_torch_function_unary(input):
  1436. return handle_torch_function(
  1437. _threshold, (input,), input, threshold, value, inplace=inplace
  1438. )
  1439. if inplace:
  1440. result = _VF.threshold_(input, threshold, value)
  1441. else:
  1442. result = _VF.threshold(input, threshold, value)
  1443. return result
  1444. # We define this function as _threshold because it takes an argument
  1445. # named threshold, which clobbers the recursive reference to the
  1446. # function needed for __torch_function__ support
  1447. threshold = _threshold
  1448. threshold_ = _add_docstr(
  1449. _VF.threshold_,
  1450. r"""
  1451. threshold_(input, threshold, value) -> Tensor
  1452. In-place version of :func:`~threshold`.
  1453. """,
  1454. )
  1455. def relu(input: Tensor, inplace: bool = False) -> Tensor: # noqa: D400,D402
  1456. r"""relu(input, inplace=False) -> Tensor
  1457. Applies the rectified linear unit function element-wise. See
  1458. :class:`~torch.nn.ReLU` for more details.
  1459. """
  1460. if has_torch_function_unary(input):
  1461. return handle_torch_function(relu, (input,), input, inplace=inplace)
  1462. if inplace:
  1463. result = torch.relu_(input)
  1464. else:
  1465. result = torch.relu(input)
  1466. return result
  1467. relu_ = _add_docstr(
  1468. torch.relu_,
  1469. r"""
  1470. relu_(input) -> Tensor
  1471. In-place version of :func:`~relu`.
  1472. """,
  1473. )
  1474. def glu(input: Tensor, dim: int = -1) -> Tensor: # noqa: D400,D402
  1475. r"""
  1476. glu(input, dim=-1) -> Tensor
  1477. The gated linear unit. Computes:
  1478. .. math ::
  1479. \text{GLU}(a, b) = a \otimes \sigma(b)
  1480. where `input` is split in half along `dim` to form `a` and `b`, :math:`\sigma`
  1481. is the sigmoid function and :math:`\otimes` is the element-wise product between matrices.
  1482. See `Language Modeling with Gated Convolutional Networks <https://arxiv.org/abs/1612.08083>`_.
  1483. Args:
  1484. input (Tensor): input tensor
  1485. dim (int): dimension on which to split the input. Default: -1
  1486. """
  1487. if has_torch_function_unary(input):
  1488. return handle_torch_function(glu, (input,), input, dim=dim)
  1489. if input.dim() == 0:
  1490. raise RuntimeError(
  1491. "glu does not support scalars because halving size must be even"
  1492. )
  1493. return torch._C._nn.glu(input, dim)
  1494. def hardtanh(
  1495. input: Tensor,
  1496. min_val: float = -1.0,
  1497. max_val: float = 1.0,
  1498. inplace: bool = False,
  1499. ) -> Tensor: # noqa: D400,D402
  1500. r"""
  1501. hardtanh(input, min_val=-1., max_val=1., inplace=False) -> Tensor
  1502. Applies the HardTanh function element-wise. See :class:`~torch.nn.Hardtanh` for more
  1503. details.
  1504. """
  1505. if has_torch_function_unary(input):
  1506. return handle_torch_function(
  1507. hardtanh, (input,), input, min_val=min_val, max_val=max_val, inplace=inplace
  1508. )
  1509. if min_val > max_val:
  1510. raise ValueError("min_val cannot be greater than max_val")
  1511. if inplace:
  1512. result = torch._C._nn.hardtanh_(input, min_val, max_val)
  1513. else:
  1514. result = torch._C._nn.hardtanh(input, min_val, max_val)
  1515. return result
  1516. hardtanh_ = _add_docstr(
  1517. torch._C._nn.hardtanh_,
  1518. r"""
  1519. hardtanh_(input, min_val=-1., max_val=1.) -> Tensor
  1520. In-place version of :func:`~hardtanh`.
  1521. """,
  1522. )
  1523. def relu6(input: Tensor, inplace: bool = False) -> Tensor: # noqa: D400,D402
  1524. r"""relu6(input, inplace=False) -> Tensor
  1525. Applies the element-wise function :math:`\text{ReLU6}(x) = \min(\max(0,x), 6)`.
  1526. See :class:`~torch.nn.ReLU6` for more details.
  1527. """
  1528. if has_torch_function_unary(input):
  1529. return handle_torch_function(relu6, (input,), input, inplace=inplace)
  1530. if inplace:
  1531. result = torch._C._nn.relu6_(input)
  1532. else:
  1533. result = torch._C._nn.relu6(input)
  1534. return result
  1535. def elu(input: Tensor, alpha: float = 1.0, inplace: bool = False) -> Tensor:
  1536. r"""Apply the Exponential Linear Unit (ELU) function element-wise.
  1537. See :class:`~torch.nn.ELU` for more details.
  1538. """
  1539. if has_torch_function_unary(input):
  1540. return handle_torch_function(elu, (input,), input, alpha=alpha, inplace=inplace)
  1541. if inplace:
  1542. result = torch._C._nn.elu_(input, alpha)
  1543. else:
  1544. result = torch._C._nn.elu(input, alpha)
  1545. return result
  1546. elu_ = _add_docstr(
  1547. torch._C._nn.elu_,
  1548. r"""
  1549. elu_(input, alpha=1.) -> Tensor
  1550. In-place version of :func:`~elu`.
  1551. """,
  1552. )
  1553. def selu(input: Tensor, inplace: bool = False) -> Tensor: # noqa: D400,D402
  1554. r"""selu(input, inplace=False) -> Tensor
  1555. Applies element-wise,
  1556. :math:`\text{SELU}(x) = scale * (\max(0,x) + \min(0, \alpha * (\exp(x) - 1)))`,
  1557. with :math:`\alpha=1.6732632423543772848170429916717` and
  1558. :math:`scale=1.0507009873554804934193349852946`.
  1559. See :class:`~torch.nn.SELU` for more details.
  1560. """
  1561. if has_torch_function_unary(input):
  1562. return handle_torch_function(selu, (input,), input, inplace=inplace)
  1563. if inplace:
  1564. result = torch.selu_(input)
  1565. else:
  1566. result = torch.selu(input)
  1567. return result
  1568. selu_ = _add_docstr(
  1569. torch.selu_,
  1570. r"""
  1571. selu_(input) -> Tensor
  1572. In-place version of :func:`~selu`.
  1573. """,
  1574. )
  1575. def celu(
  1576. input: Tensor,
  1577. alpha: float = 1.0,
  1578. inplace: bool = False,
  1579. ) -> Tensor: # noqa: D400,D402
  1580. r"""celu(input, alpha=1., inplace=False) -> Tensor
  1581. Applies element-wise,
  1582. :math:`\text{CELU}(x) = \max(0,x) + \min(0, \alpha * (\exp(x/\alpha) - 1))`.
  1583. See :class:`~torch.nn.CELU` for more details.
  1584. """
  1585. if has_torch_function_unary(input):
  1586. return handle_torch_function(
  1587. celu, (input,), input, alpha=alpha, inplace=inplace
  1588. )
  1589. if inplace:
  1590. result = torch.celu_(input, alpha)
  1591. else:
  1592. result = torch.celu(input, alpha)
  1593. return result
  1594. celu_ = _add_docstr(
  1595. torch.celu_,
  1596. r"""
  1597. celu_(input, alpha=1.) -> Tensor
  1598. In-place version of :func:`~celu`.
  1599. """,
  1600. )
  1601. def leaky_relu(
  1602. input: Tensor,
  1603. negative_slope: float = 0.01,
  1604. inplace: bool = False,
  1605. ) -> Tensor: # noqa: D400,D402
  1606. r"""
  1607. leaky_relu(input, negative_slope=0.01, inplace=False) -> Tensor
  1608. Applies element-wise,
  1609. :math:`\text{LeakyReLU}(x) = \max(0, x) + \text{negative\_slope} * \min(0, x)`
  1610. See :class:`~torch.nn.LeakyReLU` for more details.
  1611. """
  1612. if has_torch_function_unary(input):
  1613. return handle_torch_function(
  1614. leaky_relu, (input,), input, negative_slope=negative_slope, inplace=inplace
  1615. )
  1616. if inplace:
  1617. result = torch._C._nn.leaky_relu_(input, negative_slope)
  1618. else:
  1619. result = torch._C._nn.leaky_relu(input, negative_slope)
  1620. return result
  1621. leaky_relu_ = _add_docstr(
  1622. torch._C._nn.leaky_relu_,
  1623. r"""
  1624. leaky_relu_(input, negative_slope=0.01) -> Tensor
  1625. In-place version of :func:`~leaky_relu`.
  1626. """,
  1627. )
  1628. prelu = _add_docstr(
  1629. torch.prelu,
  1630. r"""prelu(input, weight) -> Tensor
  1631. Applies element-wise the function
  1632. :math:`\text{PReLU}(x) = \max(0,x) + \text{weight} * \min(0,x)` where weight is a
  1633. learnable parameter.
  1634. .. note::
  1635. `weight` is expected to be a scalar or 1-D tensor. If `weight` is 1-D,
  1636. its size must match the number of input channels, determined by
  1637. `input.size(1)` when `input.dim() >= 2`, otherwise 1.
  1638. In the 1-D case, note that when `input` has dim > 2, `weight` can be expanded
  1639. to the shape of `input` in a way that is not possible using normal
  1640. :ref:`broadcasting semantics<broadcasting-semantics>`.
  1641. See :class:`~torch.nn.PReLU` for more details.
  1642. """,
  1643. )
  1644. def rrelu(
  1645. input: Tensor,
  1646. lower: float = 1.0 / 8,
  1647. upper: float = 1.0 / 3,
  1648. training: bool = False,
  1649. inplace: bool = False,
  1650. ) -> Tensor: # noqa: D400,D402
  1651. r"""rrelu(input, lower=1./8, upper=1./3, training=False, inplace=False) -> Tensor
  1652. Randomized leaky ReLU.
  1653. See :class:`~torch.nn.RReLU` for more details.
  1654. """
  1655. if has_torch_function_unary(input):
  1656. return handle_torch_function(
  1657. rrelu,
  1658. (input,),
  1659. input,
  1660. lower=lower,
  1661. upper=upper,
  1662. training=training,
  1663. inplace=inplace,
  1664. )
  1665. if inplace:
  1666. result = torch.rrelu_(input, lower, upper, training)
  1667. else:
  1668. result = torch.rrelu(input, lower, upper, training)
  1669. return result
  1670. rrelu_ = _add_docstr(
  1671. torch.rrelu_,
  1672. r"""
  1673. rrelu_(input, lower=1./8, upper=1./3, training=False) -> Tensor
  1674. In-place version of :func:`~rrelu`.
  1675. """,
  1676. )
  1677. logsigmoid = _add_docstr(
  1678. torch._C._nn.log_sigmoid,
  1679. r"""
  1680. logsigmoid(input) -> Tensor
  1681. Applies element-wise :math:`\text{LogSigmoid}(x_i) = \log \left(\frac{1}{1 + \exp(-x_i)}\right)`
  1682. See :class:`~torch.nn.LogSigmoid` for more details.
  1683. """,
  1684. )
  1685. gelu = _add_docstr(
  1686. torch._C._nn.gelu,
  1687. r"""
  1688. gelu(input, approximate = 'none') -> Tensor
  1689. When the approximate argument is 'none', it applies element-wise the function
  1690. :math:`\text{GELU}(x) = x * \Phi(x)`
  1691. where :math:`\Phi(x)` is the Cumulative Distribution Function for Gaussian Distribution.
  1692. When the approximate argument is 'tanh', Gelu is estimated with
  1693. .. math::
  1694. \text{GELU}(x) = 0.5 * x * (1 + \text{Tanh}(\sqrt{2 / \pi} * (x + 0.044715 * x^3)))
  1695. See `Gaussian Error Linear Units (GELUs) <https://arxiv.org/abs/1606.08415>`_.
  1696. """,
  1697. )
  1698. hardshrink = _add_docstr(
  1699. torch.hardshrink,
  1700. r"""
  1701. hardshrink(input, lambd=0.5) -> Tensor
  1702. Applies the hard shrinkage function element-wise
  1703. See :class:`~torch.nn.Hardshrink` for more details.
  1704. """,
  1705. )
  1706. def tanhshrink(input): # noqa: D400,D402
  1707. r"""tanhshrink(input) -> Tensor
  1708. Applies element-wise, :math:`\text{Tanhshrink}(x) = x - \text{Tanh}(x)`
  1709. See :class:`~torch.nn.Tanhshrink` for more details.
  1710. """
  1711. if has_torch_function_unary(input):
  1712. return handle_torch_function(tanhshrink, (input,), input)
  1713. return input - input.tanh()
  1714. def softsign(input): # noqa: D400,D402
  1715. r"""softsign(input) -> Tensor
  1716. Applies element-wise, the function :math:`\text{SoftSign}(x) = \frac{x}{1 + |x|}`
  1717. See :class:`~torch.nn.Softsign` for more details.
  1718. """
  1719. if has_torch_function_unary(input):
  1720. return handle_torch_function(softsign, (input,), input)
  1721. return input / (input.abs() + 1)
  1722. softplus = _add_docstr(
  1723. torch._C._nn.softplus,
  1724. r"""
  1725. softplus(input, beta=1, threshold=20) -> Tensor
  1726. Applies element-wise, the function :math:`\text{Softplus}(x) = \frac{1}{\beta} * \log(1 + \exp(\beta * x))`.
  1727. For numerical stability the implementation reverts to the linear function
  1728. when :math:`input \times \beta > threshold`.
  1729. See :class:`~torch.nn.Softplus` for more details.
  1730. """,
  1731. )
  1732. def _get_softmax_dim(name: str, ndim: int, stacklevel: int) -> int:
  1733. warnings.warn(
  1734. f"Implicit dimension choice for {name} has been deprecated. "
  1735. "Change the call to include dim=X as an argument.",
  1736. stacklevel=stacklevel,
  1737. )
  1738. if ndim == 0 or ndim == 1 or ndim == 3:
  1739. ret = 0
  1740. else:
  1741. ret = 1
  1742. return ret
  1743. def softmin(
  1744. input: Tensor,
  1745. dim: Optional[int] = None,
  1746. _stacklevel: int = 3,
  1747. dtype: Optional[DType] = None,
  1748. ) -> Tensor:
  1749. r"""Apply a softmin function.
  1750. Note that :math:`\text{Softmin}(x) = \text{Softmax}(-x)`. See softmax definition for mathematical formula.
  1751. See :class:`~torch.nn.Softmin` for more details.
  1752. Args:
  1753. input (Tensor): input
  1754. dim (int): A dimension along which softmin will be computed (so every slice
  1755. along dim will sum to 1).
  1756. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
  1757. If specified, the input tensor is casted to :attr:`dtype` before the operation
  1758. is performed. This is useful for preventing data type overflows. Default: None.
  1759. """
  1760. if has_torch_function_unary(input):
  1761. return handle_torch_function(
  1762. softmin, (input,), input, dim=dim, _stacklevel=_stacklevel, dtype=dtype
  1763. )
  1764. if dim is None:
  1765. dim = _get_softmax_dim("softmin", input.dim(), _stacklevel)
  1766. if dtype is None:
  1767. ret = (-input).softmax(dim)
  1768. else:
  1769. ret = (-input).softmax(dim, dtype=dtype)
  1770. return ret
  1771. def softmax(
  1772. input: Tensor,
  1773. dim: Optional[int] = None,
  1774. _stacklevel: int = 3,
  1775. dtype: Optional[DType] = None,
  1776. ) -> Tensor:
  1777. r"""Apply a softmax function.
  1778. Softmax is defined as:
  1779. :math:`\text{Softmax}(x_{i}) = \frac{\exp(x_i)}{\sum_j \exp(x_j)}`
  1780. It is applied to all slices along dim, and will re-scale them so that the elements
  1781. lie in the range `[0, 1]` and sum to 1.
  1782. See :class:`~torch.nn.Softmax` for more details.
  1783. Args:
  1784. input (Tensor): input
  1785. dim (int): A dimension along which softmax will be computed.
  1786. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
  1787. If specified, the input tensor is casted to :attr:`dtype` before the operation
  1788. is performed. This is useful for preventing data type overflows. Default: None.
  1789. .. note::
  1790. This function doesn't work directly with NLLLoss,
  1791. which expects the Log to be computed between the Softmax and itself.
  1792. Use log_softmax instead (it's faster and has better numerical properties).
  1793. """
  1794. if has_torch_function_unary(input):
  1795. return handle_torch_function(
  1796. softmax, (input,), input, dim=dim, _stacklevel=_stacklevel, dtype=dtype
  1797. )
  1798. if dim is None:
  1799. dim = _get_softmax_dim("softmax", input.dim(), _stacklevel)
  1800. if dtype is None:
  1801. ret = input.softmax(dim)
  1802. else:
  1803. ret = input.softmax(dim, dtype=dtype)
  1804. return ret
  1805. def gumbel_softmax(
  1806. logits: Tensor,
  1807. tau: float = 1,
  1808. hard: bool = False,
  1809. eps: float = 1e-10,
  1810. dim: int = -1,
  1811. ) -> Tensor:
  1812. r"""
  1813. Sample from the Gumbel-Softmax distribution (`Link 1`_ `Link 2`_) and optionally discretize.
  1814. Args:
  1815. logits: `[..., num_features]` unnormalized log probabilities
  1816. tau: non-negative scalar temperature
  1817. hard: if ``True``, the returned samples will be discretized as one-hot vectors,
  1818. but will be differentiated as if it is the soft sample in autograd
  1819. dim (int): A dimension along which softmax will be computed. Default: -1.
  1820. Returns:
  1821. Sampled tensor of same shape as `logits` from the Gumbel-Softmax distribution.
  1822. If ``hard=True``, the returned samples will be one-hot, otherwise they will
  1823. be probability distributions that sum to 1 across `dim`.
  1824. .. note::
  1825. This function is here for legacy reasons, may be removed from nn.Functional in the future.
  1826. .. note::
  1827. The main trick for `hard` is to do `y_hard - y_soft.detach() + y_soft`
  1828. It achieves two things:
  1829. - makes the output value exactly one-hot
  1830. (since we add then subtract y_soft value)
  1831. - makes the gradient equal to y_soft gradient
  1832. (since we strip all other gradients)
  1833. Examples::
  1834. >>> logits = torch.randn(20, 32)
  1835. >>> # Sample soft categorical using reparametrization trick:
  1836. >>> F.gumbel_softmax(logits, tau=1, hard=False)
  1837. >>> # Sample hard categorical using "Straight-through" trick:
  1838. >>> F.gumbel_softmax(logits, tau=1, hard=True)
  1839. .. _Link 1:
  1840. https://arxiv.org/abs/1611.00712
  1841. .. _Link 2:
  1842. https://arxiv.org/abs/1611.01144
  1843. """
  1844. if has_torch_function_unary(logits):
  1845. return handle_torch_function(
  1846. gumbel_softmax, (logits,), logits, tau=tau, hard=hard, eps=eps, dim=dim
  1847. )
  1848. if eps != 1e-10:
  1849. warnings.warn("`eps` parameter is deprecated and has no effect.", stacklevel=2)
  1850. gumbels = (
  1851. -torch.empty_like(logits, memory_format=torch.legacy_contiguous_format)
  1852. .exponential_()
  1853. .log()
  1854. ) # ~Gumbel(0,1)
  1855. gumbels = (logits + gumbels) / tau # ~Gumbel(logits,tau)
  1856. y_soft = gumbels.softmax(dim)
  1857. if hard:
  1858. # Straight through.
  1859. index = y_soft.max(dim, keepdim=True)[1]
  1860. y_hard = torch.zeros_like(
  1861. logits, memory_format=torch.legacy_contiguous_format
  1862. ).scatter_(dim, index, 1.0)
  1863. ret = y_hard - y_soft.detach() + y_soft
  1864. else:
  1865. # Reparameterization trick.
  1866. ret = y_soft
  1867. return ret
  1868. def log_softmax(
  1869. input: Tensor,
  1870. dim: Optional[int] = None,
  1871. _stacklevel: int = 3,
  1872. dtype: Optional[DType] = None,
  1873. ) -> Tensor:
  1874. r"""Apply a softmax followed by a logarithm.
  1875. While mathematically equivalent to log(softmax(x)), doing these two
  1876. operations separately is slower and numerically unstable. This function
  1877. uses an alternative formulation to compute the output and gradient correctly.
  1878. See :class:`~torch.nn.LogSoftmax` for more details.
  1879. Args:
  1880. input (Tensor): input
  1881. dim (int): A dimension along which log_softmax will be computed.
  1882. dtype (:class:`torch.dtype`, optional): the desired data type of returned tensor.
  1883. If specified, the input tensor is cast to :attr:`dtype` before the operation
  1884. is performed. This is useful for preventing data type overflows. Default: None.
  1885. """
  1886. if has_torch_function_unary(input):
  1887. return handle_torch_function(
  1888. log_softmax, (input,), input, dim=dim, _stacklevel=_stacklevel, dtype=dtype
  1889. )
  1890. if dim is None:
  1891. dim = _get_softmax_dim("log_softmax", input.dim(), _stacklevel)
  1892. if dtype is None:
  1893. ret = input.log_softmax(dim)
  1894. else:
  1895. ret = input.log_softmax(dim, dtype=dtype)
  1896. return ret
  1897. softshrink = _add_docstr(
  1898. torch._C._nn.softshrink,
  1899. r"""
  1900. softshrink(input, lambd=0.5) -> Tensor
  1901. Applies the soft shrinkage function elementwise
  1902. See :class:`~torch.nn.Softshrink` for more details.
  1903. """,
  1904. )
  1905. def tanh(input): # noqa: D400,D402
  1906. r"""tanh(input) -> Tensor
  1907. Applies element-wise,
  1908. :math:`\text{Tanh}(x) = \tanh(x) = \frac{\exp(x) - \exp(-x)}{\exp(x) + \exp(-x)}`
  1909. See :class:`~torch.nn.Tanh` for more details.
  1910. """
  1911. return input.tanh()
  1912. def sigmoid(input): # noqa: D400,D402
  1913. r"""sigmoid(input) -> Tensor
  1914. Applies the element-wise function :math:`\text{Sigmoid}(x) = \frac{1}{1 + \exp(-x)}`
  1915. See :class:`~torch.nn.Sigmoid` for more details.
  1916. """
  1917. return input.sigmoid()
  1918. def hardsigmoid(input: Tensor, inplace: bool = False) -> Tensor:
  1919. r"""Apply the Hardsigmoid function element-wise.
  1920. .. math::
  1921. \text{Hardsigmoid}(x) = \begin{cases}
  1922. 0 & \text{if~} x \le -3, \\
  1923. 1 & \text{if~} x \ge +3, \\
  1924. x / 6 + 1 / 2 & \text{otherwise}
  1925. \end{cases}
  1926. Args:
  1927. inplace: If set to ``True``, will do this operation in-place. Default: ``False``
  1928. See :class:`~torch.nn.Hardsigmoid` for more details.
  1929. """
  1930. if has_torch_function_unary(input):
  1931. return handle_torch_function(hardsigmoid, (input,), input, inplace=inplace)
  1932. if inplace:
  1933. return torch._C._nn.hardsigmoid_(input)
  1934. return torch._C._nn.hardsigmoid(input)
  1935. linear = _add_docstr(
  1936. torch._C._nn.linear,
  1937. r"""
  1938. linear(input, weight, bias=None) -> Tensor
  1939. Applies a linear transformation to the incoming data: :math:`y = xA^T + b`.
  1940. This operation supports 2-D :attr:`weight` with :ref:`sparse layout<sparse-docs>`
  1941. {sparse_beta_warning}
  1942. This operator supports :ref:`TensorFloat32<tf32_on_ampere>`.
  1943. Shape:
  1944. - Input: :math:`(*, in\_features)` where `*` means any number of
  1945. additional dimensions, including none
  1946. - Weight: :math:`(out\_features, in\_features)` or :math:`(in\_features)`
  1947. - Bias: :math:`(out\_features)` or :math:`()`
  1948. - Output: :math:`(*, out\_features)` or :math:`(*)`, based on the shape of the weight
  1949. """.format(**sparse_support_notes),
  1950. )
  1951. bilinear = _add_docstr(
  1952. torch.bilinear,
  1953. r"""
  1954. bilinear(input1, input2, weight, bias=None) -> Tensor
  1955. Applies a bilinear transformation to the incoming data:
  1956. :math:`y = x_1^T A x_2 + b`
  1957. Shape:
  1958. - input1: :math:`(N, *, H_{in1})` where :math:`H_{in1}=\text{in1\_features}`
  1959. and :math:`*` means any number of additional dimensions.
  1960. All but the last dimension of the inputs should be the same.
  1961. - input2: :math:`(N, *, H_{in2})` where :math:`H_{in2}=\text{in2\_features}`
  1962. - weight: :math:`(\text{out\_features}, \text{in1\_features},
  1963. \text{in2\_features})`
  1964. - bias: :math:`(\text{out\_features})`
  1965. - output: :math:`(N, *, H_{out})` where :math:`H_{out}=\text{out\_features}`
  1966. and all but the last dimension are the same shape as the input.
  1967. """,
  1968. )
  1969. def silu(input: Tensor, inplace: bool = False) -> Tensor:
  1970. r"""Apply the Sigmoid Linear Unit (SiLU) function, element-wise.
  1971. The SiLU function is also known as the swish function.
  1972. .. math::
  1973. \text{silu}(x) = x * \sigma(x), \text{where } \sigma(x) \text{ is the logistic sigmoid.}
  1974. .. note::
  1975. See `Gaussian Error Linear Units (GELUs) <https://arxiv.org/abs/1606.08415>`_
  1976. where the SiLU (Sigmoid Linear Unit) was originally coined, and see
  1977. `Sigmoid-Weighted Linear Units for Neural Network Function Approximation
  1978. in Reinforcement Learning <https://arxiv.org/abs/1702.03118>`_ and `Swish:
  1979. a Self-Gated Activation Function <https://arxiv.org/abs/1710.05941v1>`_
  1980. where the SiLU was experimented with later.
  1981. See :class:`~torch.nn.SiLU` for more details.
  1982. """
  1983. if has_torch_function_unary(input):
  1984. return handle_torch_function(silu, (input,), input, inplace=inplace)
  1985. if inplace:
  1986. return torch._C._nn.silu_(input)
  1987. return torch._C._nn.silu(input)
  1988. def mish(input: Tensor, inplace: bool = False) -> Tensor:
  1989. r"""Apply the Mish function, element-wise.
  1990. Mish: A Self Regularized Non-Monotonic Neural Activation Function.
  1991. .. math::
  1992. \text{Mish}(x) = x * \text{Tanh}(\text{Softplus}(x))
  1993. .. note::
  1994. See `Mish: A Self Regularized Non-Monotonic Neural Activation Function <https://arxiv.org/abs/1908.08681>`_
  1995. See :class:`~torch.nn.Mish` for more details.
  1996. """
  1997. if has_torch_function_unary(input):
  1998. return handle_torch_function(mish, (input,), input, inplace=inplace)
  1999. if inplace:
  2000. return torch._C._nn.mish_(input)
  2001. return torch._C._nn.mish(input)
  2002. def hardswish(input: Tensor, inplace: bool = False) -> Tensor:
  2003. r"""Apply hardswish function, element-wise.
  2004. Follows implementation as described in the paper:
  2005. `Searching for MobileNetV3`_.
  2006. .. math::
  2007. \text{Hardswish}(x) = \begin{cases}
  2008. 0 & \text{if~} x \le -3, \\
  2009. x & \text{if~} x \ge +3, \\
  2010. x \cdot (x + 3) /6 & \text{otherwise}
  2011. \end{cases}
  2012. See :class:`~torch.nn.Hardswish` for more details.
  2013. .. _`Searching for MobileNetV3`:
  2014. https://arxiv.org/abs/1905.02244
  2015. """
  2016. if has_torch_function_unary(input):
  2017. return handle_torch_function(hardswish, (input,), input, inplace=inplace)
  2018. if inplace:
  2019. return torch._C._nn.hardswish_(input)
  2020. return torch._C._nn.hardswish(input)
  2021. def _no_grad_embedding_renorm_(
  2022. weight: Tensor,
  2023. input: Tensor,
  2024. max_norm: float,
  2025. norm_type: float,
  2026. # pyrefly: ignore [bad-return]
  2027. ) -> tuple[Tensor, Tensor]:
  2028. torch.embedding_renorm_(weight.detach(), input, max_norm, norm_type)
  2029. def embedding(
  2030. input: Tensor,
  2031. weight: Tensor,
  2032. padding_idx: Optional[int] = None,
  2033. max_norm: Optional[float] = None,
  2034. norm_type: float = 2.0,
  2035. scale_grad_by_freq: bool = False,
  2036. sparse: bool = False,
  2037. ) -> Tensor:
  2038. r"""Generate a simple lookup table that looks up embeddings in a fixed dictionary and size.
  2039. This module is often used to retrieve word embeddings using indices.
  2040. The input to the module is a list of indices, and the embedding matrix,
  2041. and the output is the corresponding word embeddings.
  2042. See :class:`torch.nn.Embedding` for more details.
  2043. .. note::
  2044. Note that the analytical gradients of this function with respect to
  2045. entries in :attr:`weight` at the row specified by :attr:`padding_idx`
  2046. are expected to differ from the numerical ones.
  2047. .. note::
  2048. Note that `:class:`torch.nn.Embedding` differs from this function in
  2049. that it initializes the row of :attr:`weight` specified by
  2050. :attr:`padding_idx` to all zeros on construction.
  2051. Args:
  2052. input (LongTensor): Tensor containing indices into the embedding matrix
  2053. weight (Tensor): The embedding matrix (must be 2-D) with number of rows equal to the maximum possible index + 1,
  2054. and number of columns equal to the embedding size
  2055. padding_idx (int, optional): If specified, the entries at :attr:`padding_idx` do not contribute to the gradient;
  2056. therefore, the embedding vector at :attr:`padding_idx` is not updated during training,
  2057. i.e. it remains as a fixed "pad".
  2058. max_norm (float, optional): If given, each embedding vector with norm larger than :attr:`max_norm`
  2059. is renormalized to have norm :attr:`max_norm`.
  2060. Note: this will modify :attr:`weight` in-place.
  2061. norm_type (float, optional): The p of the p-norm to compute for the :attr:`max_norm` option. Default ``2``.
  2062. scale_grad_by_freq (bool, optional): If given, this will scale gradients by the inverse of frequency of
  2063. the words in the mini-batch. Default ``False``.
  2064. sparse (bool, optional): If ``True``, gradient w.r.t. :attr:`weight` will be a sparse tensor. See Notes under
  2065. :class:`torch.nn.Embedding` for more details regarding sparse gradients.
  2066. Shape:
  2067. - Input: LongTensor of arbitrary shape containing the indices to extract
  2068. - Weight: Embedding matrix of floating point type with shape `(V, embedding_dim)`,
  2069. where V = maximum index + 1 and embedding_dim = the embedding size
  2070. - Output: `(*, embedding_dim)`, where `*` is the input shape
  2071. Examples::
  2072. >>> # a batch of 2 samples of 4 indices each
  2073. >>> input = torch.tensor([[1, 2, 4, 5], [4, 3, 2, 9]])
  2074. >>> # an embedding matrix containing 10 tensors of size 3
  2075. >>> embedding_matrix = torch.rand(10, 3)
  2076. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  2077. >>> F.embedding(input, embedding_matrix)
  2078. tensor([[[ 0.8490, 0.9625, 0.6753],
  2079. [ 0.9666, 0.7761, 0.6108],
  2080. [ 0.6246, 0.9751, 0.3618],
  2081. [ 0.4161, 0.2419, 0.7383]],
  2082. [[ 0.6246, 0.9751, 0.3618],
  2083. [ 0.0237, 0.7794, 0.0528],
  2084. [ 0.9666, 0.7761, 0.6108],
  2085. [ 0.3385, 0.8612, 0.1867]]])
  2086. >>> # example with padding_idx
  2087. >>> weights = torch.rand(10, 3)
  2088. >>> weights[0, :].zero_()
  2089. >>> embedding_matrix = weights
  2090. >>> input = torch.tensor([[0, 2, 0, 5]])
  2091. >>> F.embedding(input, embedding_matrix, padding_idx=0)
  2092. tensor([[[ 0.0000, 0.0000, 0.0000],
  2093. [ 0.5609, 0.5384, 0.8720],
  2094. [ 0.0000, 0.0000, 0.0000],
  2095. [ 0.6262, 0.2438, 0.7471]]])
  2096. """
  2097. if has_torch_function_variadic(input, weight):
  2098. return handle_torch_function(
  2099. embedding,
  2100. (input, weight),
  2101. input,
  2102. weight,
  2103. padding_idx=padding_idx,
  2104. max_norm=max_norm,
  2105. norm_type=norm_type,
  2106. scale_grad_by_freq=scale_grad_by_freq,
  2107. sparse=sparse,
  2108. )
  2109. if padding_idx is not None:
  2110. if padding_idx > 0:
  2111. if padding_idx >= weight.size(0):
  2112. raise AssertionError("Padding_idx must be within num_embeddings")
  2113. elif padding_idx < 0:
  2114. if padding_idx < -weight.size(0):
  2115. raise AssertionError("Padding_idx must be within num_embeddings")
  2116. padding_idx = weight.size(0) + padding_idx
  2117. else:
  2118. padding_idx = -1
  2119. if max_norm is not None:
  2120. # Note [embedding_renorm contiguous]
  2121. # `embedding_renorm_` will call .contiguous() on input anyways, so we
  2122. # call it here and take advantage of the improved locality in the
  2123. # `embedding` call below too.
  2124. input = input.contiguous()
  2125. # Note [embedding_renorm set_grad_enabled]
  2126. # XXX: equivalent to
  2127. # with torch.no_grad():
  2128. # torch.embedding_renorm_
  2129. # remove once script supports set_grad_enabled
  2130. _no_grad_embedding_renorm_(weight, input, max_norm, norm_type)
  2131. return torch.embedding(weight, input, padding_idx, scale_grad_by_freq, sparse)
  2132. def embedding_bag(
  2133. input: Tensor,
  2134. weight: Tensor,
  2135. offsets: Optional[Tensor] = None,
  2136. max_norm: Optional[float] = None,
  2137. norm_type: float = 2,
  2138. scale_grad_by_freq: bool = False,
  2139. mode: str = "mean",
  2140. sparse: bool = False,
  2141. per_sample_weights: Optional[Tensor] = None,
  2142. include_last_offset: bool = False,
  2143. padding_idx: Optional[int] = None,
  2144. ) -> Tensor:
  2145. r"""Compute sums, means or maxes of `bags` of embeddings.
  2146. Calculation is done without instantiating the intermediate embeddings.
  2147. See :class:`torch.nn.EmbeddingBag` for more details.
  2148. Note:
  2149. {backward_reproducibility_note}
  2150. Args:
  2151. input (LongTensor): Tensor containing bags of indices into the embedding matrix
  2152. weight (Tensor): The embedding matrix with number of rows equal to the maximum possible index + 1,
  2153. and number of columns equal to the embedding size
  2154. offsets (LongTensor, optional): Only used when :attr:`input` is 1D. :attr:`offsets` determines
  2155. the starting index position of each bag (sequence) in :attr:`input`.
  2156. max_norm (float, optional): If given, each embedding vector with norm larger than :attr:`max_norm`
  2157. is renormalized to have norm :attr:`max_norm`.
  2158. Note: this will modify :attr:`weight` in-place.
  2159. norm_type (float, optional): The ``p`` in the ``p``-norm to compute for the :attr:`max_norm` option.
  2160. Default ``2``.
  2161. scale_grad_by_freq (bool, optional): if given, this will scale gradients by the inverse of frequency of
  2162. the words in the mini-batch. Default ``False``.
  2163. Note: this option is not supported when ``mode="max"``.
  2164. mode (str, optional): ``"sum"``, ``"mean"`` or ``"max"``. Specifies the way to reduce the bag.
  2165. Default: ``"mean"``
  2166. sparse (bool, optional): if ``True``, gradient w.r.t. :attr:`weight` will be a sparse tensor. See Notes under
  2167. :class:`torch.nn.Embedding` for more details regarding sparse gradients.
  2168. Note: this option is not supported when ``mode="max"``.
  2169. per_sample_weights (Tensor, optional): a tensor of float / double weights, or None
  2170. to indicate all weights should be taken to be 1. If specified, :attr:`per_sample_weights`
  2171. must have exactly the same shape as input and is treated as having the same
  2172. :attr:`offsets`, if those are not None.
  2173. include_last_offset (bool, optional): if ``True``, the size of offsets is equal to the number of bags + 1.
  2174. The last element is the size of the input, or the ending index position
  2175. of the last bag (sequence). This matches the CSR format. Ignored when
  2176. input is 2D. Default ``False``.
  2177. padding_idx (int, optional): If specified, the entries at :attr:`padding_idx` do not contribute to the
  2178. gradient; therefore, the embedding vector at :attr:`padding_idx` is not updated
  2179. during training, i.e. it remains as a fixed "pad". Note that the embedding
  2180. vector at :attr:`padding_idx` is excluded from the reduction.
  2181. Shape:
  2182. - :attr:`input` (LongTensor) and :attr:`offsets` (LongTensor, optional)
  2183. - If :attr:`input` is 2D of shape `(B, N)`, it will be treated as ``B`` bags (sequences)
  2184. each of fixed length ``N``, and this will return ``B`` values aggregated in a way
  2185. depending on the :attr:`mode`. :attr:`offsets` is ignored and required to be ``None`` in this case.
  2186. - If :attr:`input` is 1D of shape `(N)`, it will be treated as a concatenation of
  2187. multiple bags (sequences). :attr:`offsets` is required to be a 1D tensor containing
  2188. the starting index positions of each bag in :attr:`input`. Therefore, for :attr:`offsets`
  2189. of shape `(B)`, :attr:`input` will be viewed as having ``B`` bags.
  2190. Empty bags (i.e., having 0-length) will have returned vectors filled by zeros.
  2191. - :attr:`weight` (Tensor): the learnable weights of the module of shape `(num_embeddings, embedding_dim)`
  2192. - :attr:`per_sample_weights` (Tensor, optional). Has the same shape as :attr:`input`.
  2193. - :attr:`output`: aggregated embedding values of shape `(B, embedding_dim)`
  2194. Examples::
  2195. >>> # an Embedding module containing 10 tensors of size 3
  2196. >>> embedding_matrix = torch.rand(10, 3)
  2197. >>> # a batch of 2 samples of 4 indices each
  2198. >>> input = torch.tensor([1, 2, 4, 5, 4, 3, 2, 9])
  2199. >>> offsets = torch.tensor([0, 4])
  2200. >>> # xdoctest: +IGNORE_WANT("non-deterministic")
  2201. >>> F.embedding_bag(input, embedding_matrix, offsets)
  2202. tensor([[ 0.3397, 0.3552, 0.5545],
  2203. [ 0.5893, 0.4386, 0.5882]])
  2204. >>> # example with padding_idx
  2205. >>> embedding_matrix = torch.rand(10, 3)
  2206. >>> input = torch.tensor([2, 2, 2, 2, 4, 3, 2, 9])
  2207. >>> offsets = torch.tensor([0, 4])
  2208. >>> F.embedding_bag(input, embedding_matrix, offsets, padding_idx=2, mode='sum')
  2209. tensor([[ 0.0000, 0.0000, 0.0000],
  2210. [-0.7082, 3.2145, -2.6251]])
  2211. """
  2212. if has_torch_function_variadic(input, weight, offsets, per_sample_weights):
  2213. return handle_torch_function(
  2214. embedding_bag,
  2215. (input, weight, offsets, per_sample_weights),
  2216. input,
  2217. weight,
  2218. offsets=offsets,
  2219. max_norm=max_norm,
  2220. norm_type=norm_type,
  2221. scale_grad_by_freq=scale_grad_by_freq,
  2222. mode=mode,
  2223. sparse=sparse,
  2224. per_sample_weights=per_sample_weights,
  2225. include_last_offset=include_last_offset,
  2226. padding_idx=padding_idx,
  2227. )
  2228. # Check for backward compatibility.
  2229. # Used to be embedding_bag(weight, input, ...)
  2230. # Now is embedding_bag(input, weight, ...)
  2231. if weight.dtype == torch.long and input.is_floating_point():
  2232. warnings.warn(
  2233. "Argument order of nn.functional.embedding_bag was changed. "
  2234. "Usage `embedding_bag(weight, input, ...)` is deprecated, "
  2235. "and should now be `embedding_bag(input, weight, ...)`.",
  2236. stacklevel=2,
  2237. )
  2238. weight, input = input, weight
  2239. if per_sample_weights is not None and input.size() != per_sample_weights.size():
  2240. raise ValueError(
  2241. f"embedding_bag: If per_sample_weights ({per_sample_weights.shape}) is not None, "
  2242. f"then it must have the same shape as the input ({input.shape})"
  2243. )
  2244. if not weight.dim() == 2:
  2245. raise ValueError(
  2246. f"weight has to be a 2D Tensor, but got Tensor of dimension {weight.dim()}"
  2247. )
  2248. if not torch.jit.is_scripting() and input.dim() == 2 and input.is_nested:
  2249. include_last_offset = True
  2250. # pyrefly: ignore [missing-attribute]
  2251. offsets = input.offsets()
  2252. input = input.values().reshape(-1)
  2253. if per_sample_weights is not None:
  2254. if not per_sample_weights.is_nested:
  2255. raise ValueError(
  2256. "If input is nested, then per_sample_weights must be nested if specified"
  2257. )
  2258. per_sample_weights = per_sample_weights.values().reshape(-1)
  2259. elif input.dim() == 2:
  2260. if offsets is not None:
  2261. type_str = "<unknown>"
  2262. # TODO: Remove this once script supports type() calls
  2263. if not torch.jit.is_scripting():
  2264. type_str = str(type(offsets))
  2265. raise ValueError(
  2266. "if input is 2D, then offsets has to be None"
  2267. ", as input is treated is a mini-batch of"
  2268. " fixed length sequences. However, found "
  2269. f"offsets of type {type_str}"
  2270. )
  2271. offsets = torch.arange(
  2272. 0, input.numel(), input.size(1), dtype=input.dtype, device=input.device
  2273. )
  2274. include_last_offset = False
  2275. input = input.reshape(-1)
  2276. if per_sample_weights is not None:
  2277. per_sample_weights = per_sample_weights.reshape(-1)
  2278. elif input.dim() == 1:
  2279. if offsets is None:
  2280. raise ValueError("offsets has to be a 1D Tensor but got None")
  2281. if offsets.dim() != 1:
  2282. raise ValueError("offsets has to be a 1D Tensor")
  2283. else:
  2284. raise ValueError(
  2285. f"input has to be 1D or 2D Tensor, but got Tensor of dimension {input.dim()}"
  2286. )
  2287. if mode == "sum":
  2288. mode_enum = 0
  2289. elif mode == "mean":
  2290. mode_enum = 1
  2291. elif mode == "max":
  2292. mode_enum = 2
  2293. if scale_grad_by_freq:
  2294. raise ValueError(
  2295. "max mode does not support scaling the gradient by the frequency"
  2296. )
  2297. if sparse:
  2298. raise ValueError("max mode does not support sparse weights")
  2299. else:
  2300. raise ValueError("mode has to be one of sum, mean or max")
  2301. if max_norm is not None:
  2302. # XXX: equivalent to
  2303. # with torch.no_grad():
  2304. # torch.nembedding_renorm_
  2305. # remove once script supports set_grad_enabled
  2306. _no_grad_embedding_renorm_(weight, input, max_norm, norm_type)
  2307. if per_sample_weights is not None and mode != "sum":
  2308. raise NotImplementedError(
  2309. "embedding_bag: per_sample_weights was not None. "
  2310. "per_sample_weights is only supported for mode='sum' "
  2311. f"(got mode='{mode}'). Please open a feature request on GitHub."
  2312. )
  2313. ret, _, _, _ = torch.embedding_bag(
  2314. weight,
  2315. input,
  2316. offsets,
  2317. scale_grad_by_freq,
  2318. mode_enum,
  2319. sparse,
  2320. per_sample_weights,
  2321. include_last_offset,
  2322. padding_idx,
  2323. )
  2324. return ret
  2325. if embedding_bag.__doc__:
  2326. embedding_bag.__doc__ = embedding_bag.__doc__.format(**reproducibility_notes)
  2327. def _verify_batch_size(size: list[int]) -> None:
  2328. # XXX: JIT script does not support the reduce from functools, and mul op is a
  2329. # builtin, which cannot be used as a value to a func yet, so rewrite this size
  2330. # check to a simple equivalent for loop
  2331. #
  2332. # TODO: make use of reduce like below when JIT is ready with the missing features:
  2333. # from operator import mul
  2334. # from functools import reduce
  2335. #
  2336. # if reduce(mul, size[2:], size[0]) == 1
  2337. size_prods = size[0]
  2338. for i in range(len(size) - 2):
  2339. size_prods *= size[i + 2]
  2340. if size_prods == 1:
  2341. raise ValueError(
  2342. f"Expected more than 1 value per channel when training, got input size {size}"
  2343. )
  2344. def batch_norm(
  2345. input: Tensor,
  2346. running_mean: Optional[Tensor],
  2347. running_var: Optional[Tensor],
  2348. weight: Optional[Tensor] = None,
  2349. bias: Optional[Tensor] = None,
  2350. training: bool = False,
  2351. momentum: float = 0.1,
  2352. eps: float = 1e-5,
  2353. ) -> Tensor:
  2354. r"""Apply Batch Normalization for each channel across a batch of data.
  2355. See :class:`~torch.nn.BatchNorm1d`, :class:`~torch.nn.BatchNorm2d`,
  2356. :class:`~torch.nn.BatchNorm3d` for details.
  2357. """
  2358. if has_torch_function_variadic(input, running_mean, running_var, weight, bias):
  2359. return handle_torch_function(
  2360. batch_norm,
  2361. (input, running_mean, running_var, weight, bias),
  2362. input,
  2363. running_mean,
  2364. running_var,
  2365. weight=weight,
  2366. bias=bias,
  2367. training=training,
  2368. momentum=momentum,
  2369. eps=eps,
  2370. )
  2371. if training:
  2372. # pyrefly: ignore [bad-argument-type]
  2373. _verify_batch_size(input.size())
  2374. if eps <= 0.0:
  2375. raise ValueError(f"batch_norm eps must be positive, but got {eps}")
  2376. return torch.batch_norm(
  2377. input,
  2378. weight,
  2379. bias,
  2380. running_mean,
  2381. running_var,
  2382. training,
  2383. momentum,
  2384. eps,
  2385. torch.backends.cudnn.enabled,
  2386. )
  2387. def _verify_spatial_size(size: list[int]) -> None:
  2388. # Verify that there is > 1 spatial element for instance norm calculation.
  2389. size_prods = 1
  2390. for i in range(2, len(size)):
  2391. size_prods *= size[i]
  2392. if size_prods == 1:
  2393. raise ValueError(
  2394. f"Expected more than 1 spatial element when training, got input size {size}"
  2395. )
  2396. def instance_norm(
  2397. input: Tensor,
  2398. running_mean: Optional[Tensor] = None,
  2399. running_var: Optional[Tensor] = None,
  2400. weight: Optional[Tensor] = None,
  2401. bias: Optional[Tensor] = None,
  2402. use_input_stats: bool = True,
  2403. momentum: float = 0.1,
  2404. eps: float = 1e-5,
  2405. ) -> Tensor:
  2406. r"""Apply Instance Normalization independently for each channel in every data sample within a batch.
  2407. See :class:`~torch.nn.InstanceNorm1d`, :class:`~torch.nn.InstanceNorm2d`,
  2408. :class:`~torch.nn.InstanceNorm3d` for details.
  2409. """
  2410. if has_torch_function_variadic(input, running_mean, running_var, weight, bias):
  2411. return handle_torch_function(
  2412. instance_norm,
  2413. (input, running_mean, running_var, weight, bias),
  2414. input,
  2415. running_mean=running_mean,
  2416. running_var=running_var,
  2417. weight=weight,
  2418. bias=bias,
  2419. use_input_stats=use_input_stats,
  2420. momentum=momentum,
  2421. eps=eps,
  2422. )
  2423. if use_input_stats:
  2424. # pyrefly: ignore [bad-argument-type]
  2425. _verify_spatial_size(input.size())
  2426. return torch.instance_norm(
  2427. input,
  2428. weight,
  2429. bias,
  2430. running_mean,
  2431. running_var,
  2432. use_input_stats,
  2433. momentum,
  2434. eps,
  2435. torch.backends.cudnn.enabled,
  2436. )
  2437. def layer_norm(
  2438. input: Tensor,
  2439. normalized_shape: list[int],
  2440. weight: Optional[Tensor] = None,
  2441. bias: Optional[Tensor] = None,
  2442. eps: float = 1e-5,
  2443. ) -> Tensor:
  2444. r"""Apply Layer Normalization for last certain number of dimensions.
  2445. See :class:`~torch.nn.LayerNorm` for details.
  2446. """
  2447. if has_torch_function_variadic(input, weight, bias):
  2448. return handle_torch_function(
  2449. layer_norm,
  2450. (input, weight, bias),
  2451. input,
  2452. normalized_shape,
  2453. weight=weight,
  2454. bias=bias,
  2455. eps=eps,
  2456. )
  2457. return torch.layer_norm(
  2458. input, normalized_shape, weight, bias, eps, torch.backends.cudnn.enabled
  2459. )
  2460. def rms_norm(
  2461. input: Tensor,
  2462. normalized_shape: list[int],
  2463. weight: Optional[Tensor] = None,
  2464. eps: Optional[float] = None,
  2465. ) -> Tensor:
  2466. r"""Apply Root Mean Square Layer Normalization.
  2467. See :class:`~torch.nn.RMSNorm` for details.
  2468. """
  2469. if has_torch_function_variadic(input, weight):
  2470. return handle_torch_function(
  2471. rms_norm, (input, weight), input, normalized_shape, weight=weight, eps=eps
  2472. )
  2473. return torch.rms_norm(input, normalized_shape, weight, eps)
  2474. def group_norm(
  2475. input: Tensor,
  2476. num_groups: int,
  2477. weight: Optional[Tensor] = None,
  2478. bias: Optional[Tensor] = None,
  2479. eps: float = 1e-5,
  2480. ) -> Tensor:
  2481. r"""Apply Group Normalization for last certain number of dimensions.
  2482. See :class:`~torch.nn.GroupNorm` for details.
  2483. """
  2484. if has_torch_function_variadic(input, weight, bias):
  2485. return handle_torch_function(
  2486. group_norm,
  2487. (
  2488. input,
  2489. weight,
  2490. bias,
  2491. ),
  2492. input,
  2493. num_groups,
  2494. weight=weight,
  2495. bias=bias,
  2496. eps=eps,
  2497. )
  2498. if input.dim() < 2:
  2499. raise RuntimeError(
  2500. f"Expected at least 2 dimensions for input tensor but received {input.dim()}"
  2501. )
  2502. _verify_batch_size(
  2503. [input.size(0) * input.size(1) // num_groups, num_groups]
  2504. + list(input.size()[2:])
  2505. )
  2506. return torch.group_norm(
  2507. input, num_groups, weight, bias, eps, torch.backends.cudnn.enabled
  2508. )
  2509. def local_response_norm(
  2510. input: Tensor,
  2511. size: int,
  2512. alpha: float = 1e-4,
  2513. beta: float = 0.75,
  2514. k: float = 1.0,
  2515. ) -> Tensor:
  2516. r"""Apply local response normalization over an input signal.
  2517. The input signal is composed of several input planes, where channels occupy the second dimension.
  2518. Normalization is applied across channels.
  2519. See :class:`~torch.nn.LocalResponseNorm` for details.
  2520. """
  2521. if has_torch_function_unary(input):
  2522. return handle_torch_function(
  2523. local_response_norm, (input,), input, size, alpha=alpha, beta=beta, k=k
  2524. )
  2525. dim = input.dim()
  2526. if dim < 3:
  2527. raise ValueError(
  2528. f"Expected 3D or higher dimensionality input (got {dim} dimensions)"
  2529. )
  2530. if input.numel() == 0:
  2531. return input
  2532. div = input.mul(input)
  2533. if dim == 3:
  2534. div = div.unsqueeze(1)
  2535. # pyrefly: ignore [bad-argument-type]
  2536. div = pad(div, (0, 0, size // 2, (size - 1) // 2))
  2537. div = avg_pool2d(div, (size, 1), stride=1).squeeze(1)
  2538. else:
  2539. sizes = input.size()
  2540. div = div.view(sizes[0], 1, sizes[1], sizes[2], -1)
  2541. # pyrefly: ignore [bad-argument-type]
  2542. div = pad(div, (0, 0, 0, 0, size // 2, (size - 1) // 2))
  2543. div = avg_pool3d(div, (size, 1, 1), stride=1).squeeze(1)
  2544. div = div.view(sizes)
  2545. div = div.mul(alpha).add(k).pow(beta)
  2546. return input / div
  2547. # loss
  2548. def ctc_loss(
  2549. log_probs: Tensor,
  2550. targets: Tensor,
  2551. input_lengths: Tensor,
  2552. target_lengths: Tensor,
  2553. blank: int = 0,
  2554. reduction: str = "mean",
  2555. zero_infinity: bool = False,
  2556. ) -> Tensor:
  2557. r"""Compute the Connectionist Temporal Classification loss.
  2558. See :class:`~torch.nn.CTCLoss` for details.
  2559. Note:
  2560. {cudnn_reproducibility_note}
  2561. Note:
  2562. {backward_reproducibility_note}
  2563. Args:
  2564. log_probs: :math:`(T, N, C)` or :math:`(T, C)` where `C = number of characters in alphabet including blank`,
  2565. `T = input length`, and `N = batch size`.
  2566. The logarithmized probabilities of the outputs
  2567. (e.g. obtained with :func:`torch.nn.functional.log_softmax`).
  2568. targets: :math:`(N, S)` or `(sum(target_lengths))`.
  2569. May be an empty tensor if all entries in `target_lengths` are zero.
  2570. In the second form, the targets are assumed to be concatenated.
  2571. input_lengths: :math:`(N)` or :math:`()`.
  2572. Lengths of the inputs (must each be :math:`\leq T`)
  2573. target_lengths: :math:`(N)` or :math:`()`.
  2574. Lengths of the targets
  2575. blank (int, optional):
  2576. Blank label. Default :math:`0`.
  2577. reduction (str, optional): Specifies the reduction to apply to the output:
  2578. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  2579. ``'mean'``: the output losses will be divided by the target lengths and
  2580. then the mean over the batch is taken, ``'sum'``: the output will be
  2581. summed. Default: ``'mean'``
  2582. zero_infinity (bool, optional):
  2583. Whether to zero infinite losses and the associated gradients.
  2584. Default: ``False``
  2585. Infinite losses mainly occur when the inputs are too short
  2586. to be aligned to the targets.
  2587. Example::
  2588. >>> log_probs = torch.randn(50, 16, 20).log_softmax(2).detach().requires_grad_()
  2589. >>> targets = torch.randint(1, 20, (16, 30), dtype=torch.long)
  2590. >>> input_lengths = torch.full((16,), 50, dtype=torch.long)
  2591. >>> target_lengths = torch.randint(10, 30, (16,), dtype=torch.long)
  2592. >>> loss = F.ctc_loss(log_probs, targets, input_lengths, target_lengths)
  2593. >>> loss.backward()
  2594. """
  2595. if has_torch_function_variadic(log_probs, targets, input_lengths, target_lengths):
  2596. return handle_torch_function(
  2597. ctc_loss,
  2598. (log_probs, targets, input_lengths, target_lengths),
  2599. log_probs,
  2600. targets,
  2601. input_lengths,
  2602. target_lengths,
  2603. blank=blank,
  2604. reduction=reduction,
  2605. zero_infinity=zero_infinity,
  2606. )
  2607. return torch.ctc_loss(
  2608. log_probs,
  2609. targets,
  2610. input_lengths,
  2611. target_lengths,
  2612. blank,
  2613. _Reduction.get_enum(reduction),
  2614. zero_infinity,
  2615. )
  2616. if ctc_loss.__doc__:
  2617. ctc_loss.__doc__ = ctc_loss.__doc__.format(**reproducibility_notes)
  2618. def nll_loss(
  2619. input: Tensor,
  2620. target: Tensor,
  2621. weight: Optional[Tensor] = None,
  2622. size_average: Optional[bool] = None,
  2623. ignore_index: int = -100,
  2624. reduce: Optional[bool] = None,
  2625. reduction: str = "mean",
  2626. ) -> Tensor:
  2627. r"""Compute the negative log likelihood loss.
  2628. See :class:`~torch.nn.NLLLoss` for details.
  2629. Args:
  2630. input: :math:`(N, C)` where `C = number of classes` or :math:`(N, C, H, W)`
  2631. in case of 2D Loss, or :math:`(N, C, d_1, d_2, ..., d_K)` where :math:`K \geq 1`
  2632. in the case of K-dimensional loss. `input` is expected to be log-probabilities.
  2633. target: :math:`(N)` where each value is :math:`0 \leq \text{targets}[i] \leq C-1`,
  2634. or :math:`(N, d_1, d_2, ..., d_K)` where :math:`K \geq 1` for
  2635. K-dimensional loss.
  2636. weight (Tensor, optional): A manual rescaling weight given to each
  2637. class. If given, has to be a Tensor of size `C`
  2638. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  2639. ignore_index (int, optional): Specifies a target value that is ignored
  2640. and does not contribute to the input gradient. When :attr:`size_average` is
  2641. ``True``, the loss is averaged over non-ignored targets. Default: -100
  2642. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  2643. reduction (str, optional): Specifies the reduction to apply to the output:
  2644. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  2645. ``'mean'``: the sum of the output will be divided by the number of
  2646. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  2647. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  2648. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  2649. Example::
  2650. >>> # input is of size N x C = 3 x 5
  2651. >>> input = torch.randn(3, 5, requires_grad=True)
  2652. >>> # each element in target has to have 0 <= value < C
  2653. >>> target = torch.tensor([1, 0, 4])
  2654. >>> output = F.nll_loss(F.log_softmax(input, dim=1), target)
  2655. >>> output.backward()
  2656. """
  2657. if has_torch_function_variadic(input, target, weight):
  2658. return handle_torch_function(
  2659. nll_loss,
  2660. (input, target, weight),
  2661. input,
  2662. target,
  2663. weight=weight,
  2664. size_average=size_average,
  2665. ignore_index=ignore_index,
  2666. reduce=reduce,
  2667. reduction=reduction,
  2668. )
  2669. if size_average is not None or reduce is not None:
  2670. reduction = _Reduction.legacy_get_string(size_average, reduce)
  2671. return torch._C._nn.nll_loss_nd(
  2672. input,
  2673. target,
  2674. weight,
  2675. # pyrefly: ignore [bad-argument-type]
  2676. _Reduction.get_enum(reduction),
  2677. ignore_index,
  2678. )
  2679. def poisson_nll_loss(
  2680. input: Tensor,
  2681. target: Tensor,
  2682. log_input: bool = True,
  2683. full: bool = False,
  2684. size_average: Optional[bool] = None,
  2685. eps: float = 1e-8,
  2686. reduce: Optional[bool] = None,
  2687. reduction: str = "mean",
  2688. ) -> Tensor:
  2689. r"""Compute the Poisson negative log likelihood loss.
  2690. See :class:`~torch.nn.PoissonNLLLoss` for details.
  2691. Args:
  2692. input: Expectation of underlying Poisson distribution.
  2693. target: Random sample :math:`target \sim \text{Poisson}(input)`.
  2694. log_input: If ``True`` the loss is computed as
  2695. :math:`\exp(\text{input}) - \text{target} * \text{input}`, if ``False`` then loss is
  2696. :math:`\text{input} - \text{target} * \log(\text{input}+\text{eps})`. Default: ``True``
  2697. full: Whether to compute full loss, i. e. to add the Stirling
  2698. approximation term. Default: ``False``
  2699. :math:`\text{target} * \log(\text{target}) - \text{target} + 0.5 * \log(2 * \pi * \text{target})`.
  2700. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  2701. eps (float, optional): Small value to avoid evaluation of :math:`\log(0)` when
  2702. :attr:`log_input`\ =\ ``False``. Default: 1e-8
  2703. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  2704. reduction (str, optional): Specifies the reduction to apply to the output:
  2705. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  2706. ``'mean'``: the sum of the output will be divided by the number of
  2707. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  2708. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  2709. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  2710. """
  2711. if has_torch_function_variadic(input, target):
  2712. return handle_torch_function(
  2713. poisson_nll_loss,
  2714. (input, target),
  2715. input,
  2716. target,
  2717. log_input=log_input,
  2718. full=full,
  2719. size_average=size_average,
  2720. eps=eps,
  2721. reduce=reduce,
  2722. reduction=reduction,
  2723. )
  2724. if size_average is not None or reduce is not None:
  2725. reduction = _Reduction.legacy_get_string(size_average, reduce)
  2726. if reduction != "none" and reduction != "mean" and reduction != "sum":
  2727. ret = input
  2728. raise ValueError(reduction + " is not a valid value for reduction")
  2729. ret = torch.poisson_nll_loss(
  2730. input, target, log_input, full, eps, _Reduction.get_enum(reduction)
  2731. )
  2732. return ret
  2733. def gaussian_nll_loss(
  2734. input: Tensor,
  2735. target: Tensor,
  2736. var: Tensor | float,
  2737. full: bool = False,
  2738. eps: float = 1e-6,
  2739. reduction: str = "mean",
  2740. ) -> Tensor:
  2741. r"""Compute the Gaussian negative log likelihood loss.
  2742. See :class:`~torch.nn.GaussianNLLLoss` for details.
  2743. Args:
  2744. input: Expectation of the Gaussian distribution.
  2745. target: Sample from the Gaussian distribution.
  2746. var: Tensor of positive variance(s), one for each of the expectations
  2747. in the input (heteroscedastic), or a single one (homoscedastic),
  2748. or a positive scalar value to be used for all expectations.
  2749. full (bool, optional): Whether to include the constant term in the loss calculation. Default: ``False``.
  2750. eps (float, optional): Value added to var, for stability. Default: 1e-6.
  2751. reduction (str, optional): Specifies the reduction to apply to the output:
  2752. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  2753. ``'mean'``: the output is the average of all batch member losses,
  2754. ``'sum'``: the output is the sum of all batch member losses.
  2755. Default: ``'mean'``.
  2756. """
  2757. if has_torch_function_variadic(input, target, var):
  2758. return handle_torch_function(
  2759. gaussian_nll_loss,
  2760. (input, target, var),
  2761. input,
  2762. target,
  2763. var,
  2764. full=full,
  2765. eps=eps,
  2766. reduction=reduction,
  2767. )
  2768. # Entries of var must be non-negative
  2769. if isinstance(var, float):
  2770. if var < 0:
  2771. raise ValueError("var has negative entry/entries")
  2772. var = var * torch.ones_like(input)
  2773. elif torch.any(var < 0):
  2774. raise ValueError("var has negative entry/entries")
  2775. # Check var size
  2776. # If var.size == input.size, the case is heteroscedastic and no further checks are needed.
  2777. # Otherwise:
  2778. if var.size() != input.size():
  2779. # If var is one dimension short of input, but the sizes match otherwise, then this is a homoscedastic case.
  2780. # e.g. input.size = (10, 2, 3), var.size = (10, 2)
  2781. # -> unsqueeze var so that var.shape = (10, 2, 1)
  2782. # this is done so that broadcasting can happen in the loss calculation
  2783. if input.size()[:-1] == var.size():
  2784. var = torch.unsqueeze(var, -1)
  2785. # This checks if the var is broadcastable to the input and there is only one mismatched dimension.
  2786. # This is also a homoscedastic case.
  2787. # e.g. input.size = (10, 2, 3), var.size = (10, 2, 1)
  2788. # or input.size = (4, 3, 32, 32), var.size = (4, 1, 32, 32)
  2789. elif (
  2790. input.ndim == var.ndim
  2791. and sum(y for x, y in zip(input.size(), var.size(), strict=True) if x != y)
  2792. == 1
  2793. ): # Heteroscedastic case
  2794. pass
  2795. # If none of the above pass, then the size of var is incorrect.
  2796. else:
  2797. raise ValueError("var is of incorrect size")
  2798. # Check validity of reduction mode
  2799. if reduction != "none" and reduction != "mean" and reduction != "sum":
  2800. raise ValueError(reduction + " is not valid")
  2801. # Clamp for stability
  2802. var = var.clone()
  2803. with torch.no_grad():
  2804. var.clamp_(min=eps)
  2805. # Calculate the loss
  2806. # pyrefly: ignore [unsupported-operation]
  2807. loss = 0.5 * (torch.log(var) + (input - target) ** 2 / var)
  2808. if full:
  2809. loss += 0.5 * math.log(2 * math.pi)
  2810. if reduction == "mean":
  2811. return loss.mean()
  2812. elif reduction == "sum":
  2813. return loss.sum()
  2814. else:
  2815. return loss
  2816. def kl_div(
  2817. input: Tensor,
  2818. target: Tensor,
  2819. size_average: Optional[bool] = None,
  2820. reduce: Optional[bool] = None,
  2821. reduction: str = "mean",
  2822. log_target: bool = False,
  2823. ) -> Tensor:
  2824. r"""Compute the KL Divergence loss.
  2825. Refer - The `Kullback-Leibler divergence Loss
  2826. <https://en.wikipedia.org/wiki/Kullback-Leibler_divergence>`__
  2827. See :class:`~torch.nn.KLDivLoss` for details.
  2828. Args:
  2829. input: Tensor of arbitrary shape in log-probabilities.
  2830. target: Tensor of the same shape as input. See :attr:`log_target` for
  2831. the target's interpretation.
  2832. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  2833. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  2834. reduction (str, optional): Specifies the reduction to apply to the output:
  2835. ``'none'`` | ``'batchmean'`` | ``'sum'`` | ``'mean'``.
  2836. ``'none'``: no reduction will be applied
  2837. ``'batchmean'``: the sum of the output will be divided by the batchsize
  2838. ``'sum'``: the output will be summed
  2839. ``'mean'``: the output will be divided by the number of elements in the output
  2840. Default: ``'mean'``
  2841. log_target (bool): A flag indicating whether ``target`` is passed in the log space.
  2842. It is recommended to pass certain distributions (like ``softmax``)
  2843. in the log space to avoid numerical issues caused by explicit ``log``.
  2844. Default: ``False``
  2845. .. note::
  2846. :attr:`size_average` and :attr:`reduce` are in the process of being deprecated,
  2847. and in the meantime, specifying either of those two args will override :attr:`reduction`.
  2848. .. warning::
  2849. :attr:`reduction` = ``'mean'`` doesn't return the true kl divergence value, please use
  2850. :attr:`reduction` = ``'batchmean'`` which aligns with KL math definition.
  2851. """
  2852. if has_torch_function_variadic(input, target):
  2853. return handle_torch_function(
  2854. kl_div,
  2855. (input, target),
  2856. input,
  2857. target,
  2858. size_average=size_average,
  2859. reduce=reduce,
  2860. reduction=reduction,
  2861. log_target=log_target,
  2862. )
  2863. if size_average is not None or reduce is not None:
  2864. reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
  2865. else:
  2866. if reduction == "mean":
  2867. warnings.warn(
  2868. "reduction: 'mean' divides the total loss by both the batch size and the support size."
  2869. "'batchmean' divides only by the batch size, and aligns with the KL div math definition."
  2870. "'mean' will be changed to behave the same as 'batchmean' in the next major release.",
  2871. stacklevel=2,
  2872. )
  2873. # special case for batchmean
  2874. if reduction == "batchmean":
  2875. reduction_enum = _Reduction.get_enum("sum")
  2876. else:
  2877. reduction_enum = _Reduction.get_enum(reduction)
  2878. reduced = torch.kl_div(input, target, reduction_enum, log_target=log_target)
  2879. if reduction == "batchmean" and input.dim() != 0:
  2880. reduced = reduced / input.size()[0]
  2881. return reduced
  2882. def cross_entropy(
  2883. input: Tensor,
  2884. target: Tensor,
  2885. weight: Optional[Tensor] = None,
  2886. size_average: Optional[bool] = None,
  2887. ignore_index: int = -100,
  2888. reduce: Optional[bool] = None,
  2889. reduction: str = "mean",
  2890. label_smoothing: float = 0.0,
  2891. ) -> Tensor:
  2892. r"""Compute the cross entropy loss between input logits and target.
  2893. See :class:`~torch.nn.CrossEntropyLoss` for details.
  2894. Args:
  2895. input (Tensor) : Predicted unnormalized logits;
  2896. see Shape section below for supported shapes.
  2897. target (Tensor) : Ground truth class indices or class probabilities;
  2898. see Shape section below for supported shapes.
  2899. weight (Tensor, optional): a manual rescaling weight given to each
  2900. class. If given, has to be a Tensor of size `C`
  2901. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  2902. ignore_index (int, optional): Specifies a target value that is ignored
  2903. and does not contribute to the input gradient. When :attr:`size_average` is
  2904. ``True``, the loss is averaged over non-ignored targets. Note that
  2905. :attr:`ignore_index` is only applicable when the target contains class indices.
  2906. Default: -100
  2907. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  2908. reduction (str, optional): Specifies the reduction to apply to the output:
  2909. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  2910. ``'mean'``: the sum of the output will be divided by the number of
  2911. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  2912. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  2913. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  2914. label_smoothing (float, optional): A float in [0.0, 1.0]. Specifies the amount
  2915. of smoothing when computing the loss, where 0.0 means no smoothing. The targets
  2916. become a mixture of the original ground truth and a uniform distribution as described in
  2917. `Rethinking the Inception Architecture for Computer Vision <https://arxiv.org/abs/1512.00567>`__. Default: :math:`0.0`.
  2918. Shape:
  2919. - Input: Shape :math:`(C)`, :math:`(N, C)` or :math:`(N, C, d_1, d_2, ..., d_K)` with :math:`K \geq 1`
  2920. in the case of `K`-dimensional loss.
  2921. - Target: If containing class indices, shape :math:`()`, :math:`(N)` or :math:`(N, d_1, d_2, ..., d_K)` with
  2922. :math:`K \geq 1` in the case of K-dimensional loss where each value should be between :math:`[0, C)`.
  2923. If containing class probabilities, same shape as the input and each value should be between :math:`[0, 1]`.
  2924. where:
  2925. .. math::
  2926. \begin{aligned}
  2927. C ={} & \text{number of classes} \\
  2928. N ={} & \text{batch size} \\
  2929. \end{aligned}
  2930. Examples::
  2931. >>> # Example of target with class indices
  2932. >>> input = torch.randn(3, 5, requires_grad=True)
  2933. >>> target = torch.randint(5, (3,), dtype=torch.int64)
  2934. >>> loss = F.cross_entropy(input, target)
  2935. >>> loss.backward()
  2936. >>>
  2937. >>> # Example of target with class probabilities
  2938. >>> input = torch.randn(3, 5, requires_grad=True)
  2939. >>> target = torch.randn(3, 5).softmax(dim=1)
  2940. >>> loss = F.cross_entropy(input, target)
  2941. >>> loss.backward()
  2942. """
  2943. if has_torch_function_variadic(input, target, weight):
  2944. return handle_torch_function(
  2945. cross_entropy,
  2946. (input, target, weight),
  2947. input,
  2948. target,
  2949. weight=weight,
  2950. size_average=size_average,
  2951. ignore_index=ignore_index,
  2952. reduce=reduce,
  2953. reduction=reduction,
  2954. label_smoothing=label_smoothing,
  2955. )
  2956. if size_average is not None or reduce is not None:
  2957. reduction = _Reduction.legacy_get_string(size_average, reduce)
  2958. return torch._C._nn.cross_entropy_loss(
  2959. input,
  2960. target,
  2961. weight,
  2962. # pyrefly: ignore [bad-argument-type]
  2963. _Reduction.get_enum(reduction),
  2964. ignore_index,
  2965. label_smoothing,
  2966. )
  2967. def binary_cross_entropy(
  2968. input: Tensor,
  2969. target: Tensor,
  2970. weight: Optional[Tensor] = None,
  2971. size_average: Optional[bool] = None,
  2972. reduce: Optional[bool] = None,
  2973. reduction: str = "mean",
  2974. ) -> Tensor:
  2975. r"""Compute Binary Cross Entropy between the target and input probabilities.
  2976. See :class:`~torch.nn.BCELoss` for details.
  2977. Args:
  2978. input: Tensor of arbitrary shape as probabilities.
  2979. target: Tensor of the same shape as input with values between 0 and 1.
  2980. weight (Tensor, optional): a manual rescaling weight
  2981. if provided it's repeated to match input tensor shape
  2982. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  2983. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  2984. reduction (str, optional): Specifies the reduction to apply to the output:
  2985. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  2986. ``'mean'``: the sum of the output will be divided by the number of
  2987. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  2988. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  2989. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  2990. Examples::
  2991. >>> input = torch.randn(3, 2, requires_grad=True)
  2992. >>> target = torch.rand(3, 2, requires_grad=False)
  2993. >>> loss = F.binary_cross_entropy(torch.sigmoid(input), target)
  2994. >>> loss.backward()
  2995. """
  2996. if has_torch_function_variadic(input, target, weight):
  2997. return handle_torch_function(
  2998. binary_cross_entropy,
  2999. (input, target, weight),
  3000. input,
  3001. target,
  3002. weight=weight,
  3003. size_average=size_average,
  3004. reduce=reduce,
  3005. reduction=reduction,
  3006. )
  3007. if size_average is not None or reduce is not None:
  3008. reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
  3009. else:
  3010. reduction_enum = _Reduction.get_enum(reduction)
  3011. if target.size() != input.size():
  3012. raise ValueError(
  3013. f"Using a target size ({target.size()}) that is different to the input size ({input.size()}) is deprecated. "
  3014. "Please ensure they have the same size."
  3015. )
  3016. if weight is not None:
  3017. new_size = _infer_size(target.size(), weight.size())
  3018. weight = weight.expand(new_size)
  3019. # pyrefly: ignore [bad-argument-type]
  3020. return torch._C._nn.binary_cross_entropy(input, target, weight, reduction_enum)
  3021. def binary_cross_entropy_with_logits(
  3022. input: Tensor,
  3023. target: Tensor,
  3024. weight: Optional[Tensor] = None,
  3025. size_average: Optional[bool] = None,
  3026. reduce: Optional[bool] = None,
  3027. reduction: str = "mean",
  3028. pos_weight: Optional[Tensor] = None,
  3029. ) -> Tensor:
  3030. r"""Compute Binary Cross Entropy between target and input logits.
  3031. See :class:`~torch.nn.BCEWithLogitsLoss` for details.
  3032. Args:
  3033. input: Tensor of arbitrary shape as unnormalized scores (often referred to as logits).
  3034. target: Tensor of the same shape as input with values between 0 and 1
  3035. weight (Tensor, optional): a manual rescaling weight. If provided, the dimension
  3036. of weight supports :ref:`broadcasting to a common shape <broadcasting-semantics>`
  3037. with respect to the input (and target) shape.
  3038. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3039. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3040. reduction (str, optional): Specifies the reduction to apply to the output:
  3041. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction will be applied,
  3042. ``'mean'``: the sum of the output will be divided by the number of
  3043. elements in the output, ``'sum'``: the output will be summed. Note: :attr:`size_average`
  3044. and :attr:`reduce` are in the process of being deprecated, and in the meantime,
  3045. specifying either of those two args will override :attr:`reduction`. Default: ``'mean'``
  3046. pos_weight (Tensor, optional): a weight of positive examples to be broadcasted with target.
  3047. Must be a tensor with equal size along the class dimension to the number of classes.
  3048. Pay close attention to PyTorch's broadcasting semantics in order to achieve the desired
  3049. operations. For a target of size [B, C, H, W] (where B is batch size) pos_weight of
  3050. size [B, C, H, W] will apply different pos_weights to each element of the batch or
  3051. [C, H, W] the same pos_weights across the batch. To apply the same positive weight
  3052. along all spatial dimensions for a 2D multi-class target [C, H, W] use: [C, 1, 1].
  3053. Default: ``None``
  3054. Examples::
  3055. >>> input = torch.randn(3, requires_grad=True)
  3056. >>> target = torch.empty(3).random_(2)
  3057. >>> loss = F.binary_cross_entropy_with_logits(input, target)
  3058. >>> loss.backward()
  3059. """
  3060. if has_torch_function_variadic(input, target, weight, pos_weight):
  3061. return handle_torch_function(
  3062. binary_cross_entropy_with_logits,
  3063. (input, target, weight, pos_weight),
  3064. input,
  3065. target,
  3066. weight=weight,
  3067. size_average=size_average,
  3068. reduce=reduce,
  3069. reduction=reduction,
  3070. pos_weight=pos_weight,
  3071. )
  3072. if size_average is not None or reduce is not None:
  3073. reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
  3074. else:
  3075. reduction_enum = _Reduction.get_enum(reduction)
  3076. if not (target.size() == input.size()):
  3077. raise ValueError(
  3078. f"Target size ({target.size()}) must be the same as input size ({input.size()})"
  3079. )
  3080. return torch.binary_cross_entropy_with_logits(
  3081. input, target, weight, pos_weight, reduction_enum
  3082. )
  3083. def smooth_l1_loss(
  3084. input: Tensor,
  3085. target: Tensor,
  3086. size_average: Optional[bool] = None,
  3087. reduce: Optional[bool] = None,
  3088. reduction: str = "mean",
  3089. beta: float = 1.0,
  3090. ) -> Tensor:
  3091. r"""Compute the Smooth L1 loss.
  3092. Function uses a squared term if the absolute
  3093. element-wise error falls below beta and an L1 term otherwise.
  3094. See :class:`~torch.nn.SmoothL1Loss` for details.
  3095. Args:
  3096. input (Tensor): Predicted values.
  3097. target (Tensor): Ground truth values.
  3098. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3099. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3100. reduction (str, optional): Specifies the reduction to apply to the output:
  3101. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3102. 'sum': the output will be summed. 'none': no reduction will be applied.
  3103. Default: 'mean'.
  3104. beta (float, optional): Specifies the threshold at which to change from the squared
  3105. term to the L1 term in the loss calculation. This value must be positive.
  3106. Default: 1.0.
  3107. Returns:
  3108. Tensor: L1 loss (optionally weighted).
  3109. """
  3110. if has_torch_function_variadic(input, target):
  3111. return handle_torch_function(
  3112. smooth_l1_loss,
  3113. (input, target),
  3114. input,
  3115. target,
  3116. size_average=size_average,
  3117. reduce=reduce,
  3118. reduction=reduction,
  3119. beta=beta,
  3120. )
  3121. if target.size() != input.size():
  3122. warnings.warn(
  3123. f"Using a target size ({target.size()}) that is different to the input size ({input.size()}). "
  3124. "This will likely lead to incorrect results due to broadcasting. "
  3125. "Please ensure they have the same size.",
  3126. stacklevel=2,
  3127. )
  3128. if size_average is not None or reduce is not None:
  3129. reduction = _Reduction.legacy_get_string(size_average, reduce)
  3130. expanded_input, expanded_target = torch.broadcast_tensors(input, target)
  3131. if beta == 0.0:
  3132. return torch._C._nn.l1_loss(
  3133. expanded_input,
  3134. expanded_target,
  3135. # pyrefly: ignore [bad-argument-type]
  3136. _Reduction.get_enum(reduction),
  3137. )
  3138. else:
  3139. return torch._C._nn.smooth_l1_loss(
  3140. expanded_input,
  3141. expanded_target,
  3142. # pyrefly: ignore [bad-argument-type]
  3143. _Reduction.get_enum(reduction),
  3144. beta,
  3145. )
  3146. def huber_loss(
  3147. input: Tensor,
  3148. target: Tensor,
  3149. reduction: str = "mean",
  3150. delta: float = 1.0,
  3151. weight: Optional[Tensor] = None,
  3152. ) -> Tensor:
  3153. r"""Compute the Huber loss, with optional weighting.
  3154. Function uses a squared term if the absolute
  3155. element-wise error falls below delta and a delta-scaled L1 term otherwise.
  3156. When delta equals 1, this loss is equivalent to SmoothL1Loss.
  3157. In general, Huber loss differs from SmoothL1Loss by a factor of delta (AKA beta in Smooth L1).
  3158. See :class:`~torch.nn.HuberLoss` for details.
  3159. Args:
  3160. input (Tensor): Predicted values.
  3161. target (Tensor): Ground truth values.
  3162. reduction (str, optional): Specifies the reduction to apply to the output:
  3163. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3164. 'sum': the output will be summed. 'none': no reduction will be applied.
  3165. Default: 'mean'.
  3166. delta (float, optional): The threshold at which to change between delta-scaled L1 and L2 loss. Default: 1.0.
  3167. weight (Tensor, optional): Weights for each sample. Default: None.
  3168. Returns:
  3169. Tensor: Huber loss (optionally weighted).
  3170. """
  3171. if has_torch_function_variadic(input, target, weight):
  3172. return handle_torch_function(
  3173. huber_loss,
  3174. (input, target, weight),
  3175. input,
  3176. target,
  3177. reduction=reduction,
  3178. delta=delta,
  3179. weight=weight,
  3180. )
  3181. if target.size() != input.size():
  3182. warnings.warn(
  3183. f"Using a target size ({target.size()}) that is different to the input size ({input.size()}). "
  3184. "This will likely lead to incorrect results due to broadcasting. "
  3185. "Please ensure they have the same size.",
  3186. stacklevel=2,
  3187. )
  3188. expanded_input, expanded_target = torch.broadcast_tensors(input, target)
  3189. if weight is None:
  3190. # Use the optimized C++ backend for standard Huber loss
  3191. return torch._C._nn.huber_loss(
  3192. expanded_input,
  3193. expanded_target,
  3194. # pyrefly: ignore [bad-argument-type]
  3195. _Reduction.get_enum(reduction),
  3196. delta,
  3197. )
  3198. else:
  3199. if weight.size() != input.size():
  3200. raise ValueError("Weights and input must have the same size.")
  3201. # Calculate the unweighted loss first
  3202. unweighted_loss = torch._C._nn.huber_loss(
  3203. expanded_input,
  3204. expanded_target,
  3205. # pyrefly: ignore [bad-argument-type]
  3206. _Reduction.get_enum("none"),
  3207. delta,
  3208. )
  3209. # Apply weight to the unweighted loss
  3210. weighted_loss = unweighted_loss * weight
  3211. if reduction == "none":
  3212. return weighted_loss
  3213. elif reduction == "sum":
  3214. return torch.sum(weighted_loss)
  3215. elif reduction == "mean":
  3216. return weighted_loss.mean()
  3217. else:
  3218. raise ValueError(
  3219. f"Invalid reduction mode: {reduction}. Expected one of 'none', 'mean', 'sum'."
  3220. )
  3221. def l1_loss(
  3222. input: Tensor,
  3223. target: Tensor,
  3224. size_average: Optional[bool] = None,
  3225. reduce: Optional[bool] = None,
  3226. reduction: str = "mean",
  3227. weight: Optional[Tensor] = None,
  3228. ) -> Tensor: # noqa: D400,D402
  3229. r"""Compute the L1 loss, with optional weighting.
  3230. Function that takes the mean element-wise absolute value difference.
  3231. See :class:`~torch.nn.L1Loss` for details.
  3232. Args:
  3233. input (Tensor): Predicted values.
  3234. target (Tensor): Ground truth values.
  3235. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3236. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3237. reduction (str, optional): Specifies the reduction to apply to the output:
  3238. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3239. 'sum': the output will be summed. 'none': no reduction will be applied.
  3240. Default: 'mean'.
  3241. weight (Tensor, optional): Weights for each sample. Default: None.
  3242. Returns:
  3243. Tensor: L1 loss (optionally weighted).
  3244. """
  3245. if has_torch_function_variadic(input, target):
  3246. return handle_torch_function(
  3247. l1_loss,
  3248. (input, target, weight),
  3249. input,
  3250. target,
  3251. size_average=size_average,
  3252. reduce=reduce,
  3253. reduction=reduction,
  3254. )
  3255. if target.size() != input.size():
  3256. warnings.warn(
  3257. f"Using a target size ({target.size()}) that is different to the input size ({input.size()}). "
  3258. "This will likely lead to incorrect results due to broadcasting. "
  3259. "Please ensure they have the same size.",
  3260. stacklevel=2,
  3261. )
  3262. if size_average is not None or reduce is not None:
  3263. reduction = _Reduction.legacy_get_string(size_average, reduce)
  3264. expanded_input, expanded_target = torch.broadcast_tensors(input, target)
  3265. if weight is not None:
  3266. if weight.size() != input.size():
  3267. raise ValueError("Weights and input must have the same size.")
  3268. absolute_errors = torch.abs(expanded_input - expanded_target)
  3269. weighted_absolute_errors = absolute_errors * weight
  3270. if reduction == "none":
  3271. return weighted_absolute_errors
  3272. elif reduction == "sum":
  3273. return torch.sum(weighted_absolute_errors)
  3274. elif reduction == "mean":
  3275. return torch.sum(weighted_absolute_errors) / torch.sum(weight)
  3276. else:
  3277. raise ValueError(
  3278. f"Invalid reduction mode: {reduction}. Expected one of 'none', 'mean', 'sum'."
  3279. )
  3280. else:
  3281. return torch._C._nn.l1_loss(
  3282. expanded_input,
  3283. expanded_target,
  3284. # pyrefly: ignore [bad-argument-type]
  3285. _Reduction.get_enum(reduction),
  3286. )
  3287. def mse_loss(
  3288. input: Tensor,
  3289. target: Tensor,
  3290. size_average: Optional[bool] = None,
  3291. reduce: Optional[bool] = None,
  3292. reduction: str = "mean",
  3293. weight: Optional[Tensor] = None,
  3294. ) -> Tensor:
  3295. r"""Compute the element-wise mean squared error, with optional weighting.
  3296. See :class:`~torch.nn.MSELoss` for details.
  3297. Args:
  3298. input (Tensor): Predicted values.
  3299. target (Tensor): Ground truth values.
  3300. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3301. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3302. reduction (str, optional): Specifies the reduction to apply to the output:
  3303. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3304. 'sum': the output will be summed. 'none': no reduction will be applied.
  3305. Default: 'mean'.
  3306. weight (Tensor, optional): Weights for each sample. Default: None.
  3307. Returns:
  3308. Tensor: Mean Squared Error loss (optionally weighted).
  3309. """
  3310. if has_torch_function_variadic(input, target, weight):
  3311. return handle_torch_function(
  3312. mse_loss,
  3313. (input, target, weight),
  3314. input,
  3315. target,
  3316. size_average=size_average,
  3317. reduce=reduce,
  3318. reduction=reduction,
  3319. weight=weight,
  3320. )
  3321. if target.size() != input.size():
  3322. warnings.warn(
  3323. f"Using a target size ({target.size()}) that is different to the input size ({input.size()}). "
  3324. "This will likely lead to incorrect results due to broadcasting. "
  3325. "Please ensure they have the same size.",
  3326. stacklevel=2,
  3327. )
  3328. if size_average is not None or reduce is not None:
  3329. reduction = _Reduction.legacy_get_string(size_average, reduce)
  3330. expanded_input, expanded_target = torch.broadcast_tensors(input, target)
  3331. if weight is not None:
  3332. if weight.size() != input.size():
  3333. raise ValueError("Weights and input must have the same size.")
  3334. # Perform weighted MSE loss manually
  3335. squared_errors = torch.pow(expanded_input - expanded_target, 2)
  3336. weighted_squared_errors = squared_errors * weight
  3337. if reduction == "none":
  3338. return weighted_squared_errors
  3339. elif reduction == "sum":
  3340. return torch.sum(weighted_squared_errors)
  3341. elif reduction == "mean":
  3342. return torch.sum(weighted_squared_errors) / torch.sum(weight)
  3343. else:
  3344. raise ValueError(
  3345. f"Invalid reduction mode: {reduction}. Expected one of 'none', 'mean', 'sum'."
  3346. )
  3347. else:
  3348. return torch._C._nn.mse_loss(
  3349. expanded_input,
  3350. expanded_target,
  3351. # pyrefly: ignore [bad-argument-type]
  3352. _Reduction.get_enum(reduction),
  3353. )
  3354. def margin_ranking_loss(
  3355. input1: Tensor,
  3356. input2: Tensor,
  3357. target: Tensor,
  3358. margin: float = 0,
  3359. size_average: Optional[bool] = None,
  3360. reduce: Optional[bool] = None,
  3361. reduction: str = "mean",
  3362. ) -> Tensor: # noqa: D400,D402
  3363. r"""Compute the margin ranking loss.
  3364. See :class:`~torch.nn.MarginRankingLoss` for details.
  3365. Args:
  3366. input1 (Tensor): Predicted values.
  3367. input2 (Tensor): Predicted values.
  3368. target (Tensor): Ground truth values.
  3369. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3370. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3371. reduction (str, optional): Specifies the reduction to apply to the output:
  3372. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3373. 'sum': the output will be summed. 'none': no reduction will be applied.
  3374. Default: 'mean'.
  3375. Returns:
  3376. Tensor: Margin ranking loss.
  3377. """
  3378. if has_torch_function_variadic(input1, input2, target):
  3379. return handle_torch_function(
  3380. margin_ranking_loss,
  3381. (input1, input2, target),
  3382. input1,
  3383. input2,
  3384. target,
  3385. margin=margin,
  3386. size_average=size_average,
  3387. reduce=reduce,
  3388. reduction=reduction,
  3389. )
  3390. if size_average is not None or reduce is not None:
  3391. reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
  3392. else:
  3393. reduction_enum = _Reduction.get_enum(reduction)
  3394. if input1.dim() != input2.dim() or input1.dim() != target.dim():
  3395. raise RuntimeError(
  3396. f"margin_ranking_loss : All input tensors should have same dimension but got sizes: "
  3397. f"input1: {input1.size()}, input2: {input2.size()}, target: {target.size()} "
  3398. )
  3399. return torch.margin_ranking_loss(input1, input2, target, margin, reduction_enum)
  3400. def hinge_embedding_loss(
  3401. input: Tensor,
  3402. target: Tensor,
  3403. margin: float = 1.0,
  3404. size_average: Optional[bool] = None,
  3405. reduce: Optional[bool] = None,
  3406. reduction: str = "mean",
  3407. ) -> Tensor: # noqa: D400,D402
  3408. r"""Compute the hinge embedding loss.
  3409. See :class:`~torch.nn.HingeEmbeddingLoss` for details.
  3410. Args:
  3411. input (Tensor): Predicted values.
  3412. target (Tensor): Ground truth values.
  3413. margin (float, optional): Margin for hinge loss. Has a default value of 1.
  3414. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3415. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3416. reduction (str, optional): Specifies the reduction to apply to the output:
  3417. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3418. 'sum': the output will be summed. 'none': no reduction will be applied.
  3419. Default: 'mean'.
  3420. Returns:
  3421. Tensor: Hinge embedding loss.
  3422. """
  3423. if has_torch_function_variadic(input, target):
  3424. return handle_torch_function(
  3425. hinge_embedding_loss,
  3426. (input, target),
  3427. input,
  3428. target,
  3429. margin=margin,
  3430. size_average=size_average,
  3431. reduce=reduce,
  3432. reduction=reduction,
  3433. )
  3434. if size_average is not None or reduce is not None:
  3435. reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
  3436. else:
  3437. reduction_enum = _Reduction.get_enum(reduction)
  3438. return torch.hinge_embedding_loss(input, target, margin, reduction_enum)
  3439. def multilabel_margin_loss(
  3440. input: Tensor,
  3441. target: Tensor,
  3442. size_average: Optional[bool] = None,
  3443. reduce: Optional[bool] = None,
  3444. reduction: str = "mean",
  3445. ) -> Tensor: # noqa: D400,D402
  3446. r"""Compute the multilabel margin loss.
  3447. See :class:`~torch.nn.MultiLabelMarginLoss` for details.
  3448. Args:
  3449. input (Tensor): Predicted values.
  3450. target (Tensor): Ground truth values.
  3451. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3452. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3453. reduction (str, optional): Specifies the reduction to apply to the output:
  3454. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3455. 'sum': the output will be summed. 'none': no reduction will be applied.
  3456. Default: 'mean'.
  3457. Returns:
  3458. Tensor: Mutilabel margin loss.
  3459. """
  3460. if has_torch_function_variadic(input, target):
  3461. return handle_torch_function(
  3462. multilabel_margin_loss,
  3463. (input, target),
  3464. input,
  3465. target,
  3466. size_average=size_average,
  3467. reduce=reduce,
  3468. reduction=reduction,
  3469. )
  3470. if size_average is not None or reduce is not None:
  3471. reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
  3472. else:
  3473. reduction_enum = _Reduction.get_enum(reduction)
  3474. # pyrefly: ignore [bad-argument-type]
  3475. return torch._C._nn.multilabel_margin_loss(input, target, reduction_enum)
  3476. def soft_margin_loss(
  3477. input: Tensor,
  3478. target: Tensor,
  3479. size_average: Optional[bool] = None,
  3480. reduce: Optional[bool] = None,
  3481. reduction: str = "mean",
  3482. ) -> Tensor: # noqa: D400,D402
  3483. r"""Compute the soft margin loss.
  3484. See :class:`~torch.nn.SoftMarginLoss` for details.
  3485. Args:
  3486. input (Tensor): Predicted values.
  3487. target (Tensor): Ground truth values.
  3488. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3489. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3490. reduction (str, optional): Specifies the reduction to apply to the output:
  3491. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3492. 'sum': the output will be summed. 'none': no reduction will be applied.
  3493. Default: 'mean'.
  3494. Returns:
  3495. Tensor: Soft margin loss.
  3496. """
  3497. if has_torch_function_variadic(input, target):
  3498. return handle_torch_function(
  3499. soft_margin_loss,
  3500. (input, target),
  3501. input,
  3502. target,
  3503. size_average=size_average,
  3504. reduce=reduce,
  3505. reduction=reduction,
  3506. )
  3507. if size_average is not None or reduce is not None:
  3508. reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
  3509. else:
  3510. reduction_enum = _Reduction.get_enum(reduction)
  3511. # pyrefly: ignore [bad-argument-type]
  3512. return torch._C._nn.soft_margin_loss(input, target, reduction_enum)
  3513. def multilabel_soft_margin_loss(
  3514. input: Tensor,
  3515. target: Tensor,
  3516. weight: Optional[Tensor] = None,
  3517. size_average: Optional[bool] = None,
  3518. reduce: Optional[bool] = None,
  3519. reduction: str = "mean",
  3520. ) -> Tensor: # noqa: D400,D402
  3521. r"""Compute the multilabel soft margin loss.
  3522. See :class:`~torch.nn.MultiLabelSoftMarginLoss` for details.
  3523. Args:
  3524. input (Tensor): Predicted values.
  3525. target (Tensor): Ground truth values.
  3526. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3527. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3528. reduction (str, optional): Specifies the reduction to apply to the output:
  3529. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3530. 'sum': the output will be summed. 'none': no reduction will be applied.
  3531. Default: 'mean'.
  3532. Returns:
  3533. Tensor: Mutilabel soft margin loss.
  3534. """
  3535. if has_torch_function_variadic(input, target, weight):
  3536. return handle_torch_function(
  3537. multilabel_soft_margin_loss,
  3538. (input, target, weight),
  3539. input,
  3540. target,
  3541. weight=weight,
  3542. size_average=size_average,
  3543. reduce=reduce,
  3544. reduction=reduction,
  3545. )
  3546. if size_average is not None or reduce is not None:
  3547. reduction = _Reduction.legacy_get_string(size_average, reduce)
  3548. loss = -(target * logsigmoid(input) + (1 - target) * logsigmoid(-input))
  3549. if weight is not None:
  3550. loss = loss * weight
  3551. class_dim = input.dim() - 1
  3552. C = input.size(class_dim)
  3553. loss = loss.sum(dim=class_dim) / C # only return N loss values
  3554. if reduction == "none":
  3555. ret = loss
  3556. elif reduction == "mean":
  3557. ret = loss.mean()
  3558. elif reduction == "sum":
  3559. ret = loss.sum()
  3560. else:
  3561. ret = input
  3562. raise ValueError(reduction + " is not valid")
  3563. return ret
  3564. def cosine_embedding_loss(
  3565. input1: Tensor,
  3566. input2: Tensor,
  3567. target: Tensor,
  3568. margin: float = 0,
  3569. size_average: Optional[bool] = None,
  3570. reduce: Optional[bool] = None,
  3571. reduction: str = "mean",
  3572. ) -> Tensor: # noqa: D400,D402
  3573. r"""Compute the cosine embedding loss.
  3574. See :class:`~torch.nn.CosineEmbeddingLoss` for details.
  3575. Args:
  3576. input1 (Tensor): Predicted values.
  3577. input2 (Tensor): Predicted values.
  3578. target (Tensor): Ground truth values.
  3579. margin (float, optional): Margin for cosine embedding. Has a default value of 0.
  3580. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3581. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3582. reduction (str, optional): Specifies the reduction to apply to the output:
  3583. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3584. 'sum': the output will be summed. 'none': no reduction will be applied.
  3585. Default: 'mean'.
  3586. Returns:
  3587. Tensor: Cosine embedding loss.
  3588. """
  3589. if has_torch_function_variadic(input1, input2, target):
  3590. return handle_torch_function(
  3591. cosine_embedding_loss,
  3592. (input1, input2, target),
  3593. input1,
  3594. input2,
  3595. target,
  3596. margin=margin,
  3597. size_average=size_average,
  3598. reduce=reduce,
  3599. reduction=reduction,
  3600. )
  3601. if size_average is not None or reduce is not None:
  3602. reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
  3603. else:
  3604. reduction_enum = _Reduction.get_enum(reduction)
  3605. return torch.cosine_embedding_loss(input1, input2, target, margin, reduction_enum)
  3606. def multi_margin_loss(
  3607. input: Tensor,
  3608. target: Tensor,
  3609. p: int = 1,
  3610. margin: float = 1.0,
  3611. weight: Optional[Tensor] = None,
  3612. size_average: Optional[bool] = None,
  3613. reduce: Optional[bool] = None,
  3614. reduction: str = "mean",
  3615. ) -> Tensor: # noqa: D400,D402
  3616. r"""Compute the multi margin loss, with optional weighting.
  3617. See :class:`~torch.nn.MultiMarginLoss` for details.
  3618. Args:
  3619. input (Tensor): Predicted values.
  3620. target (Tensor): Ground truth values.
  3621. p (int, optional): Has a default value of 1. 1 and 2 are the only supported values.
  3622. margin (float, optional): Margin for multi margin loss. Has a default value of 1.
  3623. weight (Tensor, optional): Weights for each sample. Default: None.
  3624. size_average (bool, optional): Deprecated (see :attr:`reduction`).
  3625. reduce (bool, optional): Deprecated (see :attr:`reduction`).
  3626. reduction (str, optional): Specifies the reduction to apply to the output:
  3627. 'none' | 'mean' | 'sum'. 'mean': the mean of the output is taken.
  3628. 'sum': the output will be summed. 'none': no reduction will be applied.
  3629. Default: 'mean'.
  3630. Returns:
  3631. Tensor: Multi margin loss (optionally weighted).
  3632. """
  3633. if has_torch_function_variadic(input, target, weight):
  3634. return handle_torch_function(
  3635. multi_margin_loss,
  3636. (input, target, weight),
  3637. input,
  3638. target,
  3639. p=p,
  3640. margin=margin,
  3641. weight=weight,
  3642. size_average=size_average,
  3643. reduce=reduce,
  3644. reduction=reduction,
  3645. )
  3646. if size_average is not None or reduce is not None:
  3647. reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
  3648. else:
  3649. reduction_enum = _Reduction.get_enum(reduction)
  3650. if p != 1 and p != 2:
  3651. raise ValueError("only p == 1 and p == 2 supported")
  3652. if weight is not None:
  3653. if weight.dim() != 1:
  3654. raise ValueError("weight must be one-dimensional")
  3655. return torch._C._nn.multi_margin_loss(
  3656. input,
  3657. target,
  3658. p,
  3659. margin,
  3660. weight,
  3661. # pyrefly: ignore [bad-argument-type]
  3662. reduction_enum,
  3663. )
  3664. pixel_shuffle = _add_docstr(
  3665. torch.pixel_shuffle,
  3666. r"""
  3667. pixel_shuffle(input, upscale_factor) -> Tensor
  3668. Rearranges elements in a tensor of shape :math:`(*, C \times r^2, H, W)` to a
  3669. tensor of shape :math:`(*, C, H \times r, W \times r)`, where r is the :attr:`upscale_factor`.
  3670. See :class:`~torch.nn.PixelShuffle` for details.
  3671. Args:
  3672. input (Tensor): the input tensor
  3673. upscale_factor (int): factor to increase spatial resolution by
  3674. Examples::
  3675. >>> input = torch.randn(1, 9, 4, 4)
  3676. >>> output = torch.nn.functional.pixel_shuffle(input, 3)
  3677. >>> print(output.size())
  3678. torch.Size([1, 1, 12, 12])
  3679. """,
  3680. )
  3681. pixel_unshuffle = _add_docstr(
  3682. torch.pixel_unshuffle,
  3683. r"""
  3684. pixel_unshuffle(input, downscale_factor) -> Tensor
  3685. Reverses the :class:`~torch.nn.PixelShuffle` operation by rearranging elements in a
  3686. tensor of shape :math:`(*, C, H \times r, W \times r)` to a tensor of shape
  3687. :math:`(*, C \times r^2, H, W)`, where r is the :attr:`downscale_factor`.
  3688. See :class:`~torch.nn.PixelUnshuffle` for details.
  3689. Args:
  3690. input (Tensor): the input tensor
  3691. downscale_factor (int): factor to increase spatial resolution by
  3692. Examples::
  3693. >>> input = torch.randn(1, 1, 12, 12)
  3694. >>> output = torch.nn.functional.pixel_unshuffle(input, 3)
  3695. >>> print(output.size())
  3696. torch.Size([1, 9, 4, 4])
  3697. """,
  3698. )
  3699. channel_shuffle = _add_docstr(
  3700. torch.channel_shuffle,
  3701. r"""
  3702. channel_shuffle(input, groups) -> Tensor
  3703. Divide the channels in a tensor of shape :math:`(*, C , H, W)`
  3704. into g groups and rearrange them as :math:`(*, C \frac g, g, H, W)`,
  3705. while keeping the original tensor shape.
  3706. See :class:`~torch.nn.ChannelShuffle` for details.
  3707. Args:
  3708. input (Tensor): the input tensor
  3709. groups (int): number of groups to divide channels in and rearrange.
  3710. Examples::
  3711. >>> input = torch.randn(1, 4, 2, 2)
  3712. >>> print(input)
  3713. [[[[1, 2],
  3714. [3, 4]],
  3715. [[5, 6],
  3716. [7, 8]],
  3717. [[9, 10],
  3718. [11, 12]],
  3719. [[13, 14],
  3720. [15, 16]],
  3721. ]]
  3722. >>> output = torch.nn.functional.channel_shuffle(input, 2)
  3723. >>> print(output)
  3724. [[[[1, 2],
  3725. [3, 4]],
  3726. [[9, 10],
  3727. [11, 12]],
  3728. [[5, 6],
  3729. [7, 8]],
  3730. [[13, 14],
  3731. [15, 16]],
  3732. ]]
  3733. """,
  3734. )
  3735. native_channel_shuffle = _add_docstr(
  3736. torch.native_channel_shuffle,
  3737. r"""
  3738. native_channel_shuffle(input, groups) -> Tensor
  3739. Native kernel level implementation of the `channel_shuffle`.
  3740. This function might become private in future releases, use with caution.
  3741. Divide the channels in a tensor of shape :math:`(*, C , H, W)`
  3742. into g groups and rearrange them as :math:`(*, C \frac g, g, H, W)`,
  3743. while keeping the original tensor shape.
  3744. See :class:`~torch.nn.ChannelShuffle` for details.
  3745. Args:
  3746. input (Tensor): the input tensor
  3747. groups (int): number of groups to divide channels in and rearrange.
  3748. Examples::
  3749. >>> input = torch.randn(1, 4, 2, 2)
  3750. >>> print(input)
  3751. [[[[1, 2],
  3752. [3, 4]],
  3753. [[5, 6],
  3754. [7, 8]],
  3755. [[9, 10],
  3756. [11, 12]],
  3757. [[13, 14],
  3758. [15, 16]],
  3759. ]]
  3760. >>> output = torch.nn.functional.native_channel_shuffle(input, 2)
  3761. >>> print(output)
  3762. [[[[1, 2],
  3763. [3, 4]],
  3764. [[9, 10],
  3765. [11, 12]],
  3766. [[5, 6],
  3767. [7, 8]],
  3768. [[13, 14],
  3769. [15, 16]],
  3770. ]]
  3771. """,
  3772. )
  3773. @_overload
  3774. def upsample( # noqa: F811
  3775. input: Tensor,
  3776. size: Optional[int] = None,
  3777. scale_factor: Optional[float] = None,
  3778. mode: str = "nearest",
  3779. align_corners: Optional[bool] = None,
  3780. # pyrefly: ignore [bad-return]
  3781. ) -> Tensor: # noqa: B950
  3782. pass
  3783. @_overload
  3784. def upsample( # noqa: F811
  3785. input: Tensor,
  3786. size: Optional[list[int]] = None,
  3787. scale_factor: Optional[float] = None,
  3788. mode: str = "nearest",
  3789. align_corners: Optional[bool] = None,
  3790. # pyrefly: ignore [bad-return]
  3791. ) -> Tensor: # noqa: B950
  3792. pass
  3793. def upsample( # noqa: F811
  3794. input,
  3795. size=None,
  3796. scale_factor=None,
  3797. mode="nearest",
  3798. align_corners=None,
  3799. ):
  3800. r"""Upsample input.
  3801. Provided tensor is upsampled to either the given :attr:`size` or the given
  3802. :attr:`scale_factor`
  3803. .. warning::
  3804. This function is deprecated in favor of :func:`torch.nn.functional.interpolate`.
  3805. This is equivalent with ``nn.functional.interpolate(...)``.
  3806. Note:
  3807. {backward_reproducibility_note}
  3808. The algorithm used for upsampling is determined by :attr:`mode`.
  3809. Currently temporal, spatial and volumetric upsampling are supported, i.e.
  3810. expected inputs are 3-D, 4-D or 5-D in shape.
  3811. The input dimensions are interpreted in the form:
  3812. `mini-batch x channels x [optional depth] x [optional height] x width`.
  3813. The modes available for upsampling are: `nearest`, `linear` (3D-only),
  3814. `bilinear`, `bicubic` (4D-only), `trilinear` (5D-only)
  3815. Args:
  3816. input (Tensor): the input tensor
  3817. size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):
  3818. output spatial size.
  3819. scale_factor (float or Tuple[float]): multiplier for spatial size. Has to match input size if it is a tuple.
  3820. mode (str): algorithm used for upsampling:
  3821. ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` |
  3822. ``'trilinear'``. Default: ``'nearest'``
  3823. align_corners (bool, optional): Geometrically, we consider the pixels of the
  3824. input and output as squares rather than points.
  3825. If set to ``True``, the input and output tensors are aligned by the
  3826. center points of their corner pixels, preserving the values at the corner pixels.
  3827. If set to ``False``, the input and output tensors are aligned by the corner
  3828. points of their corner pixels, and the interpolation uses edge value padding
  3829. for out-of-boundary values, making this operation *independent* of input size
  3830. when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode`
  3831. is ``'linear'``, ``'bilinear'``, ``'bicubic'`` or ``'trilinear'``.
  3832. Default: ``False``
  3833. .. note::
  3834. With ``mode='bicubic'``, it's possible to cause overshoot, in other words it can produce
  3835. negative values or values greater than 255 for images.
  3836. Explicitly call ``result.clamp(min=0, max=255)`` if you want to reduce the overshoot
  3837. when displaying the image.
  3838. .. warning::
  3839. With ``align_corners = True``, the linearly interpolating modes
  3840. (`linear`, `bilinear`, and `trilinear`) don't proportionally align the
  3841. output and input pixels, and thus the output values can depend on the
  3842. input size. This was the default behavior for these modes up to version
  3843. 0.3.1. Since then, the default behavior is ``align_corners = False``.
  3844. See :class:`~torch.nn.Upsample` for concrete examples on how this
  3845. affects the outputs.
  3846. """
  3847. warnings.warn(
  3848. "`nn.functional.upsample` is deprecated. "
  3849. "Use `nn.functional.interpolate` instead.",
  3850. stacklevel=2,
  3851. )
  3852. return interpolate(input, size, scale_factor, mode, align_corners)
  3853. if upsample.__doc__:
  3854. upsample.__doc__ = upsample.__doc__.format(**reproducibility_notes)
  3855. def _is_integer(x) -> bool:
  3856. r"""Type check the input number is an integer.
  3857. Will return True for int, SymInt, Numpy integers and Tensors with integer elements.
  3858. """
  3859. if isinstance(x, (int, torch.SymInt)):
  3860. return True
  3861. if np is not None and isinstance(x, np.integer):
  3862. return True
  3863. return isinstance(x, Tensor) and not x.is_floating_point()
  3864. @_overload
  3865. def interpolate( # noqa: F811
  3866. input: Tensor,
  3867. size: Optional[int] = None,
  3868. scale_factor: Optional[list[float]] = None,
  3869. mode: str = "nearest",
  3870. align_corners: Optional[bool] = None,
  3871. recompute_scale_factor: Optional[bool] = None,
  3872. antialias: bool = False,
  3873. # pyrefly: ignore [bad-return]
  3874. ) -> Tensor: # noqa: B950
  3875. pass
  3876. @_overload
  3877. def interpolate( # noqa: F811
  3878. input: Tensor,
  3879. size: Optional[list[int]] = None,
  3880. scale_factor: Optional[list[float]] = None,
  3881. mode: str = "nearest",
  3882. align_corners: Optional[bool] = None,
  3883. recompute_scale_factor: Optional[bool] = None,
  3884. antialias: bool = False,
  3885. # pyrefly: ignore [bad-return]
  3886. ) -> Tensor: # noqa: B950
  3887. pass
  3888. @_overload
  3889. def interpolate( # noqa: F811
  3890. input: Tensor,
  3891. size: Optional[int] = None,
  3892. scale_factor: Optional[float] = None,
  3893. mode: str = "nearest",
  3894. align_corners: Optional[bool] = None,
  3895. recompute_scale_factor: Optional[bool] = None,
  3896. antialias: bool = False,
  3897. # pyrefly: ignore [bad-return]
  3898. ) -> Tensor: # noqa: B950
  3899. pass
  3900. @_overload
  3901. def interpolate( # noqa: F811
  3902. input: Tensor,
  3903. size: Optional[list[int]] = None,
  3904. scale_factor: Optional[float] = None,
  3905. mode: str = "nearest",
  3906. align_corners: Optional[bool] = None,
  3907. recompute_scale_factor: Optional[bool] = None,
  3908. antialias: bool = False,
  3909. # pyrefly: ignore [bad-return]
  3910. ) -> Tensor:
  3911. pass
  3912. def interpolate( # noqa: F811
  3913. input: Tensor,
  3914. size: Optional[int] = None,
  3915. scale_factor: Optional[list[float]] = None,
  3916. mode: str = "nearest",
  3917. align_corners: Optional[bool] = None,
  3918. recompute_scale_factor: Optional[bool] = None,
  3919. antialias: bool = False,
  3920. ) -> Tensor: # noqa: B950
  3921. r"""Down/up samples the input.
  3922. Tensor interpolated to either the given :attr:`size` or the given
  3923. :attr:`scale_factor`
  3924. The algorithm used for interpolation is determined by :attr:`mode`.
  3925. Currently temporal, spatial and volumetric sampling are supported, i.e.
  3926. expected inputs are 3-D, 4-D or 5-D in shape.
  3927. The input dimensions are interpreted in the form:
  3928. `mini-batch x channels x [optional depth] x [optional height] x width`.
  3929. The modes available for resizing are: `nearest`, `linear` (3D-only),
  3930. `bilinear`, `bicubic` (4D-only), `trilinear` (5D-only), `area`, `nearest-exact`
  3931. Args:
  3932. input (Tensor): the input tensor
  3933. size (int or Tuple[int] or Tuple[int, int] or Tuple[int, int, int]):
  3934. output spatial size.
  3935. scale_factor (float or Tuple[float]): multiplier for spatial size. If `scale_factor` is a tuple,
  3936. its length has to match the number of spatial dimensions; `input.dim() - 2`.
  3937. mode (str): algorithm used for upsampling:
  3938. ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` |
  3939. ``'trilinear'`` | ``'area'`` | ``'nearest-exact'``. Default: ``'nearest'``
  3940. align_corners (bool, optional): Geometrically, we consider the pixels of the
  3941. input and output as squares rather than points.
  3942. If set to ``True``, the input and output tensors are aligned by the
  3943. center points of their corner pixels, preserving the values at the corner pixels.
  3944. If set to ``False``, the input and output tensors are aligned by the corner
  3945. points of their corner pixels, and the interpolation uses edge value padding
  3946. for out-of-boundary values, making this operation *independent* of input size
  3947. when :attr:`scale_factor` is kept the same. This only has an effect when :attr:`mode`
  3948. is ``'linear'``, ``'bilinear'``, ``'bicubic'`` or ``'trilinear'``.
  3949. Default: ``None``. When ``None`` and :attr:`mode` is one of the linear modes,
  3950. it is treated as ``False``.
  3951. recompute_scale_factor (bool, optional): recompute the scale_factor for use in the
  3952. interpolation calculation. If `recompute_scale_factor` is ``True``, then
  3953. `scale_factor` must be passed in and `scale_factor` is used to compute the
  3954. output `size`. The computed output `size` will be used to infer new scales for
  3955. the interpolation. Note that when `scale_factor` is floating-point, it may differ
  3956. from the recomputed `scale_factor` due to rounding and precision issues.
  3957. If `recompute_scale_factor` is ``False``, then `size` or `scale_factor` will
  3958. be used directly for interpolation. Default: ``None``.
  3959. antialias (bool, optional): flag to apply anti-aliasing. Default: ``False``. Using anti-alias
  3960. option together with ``align_corners=False``, interpolation result would match Pillow
  3961. result for downsampling operation. Supported modes: ``'bilinear'``, ``'bicubic'``.
  3962. .. note::
  3963. With ``mode='bicubic'``, it's possible to cause overshoot. For some dtypes, it can produce
  3964. negative values or values greater than 255 for images. Explicitly call ``result.clamp(min=0,max=255)``
  3965. if you want to reduce the overshoot when displaying the image.
  3966. For ``uint8`` inputs, it already performs saturating cast operation. So, no manual `clamp` operation is needed.
  3967. .. note::
  3968. Mode ``mode='nearest-exact'`` matches Scikit-Image and PIL nearest neighbours interpolation
  3969. algorithms and fixes known issues with ``mode='nearest'``. This mode is introduced to keep
  3970. backward compatibility.
  3971. Mode ``mode='nearest'`` matches buggy OpenCV's ``INTER_NEAREST`` interpolation algorithm.
  3972. .. note::
  3973. The gradients for the dtype ``float16`` on CUDA may be inaccurate in the upsample operation
  3974. when using modes ``['linear', 'bilinear', 'bicubic', 'trilinear', 'area']``.
  3975. For more details, please refer to the discussion in
  3976. `issue#104157 <https://github.com/pytorch/pytorch/issues/104157>`_.
  3977. Note:
  3978. {backward_reproducibility_note}
  3979. """
  3980. if has_torch_function_unary(input):
  3981. return handle_torch_function(
  3982. interpolate,
  3983. (input,),
  3984. input,
  3985. size=size,
  3986. scale_factor=scale_factor,
  3987. mode=mode,
  3988. align_corners=align_corners,
  3989. recompute_scale_factor=recompute_scale_factor,
  3990. antialias=antialias,
  3991. )
  3992. if mode in ("nearest", "area", "nearest-exact"):
  3993. if align_corners is not None:
  3994. raise ValueError(
  3995. "align_corners option can only be set with the "
  3996. "interpolating modes: linear | bilinear | bicubic | trilinear"
  3997. )
  3998. else:
  3999. if align_corners is None:
  4000. align_corners = False
  4001. dim = input.dim() - 2 # Number of spatial dimensions.
  4002. # Process size and scale_factor. Validate that exactly one is set.
  4003. # Validate its length if it is a list, or expand it if it is a scalar.
  4004. # After this block, exactly one of output_size and scale_factors will
  4005. # be non-None, and it will be a list (or tuple).
  4006. if size is not None and scale_factor is not None:
  4007. raise ValueError("only one of size or scale_factor should be defined")
  4008. elif size is not None:
  4009. if scale_factor is not None:
  4010. raise AssertionError("scale_factor must be None when size is specified")
  4011. scale_factors = None
  4012. if isinstance(size, (list, tuple)):
  4013. if len(size) != dim:
  4014. raise ValueError(
  4015. "Input and output must have the same number of spatial dimensions, but got "
  4016. f"input with spatial dimensions of {list(input.shape[2:])} and output size of {size}. "
  4017. "Please provide input tensor in (N, C, d1, d2, ...,dK) format and "
  4018. "output size in (o1, o2, ...,oK) format."
  4019. )
  4020. if not torch.jit.is_scripting():
  4021. if not all(_is_integer(x) for x in size):
  4022. raise TypeError(
  4023. "expected size to be one of int or Tuple[int] or Tuple[int, int] or "
  4024. f"Tuple[int, int, int], but got size with types {[type(x) for x in size]}"
  4025. )
  4026. output_size = size
  4027. else:
  4028. output_size = [size for _ in range(dim)]
  4029. elif scale_factor is not None:
  4030. if size is not None:
  4031. raise AssertionError("size must be None when scale_factor is specified")
  4032. output_size = None
  4033. if isinstance(scale_factor, (list, tuple)):
  4034. if len(scale_factor) != dim:
  4035. raise ValueError(
  4036. "Input and scale_factor must have the same number of spatial dimensions, but "
  4037. f"got input with spatial dimensions of {list(input.shape[2:])} and "
  4038. f"scale_factor of shape {scale_factor}. "
  4039. "Please provide input tensor in (N, C, d1, d2, ...,dK) format and "
  4040. "scale_factor in (s1, s2, ...,sK) format."
  4041. )
  4042. scale_factors = scale_factor
  4043. else:
  4044. scale_factors = [scale_factor for _ in range(dim)]
  4045. else:
  4046. raise ValueError("either size or scale_factor should be defined")
  4047. if (
  4048. recompute_scale_factor is not None
  4049. and recompute_scale_factor
  4050. and size is not None
  4051. ):
  4052. raise ValueError(
  4053. "recompute_scale_factor is not meaningful with an explicit size."
  4054. )
  4055. # "area" mode always requires an explicit size rather than scale factor.
  4056. # Reuse the recompute_scale_factor code path.
  4057. if mode == "area" and output_size is None:
  4058. recompute_scale_factor = True
  4059. if recompute_scale_factor is not None and recompute_scale_factor:
  4060. # We compute output_size here, then un-set scale_factors.
  4061. # The C++ code will recompute it based on the (integer) output size.
  4062. if scale_factors is None:
  4063. raise AssertionError("scale_factors is unexpectedly None")
  4064. if not torch.jit.is_scripting() and torch._C._get_tracing_state():
  4065. # make scale_factor a tensor in tracing so constant doesn't get baked in
  4066. output_size = [
  4067. (
  4068. torch.floor(
  4069. (
  4070. # pyrefly: ignore [missing-attribute]
  4071. input.size(i + 2).float()
  4072. * torch.tensor(scale_factors[i], dtype=torch.float32)
  4073. ).float()
  4074. )
  4075. )
  4076. for i in range(dim)
  4077. ]
  4078. elif torch.jit.is_scripting():
  4079. output_size = [
  4080. math.floor(float(input.size(i + 2)) * scale_factors[i])
  4081. for i in range(dim)
  4082. ]
  4083. else:
  4084. output_size = [
  4085. _sym_int(input.size(i + 2) * scale_factors[i]) for i in range(dim)
  4086. ]
  4087. scale_factors = None
  4088. if antialias and not (mode in ("bilinear", "bicubic") and input.ndim == 4):
  4089. raise ValueError(
  4090. "Anti-alias option is restricted to bilinear and bicubic modes and requires a 4-D tensor as input"
  4091. )
  4092. if input.dim() == 3 and mode == "nearest":
  4093. # pyrefly: ignore [bad-argument-type]
  4094. return torch._C._nn.upsample_nearest1d(input, output_size, scale_factors)
  4095. if input.dim() == 4 and mode == "nearest":
  4096. # pyrefly: ignore [bad-argument-type]
  4097. return torch._C._nn.upsample_nearest2d(input, output_size, scale_factors)
  4098. if input.dim() == 5 and mode == "nearest":
  4099. # pyrefly: ignore [bad-argument-type]
  4100. return torch._C._nn.upsample_nearest3d(input, output_size, scale_factors)
  4101. if input.dim() == 3 and mode == "nearest-exact":
  4102. # pyrefly: ignore [bad-argument-type]
  4103. return torch._C._nn._upsample_nearest_exact1d(input, output_size, scale_factors)
  4104. if input.dim() == 4 and mode == "nearest-exact":
  4105. # pyrefly: ignore [bad-argument-type]
  4106. return torch._C._nn._upsample_nearest_exact2d(input, output_size, scale_factors)
  4107. if input.dim() == 5 and mode == "nearest-exact":
  4108. # pyrefly: ignore [bad-argument-type]
  4109. return torch._C._nn._upsample_nearest_exact3d(input, output_size, scale_factors)
  4110. if input.dim() == 3 and mode == "area":
  4111. if output_size is None:
  4112. raise AssertionError("output_size is unexpectedly None")
  4113. # pyrefly: ignore [bad-argument-type]
  4114. return adaptive_avg_pool1d(input, output_size)
  4115. if input.dim() == 4 and mode == "area":
  4116. if output_size is None:
  4117. raise AssertionError("output_size is unexpectedly None")
  4118. return adaptive_avg_pool2d(input, output_size)
  4119. if input.dim() == 5 and mode == "area":
  4120. if output_size is None:
  4121. raise AssertionError("output_size is unexpectedly None")
  4122. return adaptive_avg_pool3d(input, output_size)
  4123. if input.dim() == 3 and mode == "linear":
  4124. if align_corners is None:
  4125. raise AssertionError("align_corners is unexpectedly None")
  4126. return torch._C._nn.upsample_linear1d(
  4127. input,
  4128. # pyrefly: ignore [bad-argument-type]
  4129. output_size,
  4130. align_corners,
  4131. scale_factors,
  4132. )
  4133. if input.dim() == 4 and mode == "bilinear":
  4134. if align_corners is None:
  4135. raise AssertionError("align_corners is unexpectedly None")
  4136. if antialias:
  4137. return torch._C._nn._upsample_bilinear2d_aa(
  4138. input,
  4139. # pyrefly: ignore [bad-argument-type]
  4140. output_size,
  4141. align_corners,
  4142. scale_factors,
  4143. )
  4144. # Two levels are necessary to prevent TorchScript from touching
  4145. # are_deterministic_algorithms_enabled.
  4146. if not torch.jit.is_scripting():
  4147. if not input.is_cpu and torch.are_deterministic_algorithms_enabled():
  4148. # Use slow decomp whose backward will be in terms of index_put
  4149. # importlib is required because the import cannot be top level
  4150. # (cycle) and cannot be nested (TS doesn't support)
  4151. return importlib.import_module(
  4152. "torch._decomp.decompositions"
  4153. )._upsample_linear_vec(input, output_size, align_corners, scale_factors)
  4154. return torch._C._nn.upsample_bilinear2d(
  4155. input,
  4156. # pyrefly: ignore [bad-argument-type]
  4157. output_size,
  4158. align_corners,
  4159. scale_factors,
  4160. )
  4161. if input.dim() == 5 and mode == "trilinear":
  4162. if align_corners is None:
  4163. raise AssertionError("align_corners is unexpectedly None")
  4164. # Two levels are necessary to prevent TorchScript from touching
  4165. # are_deterministic_algorithms_enabled.
  4166. if not torch.jit.is_scripting():
  4167. if not input.is_cpu and torch.are_deterministic_algorithms_enabled():
  4168. # Use slow decomp whose backward will be in terms of index_put
  4169. # importlib is required because the import cannot be top level
  4170. # (cycle) and cannot be nested (TS doesn't support)
  4171. return importlib.import_module(
  4172. "torch._decomp.decompositions"
  4173. )._upsample_linear_vec(input, output_size, align_corners, scale_factors)
  4174. return torch._C._nn.upsample_trilinear3d(
  4175. input,
  4176. # pyrefly: ignore [bad-argument-type]
  4177. output_size,
  4178. align_corners,
  4179. scale_factors,
  4180. )
  4181. if input.dim() == 4 and mode == "bicubic":
  4182. if align_corners is None:
  4183. raise AssertionError("align_corners is unexpectedly None")
  4184. if antialias:
  4185. return torch._C._nn._upsample_bicubic2d_aa(
  4186. input,
  4187. # pyrefly: ignore [bad-argument-type]
  4188. output_size,
  4189. align_corners,
  4190. scale_factors,
  4191. )
  4192. return torch._C._nn.upsample_bicubic2d(
  4193. input,
  4194. # pyrefly: ignore [bad-argument-type]
  4195. output_size,
  4196. align_corners,
  4197. scale_factors,
  4198. )
  4199. if input.dim() == 3 and mode == "bilinear":
  4200. raise NotImplementedError("Got 3D input, but bilinear mode needs 4D input")
  4201. if input.dim() == 3 and mode == "trilinear":
  4202. raise NotImplementedError("Got 3D input, but trilinear mode needs 5D input")
  4203. if input.dim() == 4 and mode == "linear":
  4204. raise NotImplementedError("Got 4D input, but linear mode needs 3D input")
  4205. if input.dim() == 4 and mode == "trilinear":
  4206. raise NotImplementedError("Got 4D input, but trilinear mode needs 5D input")
  4207. if input.dim() == 5 and mode == "linear":
  4208. raise NotImplementedError("Got 5D input, but linear mode needs 3D input")
  4209. if input.dim() == 5 and mode == "bilinear":
  4210. raise NotImplementedError("Got 5D input, but bilinear mode needs 4D input")
  4211. raise NotImplementedError(
  4212. "Input Error: Only 3D, 4D and 5D input Tensors supported"
  4213. f" (got {input.dim()}D) for the modes: nearest | linear | bilinear | bicubic | trilinear | area | nearest-exact"
  4214. f" (got {mode})"
  4215. )
  4216. if interpolate.__doc__:
  4217. interpolate.__doc__ = interpolate.__doc__.format(**reproducibility_notes)
  4218. @_overload
  4219. def upsample_nearest( # noqa: F811
  4220. input: Tensor,
  4221. size: Optional[int] = None,
  4222. scale_factor: Optional[float] = None,
  4223. # pyrefly: ignore [bad-return]
  4224. ) -> Tensor:
  4225. pass
  4226. @_overload
  4227. def upsample_nearest( # noqa: F811
  4228. input: Tensor,
  4229. size: Optional[list[int]] = None,
  4230. scale_factor: Optional[float] = None,
  4231. # pyrefly: ignore [bad-return]
  4232. ) -> Tensor:
  4233. pass
  4234. def upsample_nearest(input, size=None, scale_factor=None): # noqa: F811
  4235. r"""Upsamples the input, using nearest neighbours' pixel values.
  4236. .. warning::
  4237. This function is deprecated in favor of :func:`torch.nn.functional.interpolate`.
  4238. This is equivalent with ``nn.functional.interpolate(..., mode='nearest')``.
  4239. Currently spatial and volumetric upsampling are supported (i.e. expected
  4240. inputs are 4 or 5 dimensional).
  4241. Args:
  4242. input (Tensor): input
  4243. size (int or Tuple[int, int] or Tuple[int, int, int]): output spatia
  4244. size.
  4245. scale_factor (int): multiplier for spatial size. Has to be an integer.
  4246. Note:
  4247. {backward_reproducibility_note}
  4248. """
  4249. # DeprecationWarning is ignored by default
  4250. warnings.warn(
  4251. "`nn.functional.upsample_nearest` is deprecated. "
  4252. "Use `nn.functional.interpolate` instead.",
  4253. stacklevel=2,
  4254. )
  4255. return interpolate(input, size, scale_factor, mode="nearest")
  4256. if upsample_nearest.__doc__:
  4257. upsample_nearest.__doc__ = upsample_nearest.__doc__.format(**reproducibility_notes)
  4258. @_overload
  4259. def upsample_bilinear( # noqa: F811
  4260. input: Tensor,
  4261. size: Optional[int] = None,
  4262. scale_factor: Optional[float] = None,
  4263. # pyrefly: ignore [bad-return]
  4264. ) -> Tensor:
  4265. pass
  4266. @_overload
  4267. def upsample_bilinear( # noqa: F811
  4268. input: Tensor,
  4269. size: Optional[list[int]] = None,
  4270. scale_factor: Optional[float] = None,
  4271. # pyrefly: ignore [bad-return]
  4272. ) -> Tensor:
  4273. pass
  4274. @_overload
  4275. def upsample_bilinear( # noqa: F811
  4276. input: Tensor,
  4277. size: Optional[int] = None,
  4278. scale_factor: Optional[list[float]] = None,
  4279. # pyrefly: ignore [bad-return]
  4280. ) -> Tensor:
  4281. pass
  4282. @_overload
  4283. def upsample_bilinear( # noqa: F811
  4284. input: Tensor,
  4285. size: Optional[list[int]] = None,
  4286. scale_factor: Optional[list[float]] = None,
  4287. # pyrefly: ignore [bad-return]
  4288. ) -> Tensor:
  4289. pass
  4290. def upsample_bilinear(input, size=None, scale_factor=None): # noqa: F811
  4291. r"""Upsamples the input, using bilinear upsampling.
  4292. .. warning::
  4293. This function is deprecated in favor of :func:`torch.nn.functional.interpolate`.
  4294. This is equivalent with
  4295. ``nn.functional.interpolate(..., mode='bilinear', align_corners=True)``.
  4296. Expected inputs are spatial (4 dimensional). Use `upsample_trilinear` for
  4297. volumetric (5 dimensional) inputs.
  4298. Args:
  4299. input (Tensor): input
  4300. size (int or Tuple[int, int]): output spatial size.
  4301. scale_factor (int or Tuple[int, int]): multiplier for spatial size
  4302. Note:
  4303. {backward_reproducibility_note}
  4304. """
  4305. # DeprecationWarning is ignored by default
  4306. warnings.warn(
  4307. "`nn.functional.upsample_bilinear` is deprecated. "
  4308. "Use `nn.functional.interpolate` instead.",
  4309. stacklevel=2,
  4310. )
  4311. return interpolate(input, size, scale_factor, mode="bilinear", align_corners=True)
  4312. if upsample_bilinear.__doc__:
  4313. upsample_bilinear.__doc__ = upsample_bilinear.__doc__.format(
  4314. **reproducibility_notes
  4315. )
  4316. GRID_SAMPLE_INTERPOLATION_MODES = {
  4317. "bilinear": 0,
  4318. "nearest": 1,
  4319. "bicubic": 2,
  4320. }
  4321. GRID_SAMPLE_PADDING_MODES = {
  4322. "zeros": 0,
  4323. "border": 1,
  4324. "reflection": 2,
  4325. }
  4326. def grid_sample(
  4327. input: Tensor,
  4328. grid: Tensor,
  4329. mode: str = "bilinear",
  4330. padding_mode: str = "zeros",
  4331. align_corners: Optional[bool] = None,
  4332. ) -> Tensor:
  4333. r"""Compute grid sample.
  4334. Given an :attr:`input` and a flow-field :attr:`grid`, computes the
  4335. ``output`` using :attr:`input` values and pixel locations from :attr:`grid`.
  4336. Currently, only spatial (4-D) and volumetric (5-D) :attr:`input` are
  4337. supported.
  4338. In the spatial (4-D) case, for :attr:`input` with shape
  4339. :math:`(N, C, H_\text{in}, W_\text{in})` and :attr:`grid` with shape
  4340. :math:`(N, H_\text{out}, W_\text{out}, 2)`, the output will have shape
  4341. :math:`(N, C, H_\text{out}, W_\text{out})`.
  4342. For each output location ``output[n, :, h, w]``, the size-2 vector
  4343. ``grid[n, h, w]`` specifies :attr:`input` pixel locations ``x`` and ``y``,
  4344. which are used to interpolate the output value ``output[n, :, h, w]``.
  4345. In the case of 5D inputs, ``grid[n, d, h, w]`` specifies the
  4346. ``x``, ``y``, ``z`` pixel locations for interpolating
  4347. ``output[n, :, d, h, w]``. :attr:`mode` argument specifies ``nearest`` or
  4348. ``bilinear`` interpolation method to sample the input pixels.
  4349. :attr:`grid` specifies the sampling pixel locations normalized by the
  4350. :attr:`input` spatial dimensions. Therefore, it should have most values in
  4351. the range of ``[-1, 1]``. For example, values ``x = -1, y = -1`` is the
  4352. left-top pixel of :attr:`input`, and values ``x = 1, y = 1`` is the
  4353. right-bottom pixel of :attr:`input`.
  4354. If :attr:`grid` has values outside the range of ``[-1, 1]``, the corresponding
  4355. outputs are handled as defined by :attr:`padding_mode`. Options are
  4356. * ``padding_mode="zeros"``: use ``0`` for out-of-bound grid locations,
  4357. * ``padding_mode="border"``: use border values for out-of-bound grid locations,
  4358. * ``padding_mode="reflection"``: use values at locations reflected by
  4359. the border for out-of-bound grid locations. For location far away
  4360. from the border, it will keep being reflected until becoming in bound,
  4361. e.g., (normalized) pixel location ``x = -3.5`` reflects by border ``-1``
  4362. and becomes ``x' = 1.5``, then reflects by border ``1`` and becomes
  4363. ``x'' = -0.5``.
  4364. Note:
  4365. This function is often used in conjunction with :func:`affine_grid`
  4366. to build `Spatial Transformer Networks`_ .
  4367. Note:
  4368. When using the CUDA backend, this operation may induce nondeterministic
  4369. behaviour in its backward pass that is not easily switched off.
  4370. Please see the notes on :doc:`/notes/randomness` for background.
  4371. Note:
  4372. NaN values in :attr:`grid` would be interpreted as ``-1``.
  4373. Args:
  4374. input (Tensor): input of shape :math:`(N, C, H_\text{in}, W_\text{in})` (4-D case)
  4375. or :math:`(N, C, D_\text{in}, H_\text{in}, W_\text{in})` (5-D case)
  4376. grid (Tensor): flow-field of shape :math:`(N, H_\text{out}, W_\text{out}, 2)` (4-D case)
  4377. or :math:`(N, D_\text{out}, H_\text{out}, W_\text{out}, 3)` (5-D case)
  4378. mode (str): interpolation mode to calculate output values
  4379. ``'bilinear'`` | ``'nearest'`` | ``'bicubic'``. Default: ``'bilinear'``
  4380. Note: ``mode='bicubic'`` supports only 4-D input.
  4381. When ``mode='bilinear'`` and the input is 5-D, the interpolation mode
  4382. used internally will actually be trilinear. However, when the input is 4-D,
  4383. the interpolation mode will legitimately be bilinear.
  4384. padding_mode (str): padding mode for outside grid values
  4385. ``'zeros'`` | ``'border'`` | ``'reflection'``. Default: ``'zeros'``
  4386. align_corners (bool, optional): Geometrically, we consider the pixels of the
  4387. input as squares rather than points.
  4388. If set to ``True``, the extrema (``-1`` and ``1``) are considered as referring
  4389. to the center points of the input's corner pixels. If set to ``False``, they
  4390. are instead considered as referring to the corner points of the input's corner
  4391. pixels, making the sampling more resolution agnostic.
  4392. This option parallels the ``align_corners`` option in
  4393. :func:`interpolate`, and so whichever option is used here
  4394. should also be used there to resize the input image before grid sampling.
  4395. Default: ``False``
  4396. Returns:
  4397. output (Tensor): output Tensor
  4398. .. _`Spatial Transformer Networks`:
  4399. https://arxiv.org/abs/1506.02025
  4400. .. warning::
  4401. When ``align_corners = True``, the grid positions depend on the pixel
  4402. size relative to the input image size, and so the locations sampled by
  4403. :func:`grid_sample` will differ for the same input given at different
  4404. resolutions (that is, after being upsampled or downsampled).
  4405. The default behavior up to version 1.2.0 was ``align_corners = True``.
  4406. Since then, the default behavior has been changed to ``align_corners = False``,
  4407. in order to bring it in line with the default for :func:`interpolate`.
  4408. .. note::
  4409. ``mode='bicubic'`` is implemented using the `cubic convolution algorithm`_ with :math:`\alpha=-0.75`.
  4410. The constant :math:`\alpha` might be different from packages to packages.
  4411. For example, `PIL`_ and `OpenCV`_ use -0.5 and -0.75 respectively.
  4412. This algorithm may "overshoot" the range of values it's interpolating.
  4413. For example, it may produce negative values or values greater than 255 when interpolating input in [0, 255].
  4414. Clamp the results with :func:`torch.clamp` to ensure they are within the valid range.
  4415. .. _`cubic convolution algorithm`: https://en.wikipedia.org/wiki/Bicubic_interpolation
  4416. .. _`PIL`: https://github.com/python-pillow/Pillow/blob/4634eafe3c695a014267eefdce830b4a825beed7/src/libImaging/Resample.c#L51
  4417. .. _`OpenCV`: https://github.com/opencv/opencv/blob/f345ed564a06178670750bad59526cfa4033be55/modules/imgproc/src/resize.cpp#L908
  4418. """
  4419. if has_torch_function_variadic(input, grid):
  4420. return handle_torch_function(
  4421. grid_sample,
  4422. (input, grid),
  4423. input,
  4424. grid,
  4425. mode=mode,
  4426. padding_mode=padding_mode,
  4427. align_corners=align_corners,
  4428. )
  4429. if mode != "bilinear" and mode != "nearest" and mode != "bicubic":
  4430. raise ValueError(
  4431. f"nn.functional.grid_sample(): expected mode to be 'bilinear', 'nearest' or 'bicubic', but got: '{mode}'"
  4432. )
  4433. if (
  4434. padding_mode != "zeros"
  4435. and padding_mode != "border"
  4436. and padding_mode != "reflection"
  4437. ):
  4438. raise ValueError(
  4439. "nn.functional.grid_sample(): expected padding_mode "
  4440. "to be 'zeros', 'border', or 'reflection', "
  4441. f"but got: '{padding_mode}'"
  4442. )
  4443. if mode == "bilinear":
  4444. mode_enum = 0
  4445. elif mode == "nearest":
  4446. mode_enum = 1
  4447. else: # mode == 'bicubic'
  4448. mode_enum = 2
  4449. if padding_mode == "zeros":
  4450. padding_mode_enum = 0
  4451. elif padding_mode == "border":
  4452. padding_mode_enum = 1
  4453. else: # padding_mode == 'reflection'
  4454. padding_mode_enum = 2
  4455. if align_corners is None:
  4456. warnings.warn(
  4457. "Default grid_sample and affine_grid behavior has changed "
  4458. "to align_corners=False since 1.3.0. Please specify "
  4459. "align_corners=True if the old behavior is desired. "
  4460. "See the documentation of grid_sample for details.",
  4461. stacklevel=2,
  4462. )
  4463. align_corners = False
  4464. return torch.grid_sampler(input, grid, mode_enum, padding_mode_enum, align_corners)
  4465. def affine_grid(
  4466. theta: Tensor,
  4467. size: list[int],
  4468. align_corners: Optional[bool] = None,
  4469. ) -> Tensor:
  4470. r"""Generate 2D or 3D flow field (sampling grid), given a batch of affine matrices :attr:`theta`.
  4471. .. note::
  4472. This function is often used in conjunction with :func:`grid_sample`
  4473. to build `Spatial Transformer Networks`_ .
  4474. Args:
  4475. theta (Tensor): input batch of affine matrices with shape
  4476. (:math:`N \times 2 \times 3`) for 2D or
  4477. (:math:`N \times 3 \times 4`) for 3D
  4478. size (torch.Size): the target output image size.
  4479. (:math:`N \times C \times H \times W` for 2D or
  4480. :math:`N \times C \times D \times H \times W` for 3D)
  4481. Example: torch.Size((32, 3, 24, 24))
  4482. align_corners (bool, optional): if ``True``, consider ``-1`` and ``1``
  4483. to refer to the centers of the corner pixels rather than the image corners.
  4484. Refer to :func:`grid_sample` for a more complete description.
  4485. A grid generated by :func:`affine_grid` should be passed to :func:`grid_sample`
  4486. with the same setting for this option.
  4487. Default: ``False``
  4488. Returns:
  4489. output (Tensor): output Tensor of size (:math:`N \times H \times W \times 2`)
  4490. .. _`Spatial Transformer Networks`:
  4491. https://arxiv.org/abs/1506.02025
  4492. .. warning::
  4493. When ``align_corners = True``, the grid positions depend on the pixel
  4494. size relative to the input image size, and so the locations sampled by
  4495. :func:`grid_sample` will differ for the same input given at different
  4496. resolutions (that is, after being upsampled or downsampled).
  4497. The default behavior up to version 1.2.0 was ``align_corners = True``.
  4498. Since then, the default behavior has been changed to ``align_corners = False``,
  4499. in order to bring it in line with the default for :func:`interpolate`.
  4500. .. warning::
  4501. When ``align_corners = True``, 2D affine transforms on 1D data and
  4502. 3D affine transforms on 2D data (that is, when one of the spatial
  4503. dimensions has unit size) are ill-defined, and not an intended use case.
  4504. This is not a problem when ``align_corners = False``.
  4505. Up to version 1.2.0, all grid points along a unit dimension were
  4506. considered arbitrarily to be at ``-1``.
  4507. From version 1.3.0, under ``align_corners = True`` all grid points
  4508. along a unit dimension are considered to be at ``0``
  4509. (the center of the input image).
  4510. """
  4511. if has_torch_function_unary(theta):
  4512. return handle_torch_function(
  4513. affine_grid, (theta,), theta, size, align_corners=align_corners
  4514. )
  4515. if align_corners is None:
  4516. warnings.warn(
  4517. "Default grid_sample and affine_grid behavior has changed "
  4518. "to align_corners=False since 1.3.0. Please specify "
  4519. "align_corners=True if the old behavior is desired. "
  4520. "See the documentation of grid_sample for details.",
  4521. stacklevel=2,
  4522. )
  4523. align_corners = False
  4524. # enforce floating point dtype on theta
  4525. if not theta.is_floating_point():
  4526. raise ValueError(
  4527. f"Expected theta to have floating point type, but got {theta.dtype}"
  4528. )
  4529. # check that shapes and sizes match
  4530. if len(size) == 4:
  4531. if theta.dim() != 3 or theta.shape[-2] != 2 or theta.shape[-1] != 3:
  4532. raise ValueError(
  4533. f"Expected a batch of 2D affine matrices of shape Nx2x3 for size {size}. Got {theta.shape}."
  4534. )
  4535. spatial_size = size[-2:] # spatial dimension sizes
  4536. elif len(size) == 5:
  4537. if theta.dim() != 3 or theta.shape[-2] != 3 or theta.shape[-1] != 4:
  4538. raise ValueError(
  4539. f"Expected a batch of 3D affine matrices of shape Nx3x4 for size {size}. Got {theta.shape}."
  4540. )
  4541. spatial_size = size[-3:] # spatial dimension sizes
  4542. else:
  4543. raise NotImplementedError(
  4544. "affine_grid only supports 4D and 5D sizes, "
  4545. "for 2D and 3D affine transforms, respectively. "
  4546. f"Got size {size}."
  4547. )
  4548. # check for empty span
  4549. if align_corners and min(spatial_size) == 1:
  4550. warnings.warn(
  4551. "Since version 1.3.0, affine_grid behavior has changed "
  4552. "for unit-size grids when align_corners=True. "
  4553. "This is not an intended use case of affine_grid. "
  4554. "See the documentation of affine_grid for details.",
  4555. stacklevel=2,
  4556. )
  4557. elif min(size) <= 0:
  4558. raise ValueError(f"Expected non-zero, positive output size. Got {size}")
  4559. return torch.affine_grid_generator(theta, size, align_corners)
  4560. def pad(
  4561. input: Tensor,
  4562. pad: list[int],
  4563. mode: str = "constant",
  4564. value: Optional[float] = None,
  4565. ) -> Tensor:
  4566. r"""
  4567. pad(input, pad, mode="constant", value=None) -> Tensor
  4568. Pads tensor.
  4569. Padding size:
  4570. The padding size by which to pad some dimensions of :attr:`input`
  4571. are described starting from the last dimension and moving forward.
  4572. :math:`\left\lfloor\frac{\text{len(pad)}}{2}\right\rfloor` dimensions
  4573. of ``input`` will be padded.
  4574. For example, to pad only the last dimension of the input tensor, then
  4575. :attr:`pad` has the form
  4576. :math:`(\text{padding\_left}, \text{padding\_right})`;
  4577. to pad the last 2 dimensions of the input tensor, then use
  4578. :math:`(\text{padding\_left}, \text{padding\_right},`
  4579. :math:`\text{padding\_top}, \text{padding\_bottom})`;
  4580. to pad the last 3 dimensions, use
  4581. :math:`(\text{padding\_left}, \text{padding\_right},`
  4582. :math:`\text{padding\_top}, \text{padding\_bottom}`
  4583. :math:`\text{padding\_front}, \text{padding\_back})`.
  4584. Padding mode:
  4585. See :class:`torch.nn.CircularPad2d`, :class:`torch.nn.ConstantPad2d`,
  4586. :class:`torch.nn.ReflectionPad2d`, and :class:`torch.nn.ReplicationPad2d`
  4587. for concrete examples on how each of the padding modes works. Constant
  4588. padding is implemented for arbitrary dimensions. Circular, replicate and
  4589. reflection padding are implemented for padding the last 3 dimensions of a
  4590. 4D or 5D input tensor, the last 2 dimensions of a 3D or 4D input tensor,
  4591. or the last dimension of a 2D or 3D input tensor.
  4592. Note:
  4593. When using the CUDA backend, this operation may induce nondeterministic
  4594. behaviour in its backward pass that is not easily switched off.
  4595. Please see the notes on :doc:`/notes/randomness` for background.
  4596. Args:
  4597. input (Tensor): N-dimensional tensor
  4598. pad (tuple): m-elements tuple, where
  4599. :math:`\frac{m}{2} \leq` input dimensions and :math:`m` is even.
  4600. mode: ``'constant'``, ``'reflect'``, ``'replicate'`` or ``'circular'``.
  4601. Default: ``'constant'``
  4602. value: fill value for ``'constant'`` padding. Default: ``0``
  4603. Examples::
  4604. >>> t4d = torch.empty(3, 3, 4, 2)
  4605. >>> p1d = (1, 1) # pad last dim by 1 on each side
  4606. >>> out = F.pad(t4d, p1d, "constant", 0) # effectively zero padding
  4607. >>> print(out.size())
  4608. torch.Size([3, 3, 4, 4])
  4609. >>> p2d = (1, 1, 2, 2) # pad last dim by (1, 1) and 2nd to last by (2, 2)
  4610. >>> out = F.pad(t4d, p2d, "constant", 0)
  4611. >>> print(out.size())
  4612. torch.Size([3, 3, 8, 4])
  4613. >>> t4d = torch.empty(3, 3, 4, 2)
  4614. >>> p3d = (0, 1, 2, 1, 3, 3) # pad by (0, 1), (2, 1), and (3, 3)
  4615. >>> out = F.pad(t4d, p3d, "constant", 0)
  4616. >>> print(out.size())
  4617. torch.Size([3, 9, 7, 3])
  4618. """
  4619. if has_torch_function_unary(input):
  4620. return handle_torch_function(
  4621. torch.nn.functional.pad, (input,), input, pad, mode=mode, value=value
  4622. )
  4623. if not torch.jit.is_scripting():
  4624. if torch.are_deterministic_algorithms_enabled() and (
  4625. input.is_cuda or input.is_xpu
  4626. ):
  4627. if mode == "replicate":
  4628. # Use slow decomp whose backward will be in terms of index_put.
  4629. # importlib is required because the import cannot be top level
  4630. # (cycle) and cannot be nested (TS doesn't support)
  4631. return importlib.import_module(
  4632. "torch._decomp.decompositions"
  4633. )._replication_pad(input, pad)
  4634. return torch._C._nn.pad(input, pad, mode, value)
  4635. # TODO: Fix via https://github.com/pytorch/pytorch/issues/75798
  4636. pad.__module__ = "torch.nn.functional"
  4637. # distance
  4638. pairwise_distance = _add_docstr(
  4639. torch.pairwise_distance,
  4640. r"""
  4641. pairwise_distance(x1, x2, p=2.0, eps=1e-6, keepdim=False) -> Tensor
  4642. See :class:`torch.nn.PairwiseDistance` for details
  4643. """,
  4644. )
  4645. pdist = _add_docstr(
  4646. torch.pdist,
  4647. r"""
  4648. pdist(input, p=2) -> Tensor
  4649. Computes the p-norm distance between every pair of row vectors in the input.
  4650. This is identical to the upper triangular portion, excluding the diagonal, of
  4651. `torch.norm(input[:, None] - input, dim=2, p=p)`. This function will be faster
  4652. if the rows are contiguous.
  4653. If input has shape :math:`N \times M` then the output will have shape
  4654. :math:`\frac{1}{2} N (N - 1)`.
  4655. This function is equivalent to ``scipy.spatial.distance.pdist(input,
  4656. 'minkowski', p=p)`` if :math:`p \in (0, \infty)`. When :math:`p = 0` it is
  4657. equivalent to ``scipy.spatial.distance.pdist(input, 'hamming') * M``.
  4658. When :math:`p = \infty`, the closest scipy function is
  4659. ``scipy.spatial.distance.pdist(xn, lambda x, y: np.abs(x - y).max())``.
  4660. Args:
  4661. input: input tensor of shape :math:`N \times M`.
  4662. p: p value for the p-norm distance to calculate between each vector pair
  4663. :math:`\in [0, \infty]`.
  4664. """,
  4665. )
  4666. cosine_similarity = _add_docstr(
  4667. torch.cosine_similarity,
  4668. r"""
  4669. cosine_similarity(x1, x2, dim=1, eps=1e-8) -> Tensor
  4670. Returns cosine similarity between ``x1`` and ``x2``, computed along dim. ``x1`` and ``x2`` must be broadcastable
  4671. to a common shape. ``dim`` refers to the dimension in this common shape. Dimension ``dim`` of the output is
  4672. squeezed (see :func:`torch.squeeze`), resulting in the
  4673. output tensor having 1 fewer dimension.
  4674. .. math ::
  4675. \text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2, \epsilon) \cdot \max(\Vert x_2 \Vert _2, \epsilon)}
  4676. Supports :ref:`type promotion <type-promotion-doc>`.
  4677. Args:
  4678. x1 (Tensor): First input.
  4679. x2 (Tensor): Second input.
  4680. dim (int, optional): Dimension along which cosine similarity is computed. Default: 1
  4681. eps (float, optional): Small value to avoid division by zero.
  4682. Default: 1e-8
  4683. Example::
  4684. >>> input1 = torch.randn(100, 128)
  4685. >>> input2 = torch.randn(100, 128)
  4686. >>> output = F.cosine_similarity(input1, input2)
  4687. >>> print(output)
  4688. """,
  4689. )
  4690. one_hot = _add_docstr(
  4691. torch._C._nn.one_hot,
  4692. r"""
  4693. one_hot(tensor, num_classes=-1) -> LongTensor
  4694. Takes LongTensor with index values of shape ``(*)`` and returns a tensor
  4695. of shape ``(*, num_classes)`` that have zeros everywhere except where the
  4696. index of last dimension matches the corresponding value of the input tensor,
  4697. in which case it will be 1.
  4698. See also `One-hot on Wikipedia`_ .
  4699. .. _One-hot on Wikipedia:
  4700. https://en.wikipedia.org/wiki/One-hot
  4701. Arguments:
  4702. tensor (LongTensor): class values of any shape.
  4703. num_classes (int, optional): Total number of classes. If set to -1, the number
  4704. of classes will be inferred as one greater than the largest class
  4705. value in the input tensor. Default: -1
  4706. Returns:
  4707. LongTensor that has one more dimension with 1 values at the
  4708. index of last dimension indicated by the input, and 0 everywhere
  4709. else.
  4710. Examples:
  4711. >>> F.one_hot(torch.arange(0, 5) % 3)
  4712. tensor([[1, 0, 0],
  4713. [0, 1, 0],
  4714. [0, 0, 1],
  4715. [1, 0, 0],
  4716. [0, 1, 0]])
  4717. >>> F.one_hot(torch.arange(0, 5) % 3, num_classes=5)
  4718. tensor([[1, 0, 0, 0, 0],
  4719. [0, 1, 0, 0, 0],
  4720. [0, 0, 1, 0, 0],
  4721. [1, 0, 0, 0, 0],
  4722. [0, 1, 0, 0, 0]])
  4723. >>> F.one_hot(torch.arange(0, 6).view(3,2) % 3)
  4724. tensor([[[1, 0, 0],
  4725. [0, 1, 0]],
  4726. [[0, 0, 1],
  4727. [1, 0, 0]],
  4728. [[0, 1, 0],
  4729. [0, 0, 1]]])
  4730. """,
  4731. )
  4732. def triplet_margin_loss(
  4733. anchor: Tensor,
  4734. positive: Tensor,
  4735. negative: Tensor,
  4736. margin: float = 1.0,
  4737. p: float = 2,
  4738. eps: float = 1e-6,
  4739. swap: bool = False,
  4740. size_average: Optional[bool] = None,
  4741. reduce: Optional[bool] = None,
  4742. reduction: str = "mean",
  4743. ) -> Tensor:
  4744. r"""Compute the triplet loss between given input tensors and a margin greater than 0.
  4745. See :class:`~torch.nn.TripletMarginLoss` for details.
  4746. """
  4747. if has_torch_function_variadic(anchor, positive, negative):
  4748. return handle_torch_function(
  4749. triplet_margin_loss,
  4750. (anchor, positive, negative),
  4751. anchor,
  4752. positive,
  4753. negative,
  4754. margin=margin,
  4755. p=p,
  4756. eps=eps,
  4757. swap=swap,
  4758. size_average=size_average,
  4759. reduce=reduce,
  4760. reduction=reduction,
  4761. )
  4762. if size_average is not None or reduce is not None:
  4763. reduction_enum = _Reduction.legacy_get_enum(size_average, reduce)
  4764. else:
  4765. reduction_enum = _Reduction.get_enum(reduction)
  4766. if margin <= 0:
  4767. raise ValueError(f"margin must be greater than 0, got {margin}")
  4768. return torch.triplet_margin_loss(
  4769. anchor, positive, negative, margin, p, eps, swap, reduction_enum
  4770. )
  4771. def triplet_margin_with_distance_loss(
  4772. anchor: Tensor,
  4773. positive: Tensor,
  4774. negative: Tensor,
  4775. *,
  4776. distance_function: Optional[Callable[[Tensor, Tensor], Tensor]] = None,
  4777. margin: float = 1.0,
  4778. swap: bool = False,
  4779. reduction: str = "mean",
  4780. ) -> Tensor:
  4781. r"""Compute the triplet margin loss for input tensors using a custom distance function.
  4782. See :class:`~torch.nn.TripletMarginWithDistanceLoss` for details.
  4783. """
  4784. if torch.jit.is_scripting():
  4785. raise NotImplementedError(
  4786. "F.triplet_margin_with_distance_loss does not support JIT scripting: "
  4787. "functions requiring Callables cannot be scripted."
  4788. )
  4789. if has_torch_function_variadic(anchor, positive, negative):
  4790. return handle_torch_function(
  4791. triplet_margin_with_distance_loss,
  4792. (anchor, positive, negative),
  4793. anchor,
  4794. positive,
  4795. negative,
  4796. distance_function=distance_function,
  4797. margin=margin,
  4798. swap=swap,
  4799. reduction=reduction,
  4800. )
  4801. # Check validity of reduction mode
  4802. if reduction not in ("mean", "sum", "none"):
  4803. raise ValueError(f"{reduction} is not a valid value for reduction")
  4804. # Check validity of margin
  4805. if margin <= 0:
  4806. raise ValueError(f"margin must be greater than 0, got {margin}")
  4807. # Check dimensions
  4808. a_dim = anchor.ndim
  4809. p_dim = positive.ndim
  4810. n_dim = negative.ndim
  4811. if not (a_dim == p_dim and p_dim == n_dim):
  4812. raise RuntimeError(
  4813. f"The anchor, positive, and negative tensors are expected to have "
  4814. f"the same number of dimensions, but got: anchor {a_dim}D, "
  4815. f"positive {p_dim}D, and negative {n_dim}D inputs"
  4816. )
  4817. # Calculate loss
  4818. if distance_function is None:
  4819. distance_function = torch.pairwise_distance
  4820. dist_pos = distance_function(anchor, positive)
  4821. dist_neg = distance_function(anchor, negative)
  4822. # The distance swap is described in the paper "Learning shallow
  4823. # convolutional feature descriptors with triplet losses" by V. Balntas, E.
  4824. # Riba et al. If True, and if the positive example is closer to the
  4825. # negative example than the anchor is, swaps the positive example and the
  4826. # anchor in the loss computation.
  4827. if swap:
  4828. dist_swap = distance_function(positive, negative)
  4829. dist_neg = torch.minimum(dist_neg, dist_swap)
  4830. loss = torch.clamp_min(margin + dist_pos - dist_neg, 0)
  4831. # Apply reduction
  4832. if reduction == "sum":
  4833. return torch.sum(loss)
  4834. elif reduction == "mean":
  4835. return torch.mean(loss)
  4836. else: # reduction == "none"
  4837. return loss
  4838. def normalize(
  4839. input: Tensor,
  4840. p: float = 2.0,
  4841. dim: int = 1,
  4842. eps: float = 1e-12,
  4843. out: Optional[Tensor] = None,
  4844. ) -> Tensor:
  4845. r"""Perform :math:`L_p` normalization of inputs over specified dimension.
  4846. For a tensor :attr:`input` of sizes :math:`(n_0, ..., n_{dim}, ..., n_k)`, each
  4847. :math:`n_{dim}` -element vector :math:`v` along dimension :attr:`dim` is transformed as
  4848. .. math::
  4849. v = \frac{v}{\max(\lVert v \rVert_p, \epsilon)}.
  4850. With the default arguments it uses the Euclidean norm over vectors along dimension :math:`1` for normalization.
  4851. Args:
  4852. input: input tensor of any shape
  4853. p (float): the exponent value in the norm formulation. Default: 2
  4854. dim (int or tuple of ints): the dimension to reduce. Default: 1
  4855. eps (float): small value to avoid division by zero. Default: 1e-12
  4856. out (Tensor, optional): the output tensor. If :attr:`out` is used, this
  4857. operation won't be differentiable.
  4858. """
  4859. if has_torch_function_variadic(input, out):
  4860. return handle_torch_function(
  4861. normalize, (input, out), input, p=p, dim=dim, eps=eps, out=out
  4862. )
  4863. if out is None:
  4864. denom = input.norm(p, dim, keepdim=True).clamp_min(eps).expand_as(input)
  4865. return input / denom
  4866. else:
  4867. denom = input.norm(p, dim, keepdim=True).clamp_min_(eps).expand_as(input)
  4868. return torch.div(input, denom, out=out)
  4869. def assert_int_or_pair(arg: list[int], arg_name: str, message: str) -> None:
  4870. if not (isinstance(arg, int) or len(arg) == 2):
  4871. raise AssertionError(message.format(arg_name))
  4872. def unfold(
  4873. input: Tensor,
  4874. kernel_size: BroadcastingList2[int],
  4875. dilation: BroadcastingList2[int] = 1,
  4876. padding: BroadcastingList2[int] = 0,
  4877. stride: BroadcastingList2[int] = 1,
  4878. ) -> Tensor:
  4879. r"""Extract sliding local blocks from a batched input tensor.
  4880. .. warning::
  4881. Currently, only 4-D input tensors (batched image-like tensors) are
  4882. supported.
  4883. .. warning::
  4884. More than one element of the unfolded tensor may refer to a single
  4885. memory location. As a result, in-place operations (especially ones that
  4886. are vectorized) may result in incorrect behavior. If you need to write
  4887. to the tensor, please clone it first.
  4888. See :class:`torch.nn.Unfold` for details
  4889. """
  4890. if has_torch_function_unary(input):
  4891. return handle_torch_function(
  4892. unfold,
  4893. (input,),
  4894. input,
  4895. kernel_size,
  4896. dilation=dilation,
  4897. padding=padding,
  4898. stride=stride,
  4899. )
  4900. return torch._C._nn.im2col(
  4901. input, _pair(kernel_size), _pair(dilation), _pair(padding), _pair(stride)
  4902. )
  4903. def fold(
  4904. input: Tensor,
  4905. output_size: BroadcastingList2[int],
  4906. kernel_size: BroadcastingList2[int],
  4907. dilation: BroadcastingList2[int] = 1,
  4908. padding: BroadcastingList2[int] = 0,
  4909. stride: BroadcastingList2[int] = 1,
  4910. ) -> Tensor:
  4911. r"""Combine an array of sliding local blocks into a large containing tensor.
  4912. .. warning::
  4913. Currently, only unbatched (3D) or batched (4D) image-like output tensors are supported.
  4914. See :class:`torch.nn.Fold` for details
  4915. """
  4916. if has_torch_function_unary(input):
  4917. return handle_torch_function(
  4918. fold,
  4919. (input,),
  4920. input,
  4921. output_size,
  4922. kernel_size,
  4923. dilation=dilation,
  4924. padding=padding,
  4925. stride=stride,
  4926. )
  4927. return torch._C._nn.col2im(
  4928. input,
  4929. _pair(output_size),
  4930. _pair(kernel_size),
  4931. _pair(dilation),
  4932. _pair(padding),
  4933. _pair(stride),
  4934. )
  4935. #
  4936. # multihead attention
  4937. #
  4938. def _in_projection_packed(
  4939. q: Tensor,
  4940. k: Tensor,
  4941. v: Tensor,
  4942. w: Tensor,
  4943. b: Optional[Tensor] = None,
  4944. ) -> list[Tensor]:
  4945. r"""Perform the in-projection step of the attention operation, using packed weights.
  4946. Output is a triple containing projection tensors for query, key and value.
  4947. Args:
  4948. q, k, v: query, key and value tensors to be projected. For self-attention,
  4949. these are typically the same tensor; for encoder-decoder attention,
  4950. k and v are typically the same tensor. (We take advantage of these
  4951. identities for performance if they are present.) Regardless, q, k and v
  4952. must share a common embedding dimension; otherwise their shapes may vary.
  4953. w: projection weights for q, k and v, packed into a single tensor. Weights
  4954. are packed along dimension 0, in q, k, v order.
  4955. b: optional projection biases for q, k and v, packed into a single tensor
  4956. in q, k, v order.
  4957. Shape:
  4958. Inputs:
  4959. - q: :math:`(..., E)` where E is the embedding dimension
  4960. - k: :math:`(..., E)` where E is the embedding dimension
  4961. - v: :math:`(..., E)` where E is the embedding dimension
  4962. - w: :math:`(E * 3, E)` where E is the embedding dimension
  4963. - b: :math:`E * 3` where E is the embedding dimension
  4964. Output:
  4965. - in output list :math:`[q', k', v']`, each output tensor will have the
  4966. same shape as the corresponding input tensor.
  4967. """
  4968. E = q.size(-1)
  4969. if k is v:
  4970. if q is k:
  4971. # self-attention
  4972. proj = linear(q, w, b)
  4973. # reshape to 3, E and not E, 3 is deliberate for better memory coalescing and keeping same order as chunk()
  4974. proj = (
  4975. proj.unflatten(-1, (3, E))
  4976. .unsqueeze(0)
  4977. .transpose(0, -2)
  4978. .squeeze(-2)
  4979. .contiguous()
  4980. )
  4981. # pyrefly: ignore [bad-return]
  4982. return proj[0], proj[1], proj[2]
  4983. else:
  4984. # encoder-decoder attention
  4985. w_q, w_kv = w.split([E, E * 2])
  4986. if b is None:
  4987. b_q = b_kv = None
  4988. else:
  4989. b_q, b_kv = b.split([E, E * 2])
  4990. q_proj = linear(q, w_q, b_q)
  4991. kv_proj = linear(k, w_kv, b_kv)
  4992. # reshape to 2, E and not E, 2 is deliberate for better memory coalescing and keeping same order as chunk()
  4993. kv_proj = (
  4994. kv_proj.unflatten(-1, (2, E))
  4995. .unsqueeze(0)
  4996. .transpose(0, -2)
  4997. .squeeze(-2)
  4998. .contiguous()
  4999. )
  5000. # pyrefly: ignore [bad-return]
  5001. return (q_proj, kv_proj[0], kv_proj[1])
  5002. else:
  5003. w_q, w_k, w_v = w.chunk(3)
  5004. if b is None:
  5005. b_q = b_k = b_v = None
  5006. else:
  5007. b_q, b_k, b_v = b.chunk(3)
  5008. # pyrefly: ignore [bad-return]
  5009. return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
  5010. def _in_projection(
  5011. q: Tensor,
  5012. k: Tensor,
  5013. v: Tensor,
  5014. w_q: Tensor,
  5015. w_k: Tensor,
  5016. w_v: Tensor,
  5017. b_q: Optional[Tensor] = None,
  5018. b_k: Optional[Tensor] = None,
  5019. b_v: Optional[Tensor] = None,
  5020. ) -> tuple[Tensor, Tensor, Tensor]:
  5021. r"""Perform the in-projection step of the attention operation.
  5022. This is simply a triple of linear projections,
  5023. with shape constraints on the weights which
  5024. ensure embedding dimension uniformity in the projected outputs.
  5025. Output is a triple containing projection tensors for query, key and value.
  5026. Args:
  5027. q, k, v: query, key and value tensors to be projected.
  5028. w_q, w_k, w_v: weights for q, k and v, respectively.
  5029. b_q, b_k, b_v: optional biases for q, k and v, respectively.
  5030. Shape:
  5031. Inputs:
  5032. - q: :math:`(Qdims..., Eq)` where Eq is the query embedding dimension and Qdims are any
  5033. number of leading dimensions.
  5034. - k: :math:`(Kdims..., Ek)` where Ek is the key embedding dimension and Kdims are any
  5035. number of leading dimensions.
  5036. - v: :math:`(Vdims..., Ev)` where Ev is the value embedding dimension and Vdims are any
  5037. number of leading dimensions.
  5038. - w_q: :math:`(Eq, Eq)`
  5039. - w_k: :math:`(Eq, Ek)`
  5040. - w_v: :math:`(Eq, Ev)`
  5041. - b_q: :math:`(Eq)`
  5042. - b_k: :math:`(Eq)`
  5043. - b_v: :math:`(Eq)`
  5044. Output: in output triple :math:`(q', k', v')`,
  5045. - q': :math:`[Qdims..., Eq]`
  5046. - k': :math:`[Kdims..., Eq]`
  5047. - v': :math:`[Vdims..., Eq]`
  5048. """
  5049. Eq, Ek, Ev = q.size(-1), k.size(-1), v.size(-1)
  5050. if w_q.shape != (Eq, Eq):
  5051. raise AssertionError(
  5052. f"expecting query weights shape of {(Eq, Eq)}, but got {w_q.shape}"
  5053. )
  5054. if w_k.shape != (Eq, Ek):
  5055. raise AssertionError(
  5056. f"expecting key weights shape of {(Eq, Ek)}, but got {w_k.shape}"
  5057. )
  5058. if w_v.shape != (Eq, Ev):
  5059. raise AssertionError(
  5060. f"expecting value weights shape of {(Eq, Ev)}, but got {w_v.shape}"
  5061. )
  5062. if b_q is not None and b_q.shape != (Eq,):
  5063. raise AssertionError(
  5064. f"expecting query bias shape of {(Eq,)}, but got {b_q.shape}"
  5065. )
  5066. if b_k is not None and b_k.shape != (Eq,):
  5067. raise AssertionError(
  5068. f"expecting key bias shape of {(Eq,)}, but got {b_k.shape}"
  5069. )
  5070. if b_v is not None and b_v.shape != (Eq,):
  5071. raise AssertionError(
  5072. f"expecting value bias shape of {(Eq,)}, but got {b_v.shape}"
  5073. )
  5074. return linear(q, w_q, b_q), linear(k, w_k, b_k), linear(v, w_v, b_v)
  5075. scaled_dot_product_attention = _add_docstr(
  5076. torch._C._nn.scaled_dot_product_attention,
  5077. r"""scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0,
  5078. is_causal=False, scale=None, enable_gqa=False) -> Tensor:
  5079. Computes scaled dot product attention on query, key and value tensors, using an optional attention mask if passed,
  5080. and applying dropout if a probability greater than 0.0 is specified. The optional scale argument can only be
  5081. specified as a keyword argument.
  5082. .. code-block:: python
  5083. # Efficient implementation equivalent to the following:
  5084. def scaled_dot_product_attention(query, key, value, attn_mask=None, dropout_p=0.0,
  5085. is_causal=False, scale=None, enable_gqa=False) -> torch.Tensor:
  5086. L, S = query.size(-2), key.size(-2)
  5087. scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale
  5088. attn_bias = torch.zeros(L, S, dtype=query.dtype, device=query.device)
  5089. if is_causal:
  5090. assert attn_mask is None
  5091. temp_mask = torch.ones(L, S, dtype=torch.bool).tril(diagonal=0)
  5092. attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
  5093. if attn_mask is not None:
  5094. if attn_mask.dtype == torch.bool:
  5095. attn_bias.masked_fill_(attn_mask.logical_not(), float("-inf"))
  5096. else:
  5097. attn_bias = attn_mask + attn_bias
  5098. if enable_gqa:
  5099. key = key.repeat_interleave(query.size(-3)//key.size(-3), -3)
  5100. value = value.repeat_interleave(query.size(-3)//value.size(-3), -3)
  5101. attn_weight = query @ key.transpose(-2, -1) * scale_factor
  5102. attn_weight += attn_bias
  5103. attn_weight = torch.softmax(attn_weight, dim=-1)
  5104. attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
  5105. return attn_weight @ value
  5106. .. warning::
  5107. This function is beta and subject to change.
  5108. .. warning::
  5109. This function always applies dropout according to the specified ``dropout_p`` argument.
  5110. To disable dropout during evaluation, be sure to pass a value of ``0.0`` when the module
  5111. that makes the function call is not in training mode.
  5112. For example:
  5113. .. code-block:: python
  5114. class MyModel(nn.Module):
  5115. def __init__(self, p=0.5):
  5116. super().__init__()
  5117. self.p = p
  5118. def forward(self, ...):
  5119. return F.scaled_dot_product_attention(...,
  5120. dropout_p=(self.p if self.training else 0.0))
  5121. Note:
  5122. The boolean mask semantics for ``attn_mask`` are the inverse of
  5123. :class:`~torch.nn.MultiheadAttention`'s ``key_padding_mask``.
  5124. In :func:`scaled_dot_product_attention`, ``True`` indicates values
  5125. to **participate** in attention.
  5126. In :class:`~torch.nn.MultiheadAttention`, ``True`` indicates values
  5127. to be **masked out** (padding).
  5128. If migrating from MHA, ensure you invert your boolean mask (e.g.,
  5129. using ``~mask`` or ``mask.logical_not()``).
  5130. Note:
  5131. There are currently three supported implementations of scaled dot product attention:
  5132. - `FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning`_
  5133. - `Memory-Efficient Attention`_
  5134. - A PyTorch implementation defined in C++ matching the above formulation
  5135. The function may call optimized kernels for improved performance when using the CUDA backend.
  5136. For all other backends, the PyTorch implementation will be used.
  5137. All implementations are enabled by default. Scaled dot product attention attempts to automatically select the
  5138. most optimal implementation based on the inputs. In order to provide more fine-grained control over what implementation
  5139. is used, the following functions are provided for enabling and disabling implementations.
  5140. The context manager is the preferred mechanism:
  5141. - :func:`torch.nn.attention.sdpa_kernel`: A context manager used to enable or disable any of the implementations.
  5142. - :func:`torch.backends.cuda.enable_flash_sdp`: Globally enables or disables FlashAttention.
  5143. - :func:`torch.backends.cuda.enable_mem_efficient_sdp`: Globally enables or disables Memory-Efficient Attention.
  5144. - :func:`torch.backends.cuda.enable_math_sdp`: Globally enables or disables the PyTorch C++ implementation.
  5145. Each of the fused kernels has specific input limitations. If the user requires the use of a specific fused implementation,
  5146. disable the PyTorch C++ implementation using :func:`torch.nn.attention.sdpa_kernel`.
  5147. In the event that a fused implementation is not available, a warning will be raised with the
  5148. reasons why the fused implementation cannot run.
  5149. Due to the nature of fusing floating point operations, the output of this function may be different
  5150. depending on what backend kernel is chosen.
  5151. The c++ implementation supports torch.float64 and can be used when higher precision is required.
  5152. For math backend, all intermediates are kept in torch.float if inputs are in torch.half or torch.bfloat16.
  5153. For more information please see :doc:`/notes/numerical_accuracy`
  5154. Grouped Query Attention (GQA) is an experimental feature. It currently works only for Flash_attention
  5155. and math kernel on CUDA tensor, and does not support Nested tensor.
  5156. Constraints for GQA:
  5157. - number_of_heads_query % number_of_heads_key_value == 0 and,
  5158. - number_of_heads_key == number_of_heads_value
  5159. Note:
  5160. {cudnn_reproducibility_note}
  5161. """.format(**reproducibility_notes)
  5162. + r"""
  5163. Args:
  5164. query (Tensor): Query tensor; shape :math:`(N, ..., Hq, L, E)`.
  5165. key (Tensor): Key tensor; shape :math:`(N, ..., H, S, E)`.
  5166. value (Tensor): Value tensor; shape :math:`(N, ..., H, S, Ev)`.
  5167. attn_mask (optional Tensor): Attention mask; shape must be broadcastable to the shape of attention weights,
  5168. which is :math:`(N,..., L, S)`. Two types of masks are supported.
  5169. A boolean mask where a value of True indicates that the element *should* take part in attention.
  5170. A float mask of the same type as query, key, value that is added to the attention score.
  5171. dropout_p (float): Dropout probability; if greater than 0.0, dropout is applied
  5172. is_causal (bool): If set to true, the attention masking is a lower triangular matrix when the mask is a
  5173. square matrix. The attention masking has the form of the upper left causal bias due to the alignment
  5174. (see :class:`torch.nn.attention.bias.CausalBias`) when the mask is a non-square matrix.
  5175. An error is thrown if both attn_mask and is_causal are set.
  5176. scale (optional float, keyword-only): Scaling factor applied prior to softmax. If None, the default value is set
  5177. to :math:`\frac{1}{\sqrt{E}}`.
  5178. enable_gqa (bool): If set to True, Grouped Query Attention (GQA) is enabled, by default it is set to False.
  5179. Returns:
  5180. output (Tensor): Attention output; shape :math:`(N, ..., Hq, L, Ev)`.
  5181. Shape legend:
  5182. - :math:`N: \text{Batch size} ... : \text{Any number of other batch dimensions (optional)}`
  5183. - :math:`S: \text{Source sequence length}`
  5184. - :math:`L: \text{Target sequence length}`
  5185. - :math:`E: \text{Embedding dimension of the query and key}`
  5186. - :math:`Ev: \text{Embedding dimension of the value}`
  5187. - :math:`Hq: \text{Number of heads of query}`
  5188. - :math:`H: \text{Number of heads of key and value}`
  5189. Examples:
  5190. >>> # Optionally use the context manager to ensure one of the fused kernels is run
  5191. >>> query = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
  5192. >>> key = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
  5193. >>> value = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
  5194. >>> with sdpa_kernel(backends=[SDPBackend.FLASH_ATTENTION]):
  5195. >>> F.scaled_dot_product_attention(query,key,value)
  5196. >>> # Sample for GQA for llama3
  5197. >>> query = torch.rand(32, 32, 128, 64, dtype=torch.float16, device="cuda")
  5198. >>> key = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
  5199. >>> value = torch.rand(32, 8, 128, 64, dtype=torch.float16, device="cuda")
  5200. >>> with sdpa_kernel(backends=[SDPBackend.MATH]):
  5201. >>> F.scaled_dot_product_attention(query,key,value,enable_gqa=True)
  5202. .. _FlashAttention-2\: Faster Attention with Better Parallelism and Work Partitioning:
  5203. https://arxiv.org/abs/2307.08691
  5204. .. _Memory-Efficient Attention:
  5205. https://github.com/facebookresearch/xformers
  5206. .. _Grouped-Query Attention:
  5207. https://arxiv.org/pdf/2305.13245
  5208. """,
  5209. )
  5210. def _mha_shape_check(
  5211. query: Tensor,
  5212. key: Tensor,
  5213. value: Tensor,
  5214. key_padding_mask: Optional[Tensor],
  5215. attn_mask: Optional[Tensor],
  5216. num_heads: int,
  5217. ):
  5218. # Verifies the expected shape for `query, `key`, `value`, `key_padding_mask` and `attn_mask`
  5219. # and returns if the input is batched or not.
  5220. # Raises an error if `query` is not 2-D (unbatched) or 3-D (batched) tensor.
  5221. # Shape check.
  5222. if query.dim() == 3:
  5223. # Batched Inputs
  5224. is_batched = True
  5225. if key.dim() != 3 or value.dim() != 3:
  5226. raise AssertionError(
  5227. "For batched (3-D) `query`, expected `key` and `value` to be 3-D"
  5228. f" but found {key.dim()}-D and {value.dim()}-D tensors respectively"
  5229. )
  5230. if key_padding_mask is not None:
  5231. if key_padding_mask.dim() != 2:
  5232. raise AssertionError(
  5233. "For batched (3-D) `query`, expected `key_padding_mask` to be `None` or 2-D"
  5234. f" but found {key_padding_mask.dim()}-D tensor instead"
  5235. )
  5236. if attn_mask is not None:
  5237. if attn_mask.dim() not in (2, 3):
  5238. raise AssertionError(
  5239. "For batched (3-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
  5240. f" but found {attn_mask.dim()}-D tensor instead"
  5241. )
  5242. elif query.dim() == 2:
  5243. # Unbatched Inputs
  5244. is_batched = False
  5245. if key.dim() != 2 or value.dim() != 2:
  5246. raise AssertionError(
  5247. "For unbatched (2-D) `query`, expected `key` and `value` to be 2-D"
  5248. f" but found {key.dim()}-D and {value.dim()}-D tensors respectively"
  5249. )
  5250. if key_padding_mask is not None:
  5251. if key_padding_mask.dim() != 1:
  5252. raise AssertionError(
  5253. "For unbatched (2-D) `query`, expected `key_padding_mask` to be `None` or 1-D"
  5254. f" but found {key_padding_mask.dim()}-D tensor instead"
  5255. )
  5256. if attn_mask is not None:
  5257. if attn_mask.dim() not in (2, 3):
  5258. raise AssertionError(
  5259. "For unbatched (2-D) `query`, expected `attn_mask` to be `None`, 2-D or 3-D"
  5260. f" but found {attn_mask.dim()}-D tensor instead"
  5261. )
  5262. if attn_mask.dim() == 3:
  5263. expected_shape = (num_heads, query.shape[0], key.shape[0])
  5264. if attn_mask.shape != expected_shape:
  5265. raise AssertionError(
  5266. f"Expected `attn_mask` shape to be {expected_shape} but got {attn_mask.shape}"
  5267. )
  5268. else:
  5269. raise AssertionError(
  5270. f"query should be unbatched 2D or batched 3D tensor but received {query.dim()}-D query tensor"
  5271. )
  5272. return is_batched
  5273. def _canonical_mask(
  5274. mask: Optional[Tensor],
  5275. mask_name: str,
  5276. other_type: Optional[DType],
  5277. other_name: str,
  5278. target_type: DType,
  5279. check_other: bool = True,
  5280. ) -> Optional[Tensor]:
  5281. if mask is not None:
  5282. _mask_dtype = mask.dtype
  5283. _mask_is_float = torch.is_floating_point(mask)
  5284. if _mask_dtype != torch.bool and not _mask_is_float:
  5285. raise AssertionError(
  5286. f"only bool and floating types of {mask_name} are supported"
  5287. )
  5288. if check_other and other_type is not None:
  5289. if _mask_dtype != other_type:
  5290. warnings.warn(
  5291. f"Support for mismatched {mask_name} and {other_name} "
  5292. "is deprecated. Use same type for both instead.",
  5293. stacklevel=2,
  5294. )
  5295. if not _mask_is_float:
  5296. mask = torch.zeros_like(mask, dtype=target_type).masked_fill_(
  5297. mask, float("-inf")
  5298. )
  5299. return mask
  5300. def _none_or_dtype(input: Optional[Tensor]) -> Optional[DType]:
  5301. if input is None:
  5302. return None
  5303. elif isinstance(input, torch.Tensor):
  5304. return input.dtype
  5305. raise RuntimeError("input to _none_or_dtype() must be None or torch.Tensor")
  5306. def _check_key_padding_mask(
  5307. key_padding_mask: torch.Tensor, src_len: int, bsz: int
  5308. ) -> None:
  5309. torch._check_with(
  5310. AssertionError,
  5311. key_padding_mask.shape[0] == bsz,
  5312. lambda: f"Expected key_padded_mask.shape[0] to be {bsz}, but got {key_padding_mask.shape[0]}",
  5313. )
  5314. torch._check_with(
  5315. AssertionError,
  5316. key_padding_mask.shape[1] == src_len,
  5317. lambda: f"Expected key_padded_mask.shape[1] to be {src_len}, but got {key_padding_mask.shape[1]}",
  5318. )
  5319. def multi_head_attention_forward(
  5320. query: Tensor,
  5321. key: Tensor,
  5322. value: Tensor,
  5323. embed_dim_to_check: int,
  5324. num_heads: int,
  5325. in_proj_weight: Optional[Tensor],
  5326. in_proj_bias: Optional[Tensor],
  5327. bias_k: Optional[Tensor],
  5328. bias_v: Optional[Tensor],
  5329. add_zero_attn: bool,
  5330. dropout_p: float,
  5331. out_proj_weight: Tensor,
  5332. out_proj_bias: Optional[Tensor],
  5333. training: bool = True,
  5334. key_padding_mask: Optional[Tensor] = None,
  5335. need_weights: bool = True,
  5336. attn_mask: Optional[Tensor] = None,
  5337. use_separate_proj_weight: bool = False,
  5338. q_proj_weight: Optional[Tensor] = None,
  5339. k_proj_weight: Optional[Tensor] = None,
  5340. v_proj_weight: Optional[Tensor] = None,
  5341. static_k: Optional[Tensor] = None,
  5342. static_v: Optional[Tensor] = None,
  5343. average_attn_weights: bool = True,
  5344. is_causal: bool = False,
  5345. ) -> tuple[Tensor, Optional[Tensor]]:
  5346. r"""Forward method for MultiHeadAttention.
  5347. See :class:`torch.nn.MultiheadAttention` for details.
  5348. Args:
  5349. query, key, value: map a query and a set of key-value pairs to an output.
  5350. See "Attention Is All You Need" for more details.
  5351. embed_dim_to_check: total dimension of the model.
  5352. num_heads: parallel attention heads.
  5353. in_proj_weight, in_proj_bias: input projection weight and bias.
  5354. bias_k, bias_v: bias of the key and value sequences to be added at dim=0.
  5355. add_zero_attn: add a new batch of zeros to the key and
  5356. value sequences at dim=1.
  5357. dropout_p: probability of an element to be zeroed.
  5358. out_proj_weight, out_proj_bias: the output projection weight and bias.
  5359. training: apply dropout if is ``True``.
  5360. key_padding_mask: if provided, specified padding elements in the key will
  5361. be ignored by the attention. This is an binary mask. When the value is True,
  5362. the corresponding value on the attention layer will be filled with -inf.
  5363. need_weights: output attn_output_weights.
  5364. Default: `True`
  5365. Note: `needs_weight` defaults to `True`, but should be set to `False`
  5366. For best performance when attention weights are not needed.
  5367. *Setting needs_weights to `True`
  5368. leads to a significant performance degradation.*
  5369. attn_mask: 2D or 3D mask that prevents attention to certain positions. A 2D mask will be broadcasted for all
  5370. the batches while a 3D mask allows to specify a different mask for the entries of each batch.
  5371. is_causal: If specified, applies a causal mask as attention mask, and ignores
  5372. attn_mask for computing scaled dot product attention.
  5373. Default: ``False``.
  5374. .. warning::
  5375. is_causal is provides a hint that the attn_mask is the
  5376. causal mask.Providing incorrect hints can result in
  5377. incorrect execution, including forward and backward
  5378. compatibility.
  5379. use_separate_proj_weight: the function accept the proj. weights for query, key,
  5380. and value in different forms. If false, in_proj_weight will be used, which is
  5381. a combination of q_proj_weight, k_proj_weight, v_proj_weight.
  5382. q_proj_weight, k_proj_weight, v_proj_weight, in_proj_bias: input projection weight and bias.
  5383. static_k, static_v: static key and value used for attention operators.
  5384. average_attn_weights: If true, indicates that the returned ``attn_weights`` should be averaged across heads.
  5385. Otherwise, ``attn_weights`` are provided separately per head. Note that this flag only has an effect
  5386. when ``need_weights=True.``. Default: True
  5387. Shape:
  5388. Inputs:
  5389. - query: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size, E is
  5390. the embedding dimension.
  5391. - key: :math:`(S, E)` or :math:`(S, N, E)`, where S is the source sequence length, N is the batch size, E is
  5392. the embedding dimension.
  5393. - value: :math:`(S, E)` or :math:`(S, N, E)` where S is the source sequence length, N is the batch size, E is
  5394. the embedding dimension.
  5395. - key_padding_mask: :math:`(S)` or :math:`(N, S)` where N is the batch size, S is the source sequence length.
  5396. If a FloatTensor is provided, it will be directly added to the value.
  5397. If a BoolTensor is provided, the positions with the
  5398. value of ``True`` will be ignored while the position with the value of ``False`` will be unchanged.
  5399. - attn_mask: 2D mask :math:`(L, S)` where L is the target sequence length, S is the source sequence length.
  5400. 3D mask :math:`(N*num_heads, L, S)` where N is the batch size, L is the target sequence length,
  5401. S is the source sequence length. attn_mask ensures that position i is allowed to attend the unmasked
  5402. positions. If a BoolTensor is provided, positions with ``True``
  5403. are not allowed to attend while ``False`` values will be unchanged. If a FloatTensor
  5404. is provided, it will be added to the attention weight.
  5405. - static_k: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
  5406. N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
  5407. - static_v: :math:`(N*num_heads, S, E/num_heads)`, where S is the source sequence length,
  5408. N is the batch size, E is the embedding dimension. E/num_heads is the head dimension.
  5409. Outputs:
  5410. - attn_output: :math:`(L, E)` or :math:`(L, N, E)` where L is the target sequence length, N is the batch size,
  5411. E is the embedding dimension.
  5412. - attn_output_weights: Only returned when ``need_weights=True``. If ``average_attn_weights=True``, returns
  5413. attention weights averaged across heads of shape :math:`(L, S)` when input is unbatched or
  5414. :math:`(N, L, S)`, where :math:`N` is the batch size, :math:`L` is the target sequence length, and
  5415. :math:`S` is the source sequence length. If ``average_attn_weights=False``, returns attention weights per
  5416. head of shape :math:`(num_heads, L, S)` when input is unbatched or :math:`(N, num_heads, L, S)`.
  5417. """
  5418. tens_ops = (
  5419. query,
  5420. key,
  5421. value,
  5422. in_proj_weight,
  5423. in_proj_bias,
  5424. bias_k,
  5425. bias_v,
  5426. out_proj_weight,
  5427. out_proj_bias,
  5428. )
  5429. if has_torch_function(tens_ops):
  5430. return handle_torch_function(
  5431. multi_head_attention_forward,
  5432. tens_ops,
  5433. query,
  5434. key,
  5435. value,
  5436. embed_dim_to_check,
  5437. num_heads,
  5438. in_proj_weight,
  5439. in_proj_bias,
  5440. bias_k,
  5441. bias_v,
  5442. add_zero_attn,
  5443. dropout_p,
  5444. out_proj_weight,
  5445. out_proj_bias,
  5446. training=training,
  5447. key_padding_mask=key_padding_mask,
  5448. need_weights=need_weights,
  5449. attn_mask=attn_mask,
  5450. is_causal=is_causal,
  5451. use_separate_proj_weight=use_separate_proj_weight,
  5452. q_proj_weight=q_proj_weight,
  5453. k_proj_weight=k_proj_weight,
  5454. v_proj_weight=v_proj_weight,
  5455. static_k=static_k,
  5456. static_v=static_v,
  5457. average_attn_weights=average_attn_weights,
  5458. )
  5459. is_batched = _mha_shape_check(
  5460. query, key, value, key_padding_mask, attn_mask, num_heads
  5461. )
  5462. # For unbatched input, we unsqueeze at the expected batch-dim to pretend that the input
  5463. # is batched, run the computation and before returning squeeze the
  5464. # batch dimension so that the output doesn't carry this temporary batch dimension.
  5465. if not is_batched:
  5466. # unsqueeze if the input is unbatched
  5467. query = query.unsqueeze(1)
  5468. key = key.unsqueeze(1)
  5469. value = value.unsqueeze(1)
  5470. if key_padding_mask is not None:
  5471. key_padding_mask = key_padding_mask.unsqueeze(0)
  5472. # set up shape vars
  5473. tgt_len, bsz, embed_dim = query.shape
  5474. src_len, _, _ = key.shape
  5475. key_padding_mask = _canonical_mask(
  5476. mask=key_padding_mask,
  5477. mask_name="key_padding_mask",
  5478. other_type=_none_or_dtype(attn_mask),
  5479. other_name="attn_mask",
  5480. target_type=query.dtype,
  5481. )
  5482. if is_causal and attn_mask is None:
  5483. raise RuntimeError(
  5484. "Need attn_mask if specifying the is_causal hint. "
  5485. "You may use the Transformer module method "
  5486. "`generate_square_subsequent_mask` to create this mask."
  5487. )
  5488. if is_causal and key_padding_mask is None and not need_weights:
  5489. # when we have a kpm or need weights, we need attn_mask
  5490. # Otherwise, we use the is_causal hint go as is_causal
  5491. # indicator to SDPA.
  5492. attn_mask = None
  5493. else:
  5494. attn_mask = _canonical_mask(
  5495. mask=attn_mask,
  5496. mask_name="attn_mask",
  5497. other_type=None,
  5498. other_name="",
  5499. target_type=query.dtype,
  5500. check_other=False,
  5501. )
  5502. if key_padding_mask is not None:
  5503. # We have the attn_mask, and use that to merge kpm into it.
  5504. # Turn off use of is_causal hint, as the merged mask is no
  5505. # longer causal.
  5506. is_causal = False
  5507. if embed_dim != embed_dim_to_check:
  5508. raise AssertionError(
  5509. f"was expecting embedding dimension of {embed_dim_to_check}, but got {embed_dim}"
  5510. )
  5511. if isinstance(embed_dim, torch.Tensor):
  5512. # embed_dim can be a tensor when JIT tracing
  5513. head_dim = embed_dim.div(num_heads, rounding_mode="trunc")
  5514. else:
  5515. head_dim = embed_dim // num_heads
  5516. if head_dim * num_heads != embed_dim:
  5517. raise AssertionError(
  5518. f"embed_dim {embed_dim} not divisible by num_heads {num_heads}"
  5519. )
  5520. if use_separate_proj_weight:
  5521. # allow MHA to have different embedding dimensions when separate projection weights are used
  5522. if key.shape[:2] != value.shape[:2]:
  5523. raise AssertionError(
  5524. f"key's sequence and batch dims {key.shape[:2]} do not match value's {value.shape[:2]}"
  5525. )
  5526. else:
  5527. if key.shape != value.shape:
  5528. raise AssertionError(
  5529. f"key shape {key.shape} does not match value shape {value.shape}"
  5530. )
  5531. #
  5532. # compute in-projection
  5533. #
  5534. if not use_separate_proj_weight:
  5535. if in_proj_weight is None:
  5536. raise AssertionError(
  5537. "use_separate_proj_weight is False but in_proj_weight is None"
  5538. )
  5539. q, k, v = _in_projection_packed(query, key, value, in_proj_weight, in_proj_bias)
  5540. else:
  5541. if q_proj_weight is None:
  5542. raise AssertionError(
  5543. "use_separate_proj_weight is True but q_proj_weight is None"
  5544. )
  5545. if k_proj_weight is None:
  5546. raise AssertionError(
  5547. "use_separate_proj_weight is True but k_proj_weight is None"
  5548. )
  5549. if v_proj_weight is None:
  5550. raise AssertionError(
  5551. "use_separate_proj_weight is True but v_proj_weight is None"
  5552. )
  5553. if in_proj_bias is None:
  5554. b_q = b_k = b_v = None
  5555. else:
  5556. b_q, b_k, b_v = in_proj_bias.chunk(3)
  5557. q, k, v = _in_projection(
  5558. query,
  5559. key,
  5560. value,
  5561. q_proj_weight,
  5562. k_proj_weight,
  5563. v_proj_weight,
  5564. b_q,
  5565. b_k,
  5566. b_v,
  5567. )
  5568. # prep attention mask
  5569. if attn_mask is not None:
  5570. # ensure attn_mask's dim is 3
  5571. if attn_mask.dim() == 2:
  5572. correct_2d_size = (tgt_len, src_len)
  5573. if attn_mask.shape != correct_2d_size:
  5574. raise RuntimeError(
  5575. f"The shape of the 2D attn_mask is {attn_mask.shape}, but should be {correct_2d_size}."
  5576. )
  5577. attn_mask = attn_mask.unsqueeze(0)
  5578. elif attn_mask.dim() == 3:
  5579. correct_3d_size = (bsz * num_heads, tgt_len, src_len)
  5580. if attn_mask.shape != correct_3d_size:
  5581. raise RuntimeError(
  5582. f"The shape of the 3D attn_mask is {attn_mask.shape}, but should be {correct_3d_size}."
  5583. )
  5584. else:
  5585. raise RuntimeError(
  5586. f"attn_mask's dimension {attn_mask.dim()} is not supported"
  5587. )
  5588. # add bias along batch dimension (currently second)
  5589. if bias_k is not None and bias_v is not None:
  5590. if static_k is not None:
  5591. raise AssertionError("bias cannot be added to static key.")
  5592. if static_v is not None:
  5593. raise AssertionError("bias cannot be added to static value.")
  5594. k = torch.cat([k, bias_k.repeat(1, bsz, 1)])
  5595. v = torch.cat([v, bias_v.repeat(1, bsz, 1)])
  5596. if attn_mask is not None:
  5597. # pyrefly: ignore [bad-argument-type]
  5598. attn_mask = pad(attn_mask, (0, 1))
  5599. if key_padding_mask is not None:
  5600. # pyrefly: ignore [bad-argument-type]
  5601. key_padding_mask = pad(key_padding_mask, (0, 1))
  5602. else:
  5603. if bias_k is not None:
  5604. raise AssertionError("bias_k is set but bias_v is None")
  5605. if bias_v is not None:
  5606. raise AssertionError("bias_v is set but bias_k is None")
  5607. #
  5608. # reshape q, k, v for multihead attention and make them batch first
  5609. #
  5610. # pyrefly: ignore [no-matching-overload]
  5611. q = q.view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
  5612. if static_k is None:
  5613. # pyrefly: ignore [no-matching-overload]
  5614. k = k.view(k.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
  5615. else:
  5616. # TODO finish disentangling control flow so we don't do in-projections when statics are passed
  5617. if static_k.size(0) != bsz * num_heads:
  5618. raise AssertionError(
  5619. f"expecting static_k.size(0) of {bsz * num_heads}, but got {static_k.size(0)}"
  5620. )
  5621. if static_k.size(2) != head_dim:
  5622. raise AssertionError(
  5623. f"expecting static_k.size(2) of {head_dim}, but got {static_k.size(2)}"
  5624. )
  5625. k = static_k
  5626. if static_v is None:
  5627. # pyrefly: ignore [no-matching-overload]
  5628. v = v.view(v.shape[0], bsz * num_heads, head_dim).transpose(0, 1)
  5629. else:
  5630. # TODO finish disentangling control flow so we don't do in-projections when statics are passed
  5631. if static_v.size(0) != bsz * num_heads:
  5632. raise AssertionError(
  5633. f"expecting static_v.size(0) of {bsz * num_heads}, but got {static_v.size(0)}"
  5634. )
  5635. if static_v.size(2) != head_dim:
  5636. raise AssertionError(
  5637. f"expecting static_v.size(2) of {head_dim}, but got {static_v.size(2)}"
  5638. )
  5639. v = static_v
  5640. # add zero attention along batch dimension (now first)
  5641. if add_zero_attn:
  5642. zero_attn_shape = (bsz * num_heads, 1, head_dim)
  5643. k = torch.cat(
  5644. # pyrefly: ignore [no-matching-overload]
  5645. [k, torch.zeros(zero_attn_shape, dtype=k.dtype, device=k.device)],
  5646. dim=1,
  5647. )
  5648. v = torch.cat(
  5649. # pyrefly: ignore [no-matching-overload]
  5650. [v, torch.zeros(zero_attn_shape, dtype=v.dtype, device=v.device)],
  5651. dim=1,
  5652. )
  5653. if attn_mask is not None:
  5654. # pyrefly: ignore [bad-argument-type]
  5655. attn_mask = pad(attn_mask, (0, 1))
  5656. if key_padding_mask is not None:
  5657. # pyrefly: ignore [bad-argument-type]
  5658. key_padding_mask = pad(key_padding_mask, (0, 1))
  5659. # update source sequence length after adjustments
  5660. src_len = k.size(1)
  5661. # merge key padding and attention masks
  5662. if key_padding_mask is not None:
  5663. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  5664. _check_key_padding_mask(key_padding_mask, src_len, bsz)
  5665. key_padding_mask = (
  5666. key_padding_mask.view(bsz, 1, 1, src_len)
  5667. .expand(-1, num_heads, -1, -1)
  5668. .reshape(bsz * num_heads, 1, src_len)
  5669. )
  5670. if attn_mask is None:
  5671. attn_mask = key_padding_mask
  5672. else:
  5673. attn_mask = attn_mask + key_padding_mask
  5674. # adjust dropout probability
  5675. if not training:
  5676. dropout_p = 0.0
  5677. #
  5678. # (deep breath) calculate attention and out projection
  5679. #
  5680. if need_weights:
  5681. _B, _Nt, E = q.shape
  5682. q_scaled = q * math.sqrt(1.0 / float(E))
  5683. if is_causal and attn_mask is None:
  5684. raise AssertionError("FIXME: is_causal not implemented for need_weights")
  5685. if attn_mask is not None:
  5686. attn_output_weights = torch.baddbmm(
  5687. attn_mask, q_scaled, k.transpose(-2, -1)
  5688. )
  5689. else:
  5690. attn_output_weights = torch.bmm(q_scaled, k.transpose(-2, -1))
  5691. attn_output_weights = softmax(attn_output_weights, dim=-1)
  5692. if dropout_p > 0.0:
  5693. attn_output_weights = dropout(attn_output_weights, p=dropout_p)
  5694. attn_output = torch.bmm(attn_output_weights, v)
  5695. attn_output = (
  5696. # pyrefly: ignore [no-matching-overload]
  5697. attn_output.transpose(0, 1).contiguous().view(tgt_len * bsz, embed_dim)
  5698. )
  5699. attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
  5700. attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
  5701. # optionally average attention weights over heads
  5702. attn_output_weights = attn_output_weights.view(bsz, num_heads, tgt_len, src_len)
  5703. if average_attn_weights:
  5704. attn_output_weights = attn_output_weights.mean(dim=1)
  5705. if not is_batched:
  5706. # squeeze the output if input was unbatched
  5707. attn_output = attn_output.squeeze(1)
  5708. attn_output_weights = attn_output_weights.squeeze(0)
  5709. return attn_output, attn_output_weights
  5710. else:
  5711. # attn_mask can be either (L,S) or (N*num_heads, L, S)
  5712. # if attn_mask's shape is (1, L, S) we need to unsqueeze to (1, 1, L, S)
  5713. # in order to match the input for SDPA of (N, num_heads, L, S)
  5714. if attn_mask is not None:
  5715. if attn_mask.size(0) == 1 and attn_mask.dim() == 3:
  5716. attn_mask = attn_mask.unsqueeze(0)
  5717. else:
  5718. attn_mask = attn_mask.view(bsz, num_heads, -1, src_len)
  5719. q = q.view(bsz, num_heads, tgt_len, head_dim)
  5720. # pyrefly: ignore [no-matching-overload]
  5721. k = k.view(bsz, num_heads, src_len, head_dim)
  5722. # pyrefly: ignore [no-matching-overload]
  5723. v = v.view(bsz, num_heads, src_len, head_dim)
  5724. attn_output = scaled_dot_product_attention(
  5725. q, k, v, attn_mask, dropout_p, is_causal
  5726. )
  5727. attn_output = (
  5728. # pyrefly: ignore [no-matching-overload]
  5729. attn_output.permute(2, 0, 1, 3).contiguous().view(bsz * tgt_len, embed_dim)
  5730. )
  5731. attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
  5732. attn_output = attn_output.view(tgt_len, bsz, attn_output.size(1))
  5733. if not is_batched:
  5734. # squeeze the output if input was unbatched
  5735. attn_output = attn_output.squeeze(1)
  5736. return attn_output, None
  5737. def grouped_mm(
  5738. mat_a: Tensor,
  5739. mat_b: Tensor,
  5740. *,
  5741. offs: Optional[Tensor] = None,
  5742. bias: Optional[Tensor] = None,
  5743. out_dtype: Optional[torch.dtype] = None,
  5744. ) -> Tensor:
  5745. r"""
  5746. grouped_mm(mat_a, mat_b, *, offs=None, bias=None, out_dtype=None)
  5747. Computes a grouped matrix multiply that shares weight shapes across experts but
  5748. allows jagged token counts per expert, which is common in Mixture-of-Experts
  5749. (MoE) layers. Both ``mat_a`` and ``mat_b`` must be 2D or 3D tensors that already
  5750. satisfy the physical layout restrictions of grouped GEMM kernels (e.g., row-major
  5751. ``mat_a`` and column-major ``mat_b`` for FP8 inputs). Inputs are currently
  5752. expected to be ``torch.bfloat16`` values on CUDA devices with :math:`SM \ge 80`.
  5753. Args:
  5754. mat_a: Left operand. When 2D, its leading dimension is sliced into groups
  5755. according to ``offs``. When 3D, its first dimension enumerates the groups
  5756. directly and ``offs`` must be ``None``.
  5757. mat_b: Right operand. When both operands are 2D (e.g., MoE weight-gradient
  5758. updates), the trailing dimension of ``mat_a`` and the leading dimension of
  5759. ``mat_b`` are partitioned according to the same ``offs`` tensor. For the
  5760. common forward pass (``out = input @ weight.T``) ``mat_b`` is 3D with
  5761. shape ``(num_groups, N, K)``.
  5762. offs: Optional 1D tensor of monotonically increasing ``int32`` offsets that
  5763. delimit the jagged dimension of any 2D operand. ``offs[i]`` marks the end
  5764. of group ``i`` and ``offs[-1]`` must be strictly less than the total
  5765. length of that operand's sliced dimension; elements beyond ``offs[-1]``
  5766. are ignored.
  5767. bias: Optional tensor that is added to the grouped outputs. Bias is not
  5768. jagged and must be broadcastable to the result shape of each group.
  5769. out_dtype: Optional dtype that controls the accumulation/output dtype.
  5770. Passing ``torch.float32`` accumulates BF16 inputs in FP32 while keeping
  5771. the grouped GEMM API non-differentiable.
  5772. Returns:
  5773. A tensor containing the concatenated results of each per-group GEMM with
  5774. shape inferred from the operands and ``offs``.
  5775. """
  5776. return torch._grouped_mm(mat_a, mat_b, offs=offs, bias=bias, out_dtype=out_dtype)
  5777. def scaled_mm(
  5778. mat_a: Tensor,
  5779. mat_b: Tensor,
  5780. scale_a: Tensor | list[Tensor],
  5781. scale_recipe_a: ScalingType | list[ScalingType],
  5782. scale_b: Tensor | list[Tensor],
  5783. scale_recipe_b: ScalingType | list[ScalingType],
  5784. swizzle_a: SwizzleType | list[SwizzleType] | None = None,
  5785. swizzle_b: SwizzleType | list[SwizzleType] | None = None,
  5786. bias: Optional[Tensor] = None,
  5787. output_dtype: Optional[torch.dtype] = torch.bfloat16,
  5788. contraction_dim: list[int] | tuple[int, ...] = (),
  5789. use_fast_accum: bool = False,
  5790. ) -> Tensor:
  5791. r"""
  5792. scaled_mm(mat_a, mat_b, scale_a, scale_recipe_a, scale_b, scale_recipe_b, swizzle_a, swizzle_b, bias, output_dtype,
  5793. contraction_dim, use_fast_accum)
  5794. Applies a scaled matrix-multiply, mm(mat_a, mat_b) where the scaling of mat_a and mat_b are described by
  5795. scale_recipe_a and scale_recipe_b respectively.
  5796. Args:
  5797. scale_a: Tensor containing decoding scaling factors for mat_a
  5798. scale_recipe_a: Enum describing how mat_a has been scaled
  5799. scale_b: Tensor containing decoding scaling factors for mat_b
  5800. scale_recipe_b: Enum describing how mat_b has been scaled
  5801. swizzle_a: Enum describing the swizzling pattern (if any) of scale_a
  5802. swizzle_b: Enum describing the swizzling pattern (if any) of scale_b
  5803. bias: optional bias term to be added to the output
  5804. output_dtype: dtype used for the output tensor
  5805. contraction_dim: describe which dimensions are :math:`K` in the matmul.
  5806. use_fast_accum: enable/disable tensor-core fast accumulation (Hopper-GPUs only)
  5807. """
  5808. def expand_single_value(v: _Any | list[_Any] | None) -> list[_Any]:
  5809. if v is None:
  5810. return []
  5811. elif not isinstance(v, (list)):
  5812. return [
  5813. v,
  5814. ]
  5815. else:
  5816. return v
  5817. scale_a = expand_single_value(scale_a)
  5818. scale_recipe_a = expand_single_value(scale_recipe_a)
  5819. scale_b = expand_single_value(scale_b)
  5820. scale_recipe_b = expand_single_value(scale_recipe_b)
  5821. swizzle_a = expand_single_value(swizzle_a)
  5822. swizzle_b = expand_single_value(swizzle_b)
  5823. # native_functions has restrictions on what can be defined
  5824. # & passed through - std::optional<ArrayRef<Tensor>> for instance
  5825. # *cannot* be passed, but an empty vector (list) can.
  5826. # So, we need to convert None arguments for lists in python
  5827. # explicitly into empty lists.
  5828. def list_or_empty(l: list[_Any] | None) -> list[_Any]:
  5829. return l if l else []
  5830. def enum_list_as_int_list(l: _Any | list[_Any]) -> list[_Any]:
  5831. if not isinstance(l, list):
  5832. l = [
  5833. l,
  5834. ]
  5835. return [li.value for li in l]
  5836. out = torch._scaled_mm_v2(
  5837. mat_a,
  5838. mat_b,
  5839. scale_a,
  5840. enum_list_as_int_list(scale_recipe_a),
  5841. enum_list_as_int_list(list_or_empty(swizzle_a)),
  5842. scale_b,
  5843. enum_list_as_int_list(scale_recipe_b),
  5844. enum_list_as_int_list(list_or_empty(swizzle_b)),
  5845. bias,
  5846. output_dtype,
  5847. contraction_dim,
  5848. use_fast_accum,
  5849. )
  5850. return out
  5851. def scaled_grouped_mm(
  5852. mat_a: Tensor,
  5853. mat_b: Tensor,
  5854. scale_a: Tensor | list[Tensor],
  5855. scale_recipe_a: ScalingType | list[ScalingType],
  5856. scale_b: Tensor | list[Tensor],
  5857. scale_recipe_b: ScalingType | list[ScalingType],
  5858. swizzle_a: SwizzleType | list[SwizzleType] | None = None,
  5859. swizzle_b: SwizzleType | list[SwizzleType] | None = None,
  5860. bias: Optional[Tensor] = None,
  5861. offs: Optional[Tensor] = None,
  5862. output_dtype: Optional[torch.dtype] = torch.bfloat16,
  5863. contraction_dim: list[int] | tuple[int, ...] = (),
  5864. use_fast_accum: bool = False,
  5865. ) -> Tensor:
  5866. r"""
  5867. scaled_grouped_mm(mat_a, mat_b, scale_a, scale_recipe_a, scale_b, scale_recipe_b, swizzle_a, swizzle_b, bias, offs,
  5868. output_dtype, use_fast_accum)
  5869. Applies a grouped scaled matrix-multiply, grouped_mm(mat_a, mat_b) where the scaling of mat_a and mat_b are described by
  5870. scale_recipe_a and scale_recipe_b respectively.
  5871. Args:
  5872. scale_a: Tensor containing decoding scaling factors for mat_a
  5873. scale_recipe_a: Enum describing how mat_a has been scaled
  5874. scale_b: Tensor containing decoding scaling factors for mat_b
  5875. scale_recipe_b: Enum describing how mat_b has been scaled
  5876. swizzle_a: Enum describing the swizzling pattern (if any) of scale_a
  5877. swizzle_b: Enum describing the swizzling pattern (if any) of scale_b
  5878. bias: optional bias term to be added to the output
  5879. offs: optional offsets into the source tensors denoting group start indices
  5880. output_dtype: dtype used for the output tensor
  5881. contraction_dim: describe which dimensions are :math:`K` in the matmul.
  5882. use_fast_accum: enable/disable tensor-core fast accumulation (Hopper-GPUs only)
  5883. """
  5884. def expand_single_value(v: _Any | list[_Any] | None) -> list[_Any]:
  5885. if v is None:
  5886. return []
  5887. elif not isinstance(v, (list)):
  5888. return [
  5889. v,
  5890. ]
  5891. else:
  5892. return v
  5893. scale_a = expand_single_value(scale_a)
  5894. scale_recipe_a = expand_single_value(scale_recipe_a)
  5895. scale_b = expand_single_value(scale_b)
  5896. scale_recipe_b = expand_single_value(scale_recipe_b)
  5897. swizzle_a = expand_single_value(swizzle_a)
  5898. swizzle_b = expand_single_value(swizzle_b)
  5899. # native_functions has restrictions on what can be defined
  5900. # & passed through - std::optional<ArrayRef<Tensor>> for instance
  5901. # *cannot* be passed, but an empty vector (list) can.
  5902. # So, we need to convert None arguments for lists in python
  5903. # explicitly into empty lists.
  5904. def list_or_empty(l: list[_Any] | None) -> list[_Any]:
  5905. return l if l else []
  5906. def enum_list_as_int_list(l: _Any | list[_Any]) -> list[_Any]:
  5907. if not isinstance(l, list):
  5908. l = [
  5909. l,
  5910. ]
  5911. return [li.value for li in l]
  5912. out = torch._scaled_grouped_mm_v2(
  5913. mat_a,
  5914. mat_b,
  5915. scale_a,
  5916. enum_list_as_int_list(scale_recipe_a),
  5917. enum_list_as_int_list(list_or_empty(swizzle_a)),
  5918. scale_b,
  5919. enum_list_as_int_list(scale_recipe_b),
  5920. enum_list_as_int_list(list_or_empty(swizzle_b)),
  5921. offs,
  5922. bias,
  5923. output_dtype,
  5924. contraction_dim,
  5925. use_fast_accum,
  5926. )
  5927. return out