functional.py 252 KB

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