functional.py 223 KB

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