functional.py 213 KB

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