functional.py 207 KB

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