functional.py 239 KB

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