_meta_registrations.py 245 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968
  1. # mypy: allow-untyped-defs
  2. import math
  3. from collections.abc import Sequence
  4. from enum import Enum
  5. from functools import wraps
  6. from typing import Callable, Optional, TypeVar, Union
  7. from typing_extensions import ParamSpec
  8. import torch
  9. import torch._prims_common as utils
  10. from torch import SymBool, SymFloat, Tensor
  11. from torch._decomp import (
  12. _add_op_to_registry,
  13. _convert_out_params,
  14. global_decomposition_table,
  15. meta_table,
  16. )
  17. from torch._ops import OpOverload
  18. from torch._prims import _prim_elementwise_meta, ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND
  19. from torch._prims_common import (
  20. BoolLike,
  21. corresponding_complex_dtype,
  22. corresponding_real_dtype,
  23. elementwise_dtypes,
  24. ELEMENTWISE_TYPE_PROMOTION_KIND,
  25. FloatLike,
  26. IntLike,
  27. make_contiguous_strides_for,
  28. Number,
  29. suggest_memory_format,
  30. TensorLike,
  31. )
  32. from torch._prims_common.wrappers import (
  33. _maybe_convert_to_dtype,
  34. _maybe_resize_out,
  35. _resize_output_check,
  36. _safe_copy_out,
  37. out_wrapper,
  38. )
  39. from torch._refs import _broadcast_shapes, _maybe_broadcast
  40. from torch.fx.experimental import _config as exp_config
  41. from torch.utils import _pytree as pytree
  42. _T = TypeVar("_T")
  43. _P = ParamSpec("_P")
  44. aten = torch.ops.aten
  45. _meta_lib_dont_use_me_use_register_meta = torch.library.Library("aten", "IMPL", "Meta")
  46. MODE_SUM, MODE_MEAN, MODE_MAX = range(3)
  47. def register_meta(op) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
  48. def wrapper(fn):
  49. fn = _convert_out_params(fn)
  50. def register(op):
  51. _add_op_to_registry(meta_table, op, fn)
  52. pytree.tree_map_(register, op)
  53. return fn
  54. return wrapper
  55. def elementwise_meta(
  56. *args,
  57. type_promotion: ELEMENTWISE_TYPE_PROMOTION_KIND,
  58. ):
  59. # Perform type promotion, as this is expected from prim_metafunction
  60. _, result_dtype = utils.elementwise_dtypes(
  61. *args,
  62. type_promotion_kind=type_promotion,
  63. )
  64. args = [_maybe_convert_to_dtype(x, result_dtype) for x in args]
  65. # Broadcast
  66. args = _maybe_broadcast(*args)
  67. # Perform prim checks
  68. return _prim_elementwise_meta(
  69. *args, type_promotion=ELEMENTWISE_PRIM_TYPE_PROMOTION_KIND.DEFAULT
  70. )
  71. def toRealValueType(dtype):
  72. from_complex = {
  73. torch.complex32: torch.half,
  74. torch.cfloat: torch.float,
  75. torch.cdouble: torch.double,
  76. }
  77. return from_complex.get(dtype, dtype)
  78. def check_inplace_broadcast(self_shape, *args_shape):
  79. broadcasted_shape = tuple(_broadcast_shapes(self_shape, *args_shape))
  80. torch._check(
  81. broadcasted_shape == self_shape,
  82. lambda: f"output with shape {self_shape} doesn't match the broadcast shape {broadcasted_shape}",
  83. )
  84. @register_meta([aten.linspace, aten.logspace])
  85. @out_wrapper()
  86. def meta_linspace_logspace(
  87. start,
  88. end,
  89. steps,
  90. base=None,
  91. dtype=None,
  92. device=None,
  93. layout=torch.strided,
  94. pin_memory=False,
  95. requires_grad=False,
  96. ):
  97. if isinstance(start, torch.Tensor):
  98. torch._check(
  99. start.dim() == 0,
  100. lambda: "linspace only supports 0-dimensional start and end tensors",
  101. )
  102. if isinstance(end, torch.Tensor):
  103. torch._check(
  104. end.dim() == 0,
  105. lambda: "linspace only supports 0-dimensional start and end tensors",
  106. )
  107. if any(isinstance(arg, complex) for arg in (start, end, steps)):
  108. default_complex_dtype = utils.corresponding_complex_dtype(
  109. torch.get_default_dtype()
  110. )
  111. if dtype is None:
  112. dtype = default_complex_dtype
  113. else:
  114. torch._check(
  115. utils.is_complex_dtype(dtype),
  116. lambda: f"linspace(): inferred dtype {default_complex_dtype} can't be safely cast to passed dtype {dtype}",
  117. )
  118. else:
  119. dtype = dtype or torch.get_default_dtype()
  120. assert isinstance(dtype, torch.dtype)
  121. # steps does not participate in the computation of the dtype
  122. torch._check_type(
  123. isinstance(steps, IntLike),
  124. lambda: f"received an invalid combination of arguments - got \
  125. ({type(start).__name__}, {type(end).__name__}, {type(steps).__name__})",
  126. )
  127. assert isinstance(steps, IntLike) # for mypy
  128. torch._check(steps >= 0, lambda: "number of steps must be non-negative")
  129. return torch.empty(
  130. (steps,), # type: ignore[arg-type]
  131. dtype=dtype,
  132. layout=layout,
  133. device="meta",
  134. pin_memory=pin_memory,
  135. requires_grad=requires_grad,
  136. )
  137. @register_meta([aten.take.default, aten.take.out])
  138. @out_wrapper()
  139. def meta_take(self, index):
  140. # Type and device checks
  141. torch._check(
  142. index.dtype == torch.long,
  143. lambda: f"take(): Expected a long tensor for index, but got {index.dtype}",
  144. )
  145. # Index checks
  146. torch._check_index(
  147. not (self.numel() == 0 and index.numel() != 0),
  148. lambda: "take(): tried to take from an empty tensor",
  149. )
  150. return self.new_empty(index.shape)
  151. @register_meta([aten.linalg_cross.default, aten.linalg_cross.out])
  152. @out_wrapper()
  153. def linalg_cross(self, other, *, dim=-1):
  154. x_d = self.ndim
  155. y_d = other.ndim
  156. torch._check(
  157. x_d == y_d,
  158. lambda: "linalg.cross: inputs must have the same number of dimensions.",
  159. )
  160. torch._check(
  161. self.size(dim) == 3 and other.size(dim) == 3,
  162. lambda: (
  163. f"linalg.cross: inputs dimension {dim} must have length 3. "
  164. f"Got {self.size(dim)} and {other.size(dim)}"
  165. ),
  166. )
  167. out_shape = _broadcast_shapes(self.shape, other.shape)
  168. return self.new_empty(out_shape)
  169. @register_meta(aten.linalg_matrix_exp)
  170. @out_wrapper()
  171. def linalg_matrix_exp(self):
  172. squareCheckInputs(self, "linalg.matrix_exp")
  173. checkFloatingOrComplex(self, "linalg.matrix_exp")
  174. return torch.empty_like(self, memory_format=torch.contiguous_format)
  175. @register_meta(
  176. [aten.cummax.default, aten.cummax.out, aten.cummin.default, aten.cummin.out]
  177. )
  178. @out_wrapper("values", "indices")
  179. def cummaxmin(self, dim):
  180. values = torch.empty(self.shape, device=self.device, dtype=self.dtype)
  181. indices = torch.empty(self.shape, device=self.device, dtype=torch.int64)
  182. if self.numel() != 0 and self.ndim != 0:
  183. # Checks that dim is within bounds
  184. maybe_wrap_dim(dim, self.ndim)
  185. return values, indices
  186. @register_meta([aten.logcumsumexp.default, aten.logcumsumexp.out])
  187. @out_wrapper()
  188. def logcumsumexp(self, dim):
  189. # Checks that dim is within bounds
  190. maybe_wrap_dim(dim, self.ndim)
  191. return torch.empty_like(self, memory_format=torch.contiguous_format)
  192. # Stride-related code from _exec_fft in aten/src/ATen/native/mkl/SpectralOps.cpp
  193. # and aten/src/ATen/cuda/SpectralOps.cpp
  194. #
  195. # Although the actual FFT launch is different, all the permuting code appears
  196. # to be the same
  197. def _exec_fft(out, self, out_sizes, dim, *, forward):
  198. ndim = self.ndim
  199. signal_ndim = len(dim)
  200. batch_dims = ndim - signal_ndim
  201. # Permute dimensions so batch dimensions come first, and in stride order
  202. dim_permute = list(range(ndim))
  203. is_transformed_dim = [False for _ in range(ndim)]
  204. for d in dim:
  205. is_transformed_dim[d] = True
  206. # std::partition
  207. left, right = [], []
  208. for d in dim_permute:
  209. if not is_transformed_dim[d]:
  210. left.append(d)
  211. else:
  212. right.append(d)
  213. dim_permute = left + right
  214. batch_end = len(left)
  215. self_strides = self.stride()
  216. tmp = dim_permute[:batch_end]
  217. tmp.sort(key=lambda x: self_strides[x], reverse=True)
  218. dim_permute = tmp + dim_permute[batch_end:]
  219. input = self.permute(dim_permute)
  220. # Collapse batch dimensions into a single dimension
  221. batched_sizes = [-1] + list(input.shape[batch_dims:])
  222. input = input.reshape(batched_sizes)
  223. batch_size = input.size(0)
  224. batched_sizes[0] = batch_size
  225. batched_out_sizes = list(batched_sizes)
  226. for i in range(len(dim)):
  227. batched_out_sizes[i + 1] = out_sizes[dim[i]]
  228. out.resize_(batched_out_sizes, memory_format=torch.contiguous_format)
  229. # Inplace reshaping to original batch shape and inverting the dimension permutation
  230. out_strides = [0 for _ in range(ndim)]
  231. batch_numel = 1
  232. i = batch_dims - 1
  233. while i >= 0:
  234. out_strides[dim_permute[i]] = batch_numel * out.stride(0)
  235. batch_numel *= out_sizes[dim_permute[i]]
  236. i -= 1
  237. for i in range(batch_dims, ndim):
  238. out_strides[dim_permute[i]] = out.stride(1 + (i - batch_dims))
  239. out.as_strided_(out_sizes, out_strides, out.storage_offset())
  240. return out
  241. def _sort_dims(self: Tensor, dim: list[int], exclude_last: bool = False):
  242. sorted_dims = list(dim)
  243. self_strides = self.stride()
  244. sorted_dims[: len(sorted_dims) - int(exclude_last)].sort(
  245. key=lambda i: self_strides[i]
  246. )
  247. return sorted_dims
  248. # See _fft_c2c_cufft in aten/src/ATen/native/cuda/SpectralOps.cpp
  249. # and _fft_c2c_mkl in aten/src/ATen/native/mkl/SpectralOps.cpp
  250. @register_meta([aten._fft_c2c.default, aten._fft_c2c.out])
  251. @out_wrapper()
  252. def meta_fft_c2c(self, dim, normalization, forward):
  253. torch._check(self.dtype.is_complex)
  254. if not dim:
  255. return self.clone()
  256. sorted_dims = _sort_dims(self, dim)
  257. out = self.new_empty(self.size())
  258. return _exec_fft(out, self, self.size(), sorted_dims, forward=forward)
  259. cufft_max_ndim = 3
  260. def use_optimized_cufft_path(dim: list[int]):
  261. if len(dim) > cufft_max_ndim or (len(dim) >= 2 and dim[0] == 0 and dim[1] == 1):
  262. return False
  263. else:
  264. return True
  265. @register_meta([aten._fft_r2c.default, aten._fft_r2c.out])
  266. @out_wrapper()
  267. def meta_fft_r2c(self, dim, normalization, onesided):
  268. torch._check(self.dtype.is_floating_point)
  269. input_sizes = list(self.size())
  270. out_sizes = list(input_sizes)
  271. last_dim = dim[-1]
  272. last_dim_halfsize = input_sizes[last_dim] // 2 + 1
  273. onesided_sizes = list(input_sizes)
  274. onesided_sizes[last_dim] = last_dim_halfsize
  275. if onesided:
  276. out_sizes[last_dim] = last_dim_halfsize
  277. if device_hint(self) == "cuda" or device_hint(self) == "xpu":
  278. # _fft_r2c_cufft in aten/src/ATen/native/cuda/SpectralOps.cpp
  279. # _fft_r2c_xpu in torch-xpu-ops/src/ATen/native/xpu/SpectralOps.cpp
  280. output = self.new_empty(
  281. out_sizes, dtype=utils.corresponding_complex_dtype(self.dtype)
  282. )
  283. working_tensor = self
  284. if device_hint(self) == "cuda" and use_optimized_cufft_path(dim):
  285. _exec_fft(output, working_tensor, out_sizes, dim, forward=True)
  286. else:
  287. # First do the R2C transform on the last dimension
  288. target_sizes = out_sizes if len(dim) == 1 else onesided_sizes
  289. _exec_fft(output, working_tensor, target_sizes, [last_dim], forward=True)
  290. if len(dim) > 1:
  291. working_tensor = self.new_empty(
  292. out_sizes, dtype=utils.corresponding_complex_dtype(self.dtype)
  293. )
  294. # Then any remaining C2C transforms
  295. sorted_dims = dim[:-1]
  296. while sorted_dims:
  297. output, working_tensor = working_tensor, output
  298. strides = working_tensor.stride()
  299. sorted_dims.sort(
  300. key=lambda i: strides[i], reverse=True
  301. ) # NB reverse! Not sure if this is og bug
  302. max_dims = min(cufft_max_ndim, len(sorted_dims))
  303. last_dims = sorted_dims[len(sorted_dims) - max_dims :]
  304. _exec_fft(
  305. output, working_tensor, onesided_sizes, last_dims, forward=True
  306. )
  307. sorted_dims = sorted_dims[: len(sorted_dims) - max_dims]
  308. if not onesided:
  309. if output.size(last_dim) != out_sizes[last_dim]:
  310. working_tensor.resize_(out_sizes, memory_format=torch.contiguous_format)
  311. output = working_tensor
  312. return output
  313. else:
  314. return self.new_empty(
  315. out_sizes, dtype=utils.corresponding_complex_dtype(self.dtype)
  316. )
  317. @register_meta(aten.randperm.generator_out)
  318. def meta_randperm(n, *, generator=None, out):
  319. return _maybe_resize_out(out, torch.Size([n]))
  320. @register_meta(aten.randperm.default)
  321. def meta_randperm_default(
  322. n,
  323. *,
  324. dtype=torch.long,
  325. layout=None,
  326. device=None,
  327. pin_memory=None,
  328. ):
  329. return torch.empty(
  330. n, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
  331. )
  332. @register_meta([aten.randint.default, aten.randint.out])
  333. @out_wrapper()
  334. def meta_randint(
  335. high,
  336. size,
  337. *,
  338. dtype=torch.long,
  339. layout=None,
  340. device=None,
  341. pin_memory=None,
  342. ):
  343. low = 0
  344. torch._check(
  345. high > low,
  346. lambda: f"random_ expects 'from' to be less than 'to', but got from={low} >= to={high}",
  347. )
  348. return torch.empty(
  349. size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
  350. )
  351. @register_meta([aten.randint.low, aten.randint.low_out])
  352. @out_wrapper()
  353. def meta_randint_low(
  354. low,
  355. high,
  356. size,
  357. *,
  358. dtype=torch.long,
  359. layout=None,
  360. device=None,
  361. pin_memory=None,
  362. ):
  363. torch._check(
  364. high > low,
  365. lambda: f"random_ expects 'from' to be less than 'to', but got from={low} >= to={high}",
  366. )
  367. return torch.empty(
  368. size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
  369. )
  370. @register_meta([aten.rand.default, aten.rand.out])
  371. @out_wrapper()
  372. def meta_rand_default(size, *, dtype=None, layout=None, device=None, pin_memory=None):
  373. return torch.empty(
  374. size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
  375. )
  376. @register_meta([aten._fft_c2r.default, aten._fft_c2r.out])
  377. @out_wrapper()
  378. def meta_fft_c2r(self: Tensor, dim: list[int], normalization: int, lastdim: int):
  379. # _fft_c2r_mkl
  380. torch._check(self.dtype.is_complex)
  381. if device_hint(self) == "cuda":
  382. out_sizes = list(self.size())
  383. out_sizes[dim[-1]] = lastdim
  384. output = self.new_empty(out_sizes, dtype=toRealValueType(self.dtype))
  385. if use_optimized_cufft_path(dim):
  386. return _exec_fft(
  387. output,
  388. self.clone(memory_format=torch.contiguous_format),
  389. out_sizes,
  390. dim,
  391. forward=False,
  392. )
  393. else:
  394. # First complete any C2C transforms
  395. if len(dim) > 1:
  396. temp = meta_fft_c2c(self, dim[:-1], 0, lastdim) # fft_norm_mode::none
  397. else:
  398. temp = self.clone(memory_format=torch.contiguous_format)
  399. return _exec_fft(output, temp, out_sizes, [dim[-1]], forward=False)
  400. else:
  401. input = self
  402. if len(dim) > 1:
  403. c2c_dims = dim[:-1]
  404. input = meta_fft_c2c(self, c2c_dims, normalization, forward=False)
  405. dim = dim[-1:]
  406. out_sizes = list(input.size())
  407. out_sizes[dim[-1]] = lastdim
  408. out = self.new_empty(out_sizes, dtype=toRealValueType(self.dtype))
  409. return _exec_fft(out, input, out_sizes, dim, forward=False)
  410. @register_meta(aten.copy_.default)
  411. def meta_copy_(self, src, non_blocking=False):
  412. # This code simulates the original decomp from inductor,
  413. # which runs most of the meta checks that we care about.
  414. # In theory, we should make this more robust by carefully
  415. # auditing our C++ copy_() kernel and copying the checks here.
  416. from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols
  417. # TODO: Ideally, we'd insert a deferred runtime assert here, but if we are
  418. # calling an actual copy_, you'll get that automatically
  419. # https://github.com/pytorch/pytorch/issues/122477
  420. if (
  421. not free_unbacked_symbols(self) and torch._debug_has_internal_overlap(self) == 1
  422. ): # 1 == MemOverlap::Yes
  423. raise RuntimeError(
  424. "more than one element of the written-to tensor refers to a single memory location"
  425. )
  426. if isinstance(src, Tensor):
  427. intermediate = src.to(self, non_blocking)
  428. if self.size() != intermediate.size():
  429. aten.expand_copy.default(intermediate, self.size())
  430. return self
  431. def inferUnsqueezeGeometry(tensor, dim):
  432. result_sizes = list(tensor.size())
  433. result_strides = list(tensor.stride())
  434. new_stride = 1 if dim >= tensor.dim() else result_sizes[dim] * result_strides[dim]
  435. result_sizes.insert(dim, 1)
  436. result_strides.insert(dim, new_stride)
  437. return result_sizes, result_strides
  438. @register_meta(aten.unsqueeze_.default)
  439. def meta_unsqueeze_(self, dim):
  440. dim = maybe_wrap_dim(dim, self.dim() + 1)
  441. g_sizes, g_strides = inferUnsqueezeGeometry(self, dim)
  442. self.as_strided_(g_sizes, g_strides)
  443. return self
  444. @register_meta(aten._sparse_semi_structured_linear)
  445. def meta_sparse_structured_linear(
  446. input: Tensor,
  447. weight: Tensor,
  448. _meta: Tensor,
  449. bias: Optional[Tensor] = None,
  450. _activation_opt: Optional[str] = None,
  451. out_dtype: Optional[torch.dtype] = None,
  452. ):
  453. output_sizes = list(input.shape)
  454. if bias is not None:
  455. assert weight.size(0) == bias.size(0), "output size mismatch"
  456. assert weight.size(1) == input.size(-1) / 2
  457. output_sizes[-1] = weight.size(0)
  458. # see: https://github.com/pytorch/pytorch/pull/114477#issuecomment-1830121375
  459. # We assume that we have already squashed the inputs into a 2-D tensor
  460. # Then, as the output is transposed, we need to propagate the transposed
  461. # stride information to the output tensor
  462. assert len(input.shape) == 2, "we can only handle the squashed input case"
  463. transposed_strides = (1, input.size(0))
  464. if out_dtype is not None:
  465. assert input.dtype == torch.int8 and out_dtype == torch.int32, (
  466. "out_dtype is only supported for i8i8->i32 linear operator"
  467. )
  468. output = input.new_empty(
  469. output_sizes,
  470. dtype=input.dtype if out_dtype is None else out_dtype,
  471. ).as_strided(output_sizes, transposed_strides)
  472. return output
  473. @register_meta(aten._sparse_semi_structured_mm)
  474. def meta_sparse_structured_mm(
  475. mat1: Tensor,
  476. mat1_meta: Tensor,
  477. mat2: Tensor,
  478. out_dtype: Optional[torch.dtype] = None,
  479. ):
  480. assert len(mat1.shape) == 2
  481. assert len(mat1_meta.shape) == 2
  482. assert len(mat2.shape) == 2
  483. assert mat1.size(1) == mat2.size(0) / 2
  484. output_sizes = [mat1.size(0), mat2.size(1)]
  485. if out_dtype is not None:
  486. assert mat2.dtype == torch.int8 and out_dtype == torch.int32, (
  487. "out_dtype is only supported for i8i8->i32 linear operator"
  488. )
  489. output = mat2.new_empty(
  490. output_sizes,
  491. dtype=mat2.dtype if out_dtype is None else out_dtype,
  492. )
  493. return output
  494. @register_meta(aten._sparse_semi_structured_addmm)
  495. def meta_sparse_structured_addmm(
  496. input: Tensor,
  497. mat1: Tensor,
  498. mat1_meta: Tensor,
  499. mat2: Tensor,
  500. *,
  501. alpha=1,
  502. beta=1,
  503. out_dtype: Optional[torch.dtype] = None,
  504. ):
  505. assert len(input.shape) == 1, (
  506. "only input broadcasted to columns of mat1 * mat2 product is supported"
  507. )
  508. assert len(mat1.shape) == 2
  509. assert len(mat1_meta.shape) == 2
  510. assert len(mat2.shape) == 2
  511. assert input.size(0) == mat1.size(0), (
  512. "only input broadcasted to columns of mat1 * mat2 product is supported"
  513. )
  514. assert mat1.size(1) == mat2.size(0) / 2
  515. output_sizes = [mat1.size(0), mat2.size(1)]
  516. if out_dtype is not None:
  517. assert mat2.dtype == torch.int8 and out_dtype == torch.int32, (
  518. "out_dtype is only supported for i8i8->i32 linear operator"
  519. )
  520. output = mat2.new_empty(
  521. output_sizes,
  522. dtype=mat2.dtype if out_dtype is None else out_dtype,
  523. )
  524. return output
  525. @register_meta(aten._cslt_sparse_mm)
  526. def meta__cslt_sparse_mm(
  527. compressed_A: torch.Tensor,
  528. dense_B: torch.Tensor,
  529. bias: Optional[Tensor] = None,
  530. alpha: Optional[Tensor] = None,
  531. out_dtype: Optional[torch.dtype] = None,
  532. transpose_result: bool = False,
  533. alg_id: int = 0,
  534. split_k: int = 1,
  535. split_k_mode: int = -1,
  536. ):
  537. assert dense_B.dtype in {
  538. torch.float32,
  539. torch.float16,
  540. torch.bfloat16,
  541. torch.int8,
  542. torch.float8_e4m3fn,
  543. }, "_cslt_sparse_mm only supports fp16, bf16, int8, and fp8e4m3"
  544. assert compressed_A.dtype == dense_B.dtype, "inputs must have the same dtype"
  545. assert len(dense_B.shape) == 2, "_cslt_sparse_mm only supports 2d inputs"
  546. is_8bit_input_type = compressed_A.dtype in [torch.int8, torch.float8_e4m3fn]
  547. compression_factor = 10 if is_8bit_input_type else 9
  548. if is_8bit_input_type:
  549. assert not dense_B.is_contiguous(), (
  550. "dense input must be transposed for 8bit dtypes"
  551. )
  552. k = dense_B.size(0)
  553. n = dense_B.size(1)
  554. m = (compressed_A.numel() * 16) // (compression_factor * k)
  555. if bias is not None:
  556. assert m == bias.size(0)
  557. if out_dtype is not None:
  558. assert is_8bit_input_type and out_dtype in {
  559. torch.float16,
  560. torch.bfloat16,
  561. torch.int32,
  562. torch.float8_e4m3fn,
  563. }, (
  564. "out_dtype is not supported for {compressed_A.dtype} x {dense_B.dtype} -> {out_dtype} matmul!"
  565. )
  566. output_shape = (n, m) if transpose_result else (m, n)
  567. return dense_B.new_empty(output_shape, dtype=out_dtype)
  568. @register_meta(aten.index_reduce.default)
  569. def meta_index_reduce(
  570. self: Tensor,
  571. dim: int,
  572. index: Tensor,
  573. source: torch.Tensor,
  574. reduce: str,
  575. *,
  576. include_self: bool = True,
  577. ) -> Tensor:
  578. return torch.empty_like(self, memory_format=torch.contiguous_format)
  579. @register_meta(aten.index_reduce_.default)
  580. def meta_index_reduce_(
  581. self: Tensor,
  582. dim: int,
  583. index: Tensor,
  584. source: torch.Tensor,
  585. reduce: str,
  586. *,
  587. include_self: bool = True,
  588. ) -> Tensor:
  589. return self
  590. # Implementations below are taken from https://github.com/albanD/subclass_zoo/blob/main/python_meta_tensor.py
  591. @out_wrapper()
  592. @register_meta(aten.index_select.default)
  593. def meta_index_select(self, dim, index):
  594. result_size = list(self.size())
  595. if self.dim() > 0:
  596. result_size[dim] = index.numel()
  597. return self.new_empty(result_size)
  598. @register_meta(aten.segment_reduce.default)
  599. def meta_segment_reduce(
  600. data: Tensor,
  601. reduce: str,
  602. *,
  603. lengths: Optional[Tensor] = None,
  604. indices: Optional[Tensor] = None,
  605. offsets: Optional[Tensor] = None,
  606. axis: int = 0,
  607. unsafe: bool = False,
  608. initial=None,
  609. ) -> Tensor:
  610. if indices is not None:
  611. raise NotImplementedError(
  612. "segment_reduce(): indices based reduction is not supported yet."
  613. )
  614. def segment_reduce_lengths_tensor(lengths_shape):
  615. return torch.empty(
  616. lengths_shape + data.shape[axis + 1 :],
  617. dtype=data.dtype,
  618. device="meta",
  619. memory_format=torch.contiguous_format,
  620. )
  621. if lengths is not None:
  622. return segment_reduce_lengths_tensor(lengths.shape)
  623. # FIXME should probably check that lengths and offset aren't both set, but
  624. # the ATen implementation neglects this too
  625. if offsets is not None:
  626. # lengths == torch.diff(offsets)
  627. lengths_shape = offsets.shape[:-1] + (offsets.shape[-1] - 1,)
  628. return segment_reduce_lengths_tensor(lengths_shape)
  629. raise RuntimeError("segment_reduce(): Either lengths or offsets must be defined.")
  630. @register_meta([aten.max.default, aten.max.unary_out])
  631. @out_wrapper()
  632. def meta_max(self):
  633. return self.new_empty(())
  634. @register_meta(aten.max.dim)
  635. def meta_max_dim(self, dim, keepdim=False):
  636. dim = utils.reduction_dims(self.shape, (dim,))
  637. output_shape = _compute_reduction_shape(self, dim, keepdim)
  638. return (
  639. self.new_empty(output_shape),
  640. self.new_empty(output_shape, dtype=torch.long),
  641. )
  642. @register_meta([aten.min.default, aten.min.unary_out])
  643. @out_wrapper()
  644. def meta_min(self):
  645. return self.new_empty(())
  646. @register_meta(aten.min.dim)
  647. def meta_min_dim(self, dim, keepdim=False):
  648. dim = utils.reduction_dims(self.shape, (dim,))
  649. output_shape = _compute_reduction_shape(self, dim, keepdim)
  650. return (
  651. self.new_empty(output_shape),
  652. self.new_empty(output_shape, dtype=torch.long),
  653. )
  654. @register_meta(aten.angle.default)
  655. def meta_angle(self):
  656. if self.is_complex():
  657. result_dtype = corresponding_real_dtype(self.dtype)
  658. else:
  659. _, result_dtype = elementwise_dtypes(
  660. self,
  661. type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
  662. )
  663. return torch.empty_like(self, dtype=result_dtype)
  664. @register_meta(aten.angle.out)
  665. def meta_angle_out(self, out):
  666. torch._resize_output_(out, self.size(), self.device)
  667. return out.copy_(torch.angle(self))
  668. @register_meta(aten._assert_async.default)
  669. def assert_async(val):
  670. return
  671. @register_meta(aten._assert_async.msg)
  672. def assert_async_meta(val, assert_msg):
  673. return
  674. @register_meta(aten._print.default)
  675. def print_meta(s):
  676. return
  677. @register_meta(aten._make_dep_token.default)
  678. def make_dep_token(
  679. *,
  680. dtype=None,
  681. layout=None,
  682. device=None,
  683. pin_memory=None,
  684. memory_format=None,
  685. ):
  686. return torch.empty(0, device="meta")
  687. @register_meta(aten.sym_constrain_range.default)
  688. def sym_constrain_range(size, min=None, max=None):
  689. # Avoid importing sympy at a module level
  690. from torch.fx.experimental.symbolic_shapes import constrain_range
  691. if isinstance(size, (SymFloat, SymBool)):
  692. raise ValueError("Constraining SymFloat or Symbool is nyi")
  693. constrain_range(size, min=min, max=max)
  694. @register_meta(aten._functional_sym_constrain_range.default)
  695. def functional_sym_constrain_range(size, min=None, max=None, dep_token=None):
  696. aten.sym_constrain_range(size, min=min, max=max)
  697. return dep_token
  698. @register_meta(aten.sym_constrain_range_for_size.default)
  699. def sym_constrain_range_for_size(size, min=None, max=None):
  700. # Avoid importing sympy at a module level
  701. from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size
  702. if min is None and max is None:
  703. torch._check_is_size(size)
  704. return
  705. if isinstance(size, (SymFloat, SymBool)):
  706. raise ValueError("Constraining SymFloat or Symbool is nyi")
  707. if type(size) is int:
  708. if min is not None:
  709. torch._check(size >= min)
  710. if max is not None:
  711. torch._check(size <= max)
  712. return
  713. _constrain_range_for_size(size, min=min, max=max)
  714. @register_meta(aten._functional_sym_constrain_range_for_size.default)
  715. def functional_sym_constrain_range_for_size(size, min, max, dep_token):
  716. aten.sym_constrain_range_for_size(size, min=min, max=max)
  717. return dep_token
  718. @register_meta(aten._functional_assert_async.msg)
  719. def functional_assert_async_meta(val, assert_msg, dep_token):
  720. return dep_token
  721. # From aten/src/ATen/native/LinearAlgebraUtils.h
  722. def squareCheckInputs(self: Tensor, f_name: str):
  723. assert self.dim() >= 2, (
  724. f"{f_name}: The input tensor must have at least 2 dimensions."
  725. )
  726. assert self.size(-1) == self.size(-2), (
  727. f"{f_name}: A must be batches of square matrices, but they are {self.size(-2)} by {self.size(-1)} matrices"
  728. )
  729. # Validates input shapes and devices
  730. # for linear solve methods (solve, cholesky_solve, lu_solve, triangular_solve)
  731. # From aten/src/ATen/native/LinearAlgebraUtils.h
  732. def linearSolveCheckInputs(self: Tensor, A: Tensor, name: str):
  733. torch._check(
  734. self.device == A.device,
  735. lambda: (
  736. f"Expected b and A to be on the same device, but found b on "
  737. f"{self.device} and A on {A.device} instead."
  738. ),
  739. )
  740. torch._check(
  741. self.dtype == A.dtype,
  742. lambda: (
  743. f"Expected b and A to have the same dtype, but found b of type "
  744. f"{self.dtype} and A of type {A.dtype} instead."
  745. ),
  746. )
  747. torch._check(
  748. A.size(-1) == A.size(-2),
  749. lambda: (
  750. f"A must be batches of square matrices, "
  751. f"but they are {A.size(-2)} by {A.size(-1)} matrices"
  752. ),
  753. )
  754. torch._check(
  755. A.size(-1) == self.size(-2),
  756. lambda: (
  757. f"Incompatible matrix sizes for {name}: each A "
  758. f"matrix is {A.size(-1)} by {A.size(-1)}"
  759. f" but each b matrix is {self.size(-2)} by {self.size(-1)}"
  760. ),
  761. )
  762. # From aten/src/ATen/native/LinearAlgebraUtils.h
  763. def checkFloatingOrComplex(
  764. t: Tensor,
  765. f_name: str,
  766. allow_low_precision_dtypes: bool = True,
  767. ):
  768. dtype = t.dtype
  769. torch._check(
  770. t.is_floating_point() or t.is_complex(),
  771. lambda: f"{f_name}: Expected a floating point or complex tensor as input. Got {dtype}",
  772. )
  773. if not allow_low_precision_dtypes:
  774. torch._check(
  775. dtype in (torch.float, torch.double, torch.cfloat, torch.cdouble),
  776. lambda: f"{f_name}: Low precision dtypes not supported. Got {dtype}",
  777. )
  778. # From aten/src/ATen/native/LinearAlgebraUtils.h
  779. def checkIsMatrix(A: Tensor, f_name: str, arg_name: str = "A"):
  780. torch._check(
  781. A.dim() >= 2,
  782. lambda: f"{f_name}: The input tensor {arg_name} must have at least 2 dimensions.",
  783. )
  784. def checkInputsSolver(A: Tensor, B: Tensor, left: bool, f_name: str):
  785. squareCheckInputs(A, f_name)
  786. checkIsMatrix(B, f_name)
  787. torch._check(
  788. A.size(-2) == B.size(-2) if left else A.size(-1) == B.size(-1),
  789. lambda: (
  790. f"{f_name}: Incompatible shapes of A and B for the equation "
  791. f"{'AX = B' if left else 'XA = B'}"
  792. f" ({A.size(-2)}x{A.size(-1)} and {B.size(-2)}x{B.size(-1)})"
  793. ),
  794. )
  795. def checkSameDevice(
  796. fn_name: str,
  797. result: Tensor,
  798. input: Tensor,
  799. result_name: str = "result",
  800. ):
  801. torch._check(
  802. result.device == input.device,
  803. lambda: (
  804. f"{fn_name}: Expected {result_name} and input tensors to be on the same device, but got "
  805. f"{result_name} on {result.device} and input on {input.device}"
  806. ),
  807. )
  808. def checkUplo(UPLO: str):
  809. UPLO_uppercase = UPLO.upper()
  810. torch._check(
  811. len(UPLO) == 1 and (UPLO_uppercase == "U" or UPLO_uppercase == "L"),
  812. lambda: f"Expected UPLO argument to be 'L' or 'U', but got {UPLO}",
  813. )
  814. @register_meta([aten._linalg_eigh.default, aten._linalg_eigh.eigenvalues])
  815. @out_wrapper("eigenvalues", "eigenvectors")
  816. def meta__linalg_eigh(A: Tensor, UPLO: str = "L", compute_v: bool = True):
  817. squareCheckInputs(A, "linalg.eigh")
  818. checkUplo(UPLO)
  819. shape = list(A.shape)
  820. if compute_v:
  821. vecs = A.new_empty(shape)
  822. vecs.as_strided_(shape, make_contiguous_strides_for(shape, row_major=False))
  823. else:
  824. vecs = A.new_empty([0])
  825. shape.pop()
  826. vals = A.new_empty(shape, dtype=toRealValueType(A.dtype))
  827. return vals, vecs
  828. @register_meta([aten._linalg_eigvals.default, aten.linalg_eigvals.out])
  829. @out_wrapper()
  830. def meta__linalg_eigvals(input: Tensor) -> Tensor:
  831. squareCheckInputs(input, "linalg.eigvals")
  832. complex_dtype = (
  833. input.dtype
  834. if utils.is_complex_dtype(input.dtype)
  835. else utils.corresponding_complex_dtype(input.dtype)
  836. )
  837. return input.new_empty(input.shape[:-1], dtype=complex_dtype)
  838. @register_meta([aten.linalg_eig])
  839. @out_wrapper("eigenvalues", "eigenvectors")
  840. def meta_linalg_eig(input: Tensor):
  841. squareCheckInputs(input, "linalg.eig")
  842. complex_dtype = (
  843. input.dtype
  844. if utils.is_complex_dtype(input.dtype)
  845. else utils.corresponding_complex_dtype(input.dtype)
  846. )
  847. values = input.new_empty(input.shape[:-1], dtype=complex_dtype)
  848. vectors = input.new_empty(input.shape, dtype=complex_dtype)
  849. return values, vectors
  850. def cloneBatchedColumnMajor(src: Tensor) -> Tensor:
  851. return src.mT.clone(memory_format=torch.contiguous_format).transpose(-2, -1)
  852. @register_meta(aten._cholesky_solve_helper)
  853. @out_wrapper()
  854. def _cholesky_solve_helper(self: Tensor, A: Tensor, upper: bool) -> Tensor:
  855. return cloneBatchedColumnMajor(self)
  856. @register_meta(aten.cholesky_solve)
  857. @out_wrapper()
  858. def cholesky_solve(self: Tensor, A: Tensor, upper: bool = False) -> Tensor:
  859. torch._check(
  860. self.ndim >= 2,
  861. lambda: f"b should have at least 2 dimensions, but has {self.ndim} dimensions instead",
  862. )
  863. torch._check(
  864. A.ndim >= 2,
  865. lambda: f"u should have at least 2 dimensions, but has {A.ndim} dimensions instead",
  866. )
  867. self_broadcasted, A_broadcasted = _linalg_broadcast_batch_dims_name(
  868. self, A, "cholesky_solve"
  869. )
  870. return _cholesky_solve_helper(self_broadcasted, A_broadcasted, upper)
  871. @register_meta(aten.cholesky)
  872. @out_wrapper()
  873. def cholesky(self: Tensor, upper: bool = False) -> Tensor:
  874. if self.numel() == 0:
  875. return torch.empty_like(self, memory_format=torch.legacy_contiguous_format)
  876. squareCheckInputs(self, "cholesky")
  877. return cloneBatchedColumnMajor(self)
  878. @register_meta(aten.cholesky_inverse)
  879. @out_wrapper()
  880. def cholesky_inverse(self: Tensor, upper: bool = False) -> Tensor:
  881. squareCheckInputs(self, "cholesky_inverse")
  882. return cloneBatchedColumnMajor(self)
  883. # From aten/src/ATen/native/BatchLinearAlgebra.cpp
  884. @register_meta(aten.linalg_cholesky_ex.default)
  885. def linalg_cholesky_ex(A: Tensor, upper: bool = False, check_errors: bool = False):
  886. squareCheckInputs(A, "linalg.cholesky")
  887. checkFloatingOrComplex(A, "linalg.cholesky")
  888. A_shape = A.shape
  889. ndim = len(A_shape)
  890. # L
  891. L_strides = make_contiguous_strides_for(A_shape, False)
  892. L = A.new_empty(A_shape)
  893. L.as_strided_(A_shape, L_strides)
  894. # infos
  895. infos = A.new_empty(A_shape[0 : ndim - 2], dtype=torch.int32)
  896. return L, infos
  897. @register_meta(
  898. [aten.linalg_householder_product.default, aten.linalg_householder_product.out]
  899. )
  900. @out_wrapper()
  901. def linalg_householder_product(input: Tensor, tau: Tensor) -> Tensor:
  902. torch._check(
  903. input.ndim >= 2,
  904. lambda: "torch.linalg.householder_product: input must have at least 2 dimensions.",
  905. )
  906. torch._check(
  907. input.size(-2) >= input.size(-1),
  908. lambda: "torch.linalg.householder_product: input.shape[-2] must be greater than or equal to input.shape[-1]",
  909. )
  910. torch._check(
  911. input.size(-1) >= tau.size(-1),
  912. lambda: "torch.linalg.householder_product: input.shape[-1] must be greater than or equal to tau.shape[-1]",
  913. )
  914. torch._check(
  915. input.ndim - tau.ndim == 1,
  916. lambda: (
  917. f"torch.linalg.householder_product: Expected tau to have one dimension less than input, "
  918. f"but got tau.ndim equal to {tau.ndim} and input.ndim is equal to {input.ndim}"
  919. ),
  920. )
  921. if input.ndim > 2:
  922. expected_batch_tau_shape = input.shape[:-2]
  923. actual_batch_tau_shape = tau.shape[:-1]
  924. torch._check(
  925. actual_batch_tau_shape == expected_batch_tau_shape,
  926. lambda: (
  927. f"torch.linalg.householder_product: Expected batch dimensions of tau to be "
  928. f"equal to input.shape[:-2], but got {actual_batch_tau_shape}"
  929. ),
  930. )
  931. torch._check(
  932. tau.dtype == input.dtype,
  933. lambda: (
  934. f"torch.linalg.householder_product: tau dtype {tau.dtype}"
  935. f" does not match input dtype {input.dtype}"
  936. ),
  937. )
  938. checkSameDevice("torch.linalg.householder_product", tau, input, "tau")
  939. return torch.empty_strided(
  940. size=input.shape,
  941. stride=make_contiguous_strides_for(input.shape, row_major=False),
  942. dtype=input.dtype,
  943. device=input.device,
  944. )
  945. # From aten/src/ATen/native/BatchLinearAlgebra.cpp
  946. @register_meta(aten.linalg_inv_ex.default)
  947. def linalg_inv_ex_meta(A: Tensor, check_errors: bool = False):
  948. squareCheckInputs(A, "linalg.inv_ex")
  949. checkFloatingOrComplex(A, "linalg.inv_ex", allow_low_precision_dtypes=False)
  950. L = A.new_empty(A.shape)
  951. L.as_strided_(A.shape, make_contiguous_strides_for(A.shape, row_major=False))
  952. infos = A.new_empty(A.shape[:-2], dtype=torch.int32)
  953. return L, infos
  954. @register_meta([aten.linalg_ldl_factor_ex.default, aten.linalg_ldl_factor_ex.out])
  955. @out_wrapper("LD", "pivots", "info")
  956. def linalg_ldl_factor_ex_meta(
  957. self: Tensor,
  958. *,
  959. hermitian: bool = False,
  960. check_errors: bool = False,
  961. ) -> tuple[Tensor, Tensor, Tensor]:
  962. squareCheckInputs(self, "torch.linalg.ldl_factor_ex")
  963. checkFloatingOrComplex(self, "torch.linalg.ldl_factor_ex")
  964. LD = torch.empty_strided(
  965. size=self.shape,
  966. stride=make_contiguous_strides_for(self.shape, row_major=False),
  967. dtype=self.dtype,
  968. device=self.device,
  969. )
  970. pivots = self.new_empty(self.shape[:-1], dtype=torch.int)
  971. info = self.new_empty(self.shape[:-2], dtype=torch.int)
  972. return LD, pivots, info
  973. @register_meta([aten.linalg_ldl_solve.default, aten.linalg_ldl_solve.out])
  974. @out_wrapper()
  975. def linalg_ldl_solve_meta(
  976. LD: Tensor,
  977. pivots: Tensor,
  978. B: Tensor,
  979. *,
  980. hermitian: bool = False,
  981. ) -> Tensor:
  982. squareCheckInputs(LD, "torch.linalg.ldl_solve")
  983. checkFloatingOrComplex(LD, "torch.linalg.ldl_solve")
  984. linearSolveCheckInputs(B, LD, "torch.linalg.ldl_solve")
  985. torch._check(
  986. B.ndim >= 2,
  987. lambda: (
  988. f"torch.linalg.ldl_solve: Expected B to have at least 2 dimensions, "
  989. f"but it has {B.ndim} dimensions instead"
  990. ),
  991. )
  992. expected_pivots_shape = LD.shape[:-1]
  993. torch._check(
  994. expected_pivots_shape == pivots.shape,
  995. lambda: (
  996. f"torch.linalg.ldl_solve: Expected LD.shape[:-1] and pivots.shape to be the same, "
  997. f"but got pivots with shape {pivots.shape} instead"
  998. ),
  999. )
  1000. torch._check(
  1001. utils.is_integer_dtype(pivots.dtype),
  1002. lambda: f"torch.linalg.ldl_solve: Expected pivots to be integers. Got {pivots.dtype}",
  1003. )
  1004. torch._check(
  1005. LD.dtype == B.dtype,
  1006. lambda: f"torch.linalg.ldl_solve: LD dtype {LD.dtype} does not match b dtype {B.dtype}",
  1007. )
  1008. B_broadcast_size, _ = _linalg_broadcast_batch_dims(B, LD)
  1009. return torch.empty_strided(
  1010. size=B_broadcast_size,
  1011. stride=make_contiguous_strides_for(B_broadcast_size, row_major=False),
  1012. dtype=B.dtype,
  1013. device=B.device,
  1014. )
  1015. @register_meta([aten.linalg_lu.default, aten.linalg_lu.out])
  1016. @out_wrapper("P", "L", "U")
  1017. def linalg_lu_meta(A: Tensor, *, pivot: bool = True) -> tuple[Tensor, Tensor, Tensor]:
  1018. torch._check(
  1019. A.ndim >= 2,
  1020. lambda: f"linalg.lu: Expected tensor with 2 or more dimensions. Got size: {A.shape} instead",
  1021. )
  1022. sizes = list(A.shape)
  1023. m = sizes[-2]
  1024. n = sizes[-1]
  1025. k = min(m, n)
  1026. sizes[-1] = m
  1027. if pivot:
  1028. P = A.new_empty(sizes)
  1029. else:
  1030. P = A.new_empty([0])
  1031. sizes[-1] = k
  1032. L = A.new_empty(sizes)
  1033. sizes[-2] = k
  1034. sizes[-1] = n
  1035. U = A.new_empty(sizes)
  1036. return P, L, U
  1037. @register_meta([aten.linalg_lu_factor_ex.default, aten.linalg_lu_factor_ex.out])
  1038. @out_wrapper("LU", "pivots", "info")
  1039. def linalg_lu_factor_ex_meta(
  1040. A: Tensor,
  1041. *,
  1042. pivot: bool = True,
  1043. check_errors: bool = False,
  1044. ) -> tuple[Tensor, Tensor, Tensor]:
  1045. torch._check(
  1046. A.ndim >= 2,
  1047. lambda: f"torch.lu_factor: Expected tensor with 2 or more dimensions. Got size: {A.shape} instead",
  1048. )
  1049. sizes = list(A.shape)
  1050. m = sizes[-2]
  1051. n = sizes[-1]
  1052. LU = torch.empty_strided(
  1053. size=sizes,
  1054. stride=make_contiguous_strides_for(sizes, row_major=False),
  1055. dtype=A.dtype,
  1056. device=A.device,
  1057. )
  1058. # Sets sizes to the size of pivots
  1059. sizes.pop()
  1060. sizes[-1] = min(m, n)
  1061. pivots = A.new_empty(sizes, dtype=torch.int)
  1062. # Sets sizes to the size of info
  1063. sizes.pop()
  1064. info = A.new_empty(sizes, dtype=torch.int)
  1065. return LU, pivots, info
  1066. @register_meta([aten.linalg_lu_solve.default, aten.linalg_lu_solve.out])
  1067. @out_wrapper()
  1068. def linalg_lu_solve_meta(
  1069. LU: Tensor,
  1070. pivots: Tensor,
  1071. B: Tensor,
  1072. *,
  1073. left: bool = True,
  1074. adjoint: bool = False,
  1075. ) -> Tensor:
  1076. # dtype
  1077. checkFloatingOrComplex(LU, "torch.linalg.lu_solve")
  1078. torch._check(
  1079. LU.dtype == B.dtype,
  1080. lambda: (
  1081. f"linalg.lu_solve: Expected LU and B to have the same dtype, "
  1082. f"but found LU of type {LU.dtype} and B of type {B.dtype} instead"
  1083. ),
  1084. )
  1085. torch._check(
  1086. pivots.dtype == torch.int,
  1087. lambda: "linalg.lu_solve: pivots should be a Tensor of scalar type torch.int32",
  1088. )
  1089. # matrix shapes
  1090. squareCheckInputs(LU, "torch.linalg.lu_solve")
  1091. checkInputsSolver(LU, B, left, "linalg.lu_solve")
  1092. torch._check(
  1093. LU.size(-1) == pivots.size(-1),
  1094. lambda: "linalg.lu_solve: Number of pivots per batch should be same as the dimension of the matrix",
  1095. )
  1096. # batches
  1097. torch._check(
  1098. LU.shape[:-1] == pivots.shape,
  1099. lambda: (
  1100. f"linalg.lu_solve: Expected LU.shape[:-1] and pivots.shape to be the same, "
  1101. f"but got pivots with shape {pivots.shape} instead"
  1102. ),
  1103. )
  1104. B_broadcast_size, _ = _linalg_broadcast_batch_dims(B, LU)
  1105. result = torch.empty_strided(
  1106. size=B_broadcast_size,
  1107. stride=make_contiguous_strides_for(B_broadcast_size, row_major=not left),
  1108. dtype=B.dtype,
  1109. device=B.device,
  1110. )
  1111. if result.numel() != 0 and not left:
  1112. if result.is_complex():
  1113. result = result.conj()
  1114. return result
  1115. @register_meta(aten.lu_unpack)
  1116. @out_wrapper("P", "L", "U")
  1117. def lu_unpack_meta(
  1118. LU: Tensor,
  1119. pivots: Tensor,
  1120. unpack_data: bool = True,
  1121. unpack_pivots: bool = True,
  1122. ) -> tuple[Tensor, Tensor, Tensor]:
  1123. torch._check(
  1124. LU.ndim >= 2,
  1125. lambda: f"torch.lu_unpack: Expected tensor with 2 or more dimensions. Got size: {LU.shape} instead",
  1126. )
  1127. if unpack_pivots:
  1128. torch._check(
  1129. pivots.dtype == torch.int32,
  1130. lambda: (
  1131. "torch.lu_unpack: LU_pivots is expected to be a contiguous tensor of torch.int32 dtype.\n"
  1132. "Note: this function is intended to be used with the output produced by torch.linalg.lu_factor"
  1133. ),
  1134. )
  1135. sizes = list(LU.shape)
  1136. m = sizes[-2]
  1137. n = sizes[-1]
  1138. k = min(m, n)
  1139. sizes[-1] = m
  1140. if unpack_pivots:
  1141. P = LU.new_empty(sizes)
  1142. else:
  1143. P = LU.new_empty([0])
  1144. if unpack_data:
  1145. sizes[-1] = k
  1146. L = LU.new_empty(sizes)
  1147. sizes[-2] = k
  1148. sizes[-1] = n
  1149. U = LU.new_empty(sizes)
  1150. else:
  1151. L = LU.new_empty([0])
  1152. U = LU.new_empty([0])
  1153. return P, L, U
  1154. # parse the "mode" param in linalg_qr: return a tuple of bools (compute_q, reduced)
  1155. def _parse_qr_mode(mode: str) -> tuple[bool, bool]:
  1156. if mode == "reduced":
  1157. compute_q = True
  1158. reduced = True
  1159. elif mode == "complete":
  1160. compute_q = True
  1161. reduced = False
  1162. elif mode == "r":
  1163. compute_q = False
  1164. reduced = True # this is actually irrelevant in this mode
  1165. else:
  1166. torch._check(
  1167. False,
  1168. lambda: (
  1169. f"qr received unrecognized mode '{mode}' "
  1170. f"but expected one of 'reduced' (default), 'r', or 'complete'"
  1171. ),
  1172. )
  1173. return compute_q, reduced # type: ignore[possibly-undefined]
  1174. @register_meta([aten.linalg_qr.default, aten.linalg_qr.out])
  1175. @out_wrapper("Q", "R")
  1176. def linalg_qr_meta(A: Tensor, mode: str = "reduced") -> tuple[Tensor, Tensor]:
  1177. checkIsMatrix(A, "linalg.qr")
  1178. checkFloatingOrComplex(A, "linalg.qr")
  1179. compute_q, reduced_mode = _parse_qr_mode(mode)
  1180. m = A.shape[-2]
  1181. n = A.shape[-1]
  1182. k = min(m, n)
  1183. if compute_q:
  1184. Q_shape = list(A.shape)
  1185. Q_shape[-1] = k if reduced_mode else m
  1186. Q = A.new_empty(Q_shape)
  1187. Q.as_strided_(Q_shape, make_contiguous_strides_for(Q_shape, row_major=False))
  1188. else:
  1189. Q = A.new_empty([0])
  1190. # For readability
  1191. R_shape = list(A.shape)
  1192. R_shape[-2] = k if reduced_mode or not compute_q else m
  1193. R = A.new_empty(R_shape)
  1194. R.as_strided_(R_shape, make_contiguous_strides_for(R_shape, row_major=False))
  1195. return Q, R
  1196. @register_meta([aten._linalg_slogdet.default, aten._linalg_slogdet.sign])
  1197. @out_wrapper("sign", "logabsdet", "LU", "pivots")
  1198. def _linalg_slogdet(A: Tensor) -> tuple[Tensor, Tensor, Tensor, Tensor]:
  1199. squareCheckInputs(A, "linalg.slogdet")
  1200. checkFloatingOrComplex(A, "linalg.slogdet", False)
  1201. shape = A.shape
  1202. sign = A.new_empty(shape[:-2])
  1203. logabsdet = A.new_empty(shape[:-2], dtype=toRealValueType(A.dtype))
  1204. LU = torch.empty_strided(
  1205. size=shape,
  1206. stride=make_contiguous_strides_for(shape, False),
  1207. dtype=A.dtype,
  1208. device=A.device,
  1209. )
  1210. pivots = A.new_empty(shape[:-1], dtype=torch.int32)
  1211. return sign, logabsdet, LU, pivots
  1212. # From aten/src/ATen/native/BatchLinearAlgebra.cpp
  1213. # NOTE: matching defaults in aten/src/ATen/native/native_functions.yaml
  1214. @register_meta(aten._linalg_svd.default)
  1215. def _linalg_svd_meta(
  1216. A: Tensor,
  1217. full_matrices: bool = False,
  1218. compute_uv: bool = True,
  1219. driver: Optional[str] = None,
  1220. ):
  1221. checkIsMatrix(A, "linalg.svd")
  1222. checkFloatingOrComplex(A, "linalg.svd")
  1223. batch_dims = list(A.shape[:-2])
  1224. m = A.shape[-2]
  1225. n = A.shape[-1]
  1226. k = min(m, n)
  1227. if compute_uv:
  1228. U_shape = batch_dims + [m, m if full_matrices else k]
  1229. U = A.new_empty(U_shape)
  1230. U.as_strided_(U_shape, make_contiguous_strides_for(U_shape, row_major=False))
  1231. V_shape = batch_dims + [n if full_matrices else k, n]
  1232. V = A.new_empty(V_shape)
  1233. # NB: This checks for CUDA since there is no way to check for cuSolver.
  1234. # Also, this might not work correctly on CPU when fake_device is not
  1235. # available as device_hint just defaults to CUDA in that case. See
  1236. # _linalg_svd meta in core.
  1237. is_cuda = device_hint(A) == "cuda"
  1238. V.as_strided_(V_shape, make_contiguous_strides_for(V_shape, row_major=is_cuda))
  1239. else:
  1240. # doesn't matter
  1241. U = A.new_empty([0])
  1242. V = A.new_empty([0])
  1243. # S is always real, even when A is complex.
  1244. S = A.new_empty(batch_dims + [k], dtype=toRealValueType(A.dtype))
  1245. return U, S, V
  1246. def _linalg_broadcast_batch_dims(
  1247. arg1: Tensor,
  1248. arg2: Tensor,
  1249. ) -> tuple[list[int], list[int]]:
  1250. # broadcast the batch dimensions of arg1 and arg2.
  1251. arg1_batch_sizes = arg1.shape[:-2]
  1252. arg2_batch_sizes = arg2.shape[:-2]
  1253. expand_batch_portion = _broadcast_shapes(arg1_batch_sizes, arg2_batch_sizes)
  1254. arg1_expand_size = list(expand_batch_portion)
  1255. arg1_expand_size += [arg1.size(-2), arg1.size(-1)]
  1256. arg2_expand_size = list(expand_batch_portion)
  1257. arg2_expand_size += [arg2.size(-2), arg2.size(-1)]
  1258. return arg1_expand_size, arg2_expand_size
  1259. def _linalg_broadcast_batch_dims_name(
  1260. arg1: Tensor,
  1261. arg2: Tensor,
  1262. name: Optional[str],
  1263. ) -> tuple[Tensor, Tensor]:
  1264. # If there's no name we assume we don't want to check the errors
  1265. if name:
  1266. linearSolveCheckInputs(arg1, arg2, name)
  1267. arg1_expand_size, arg2_expand_size = _linalg_broadcast_batch_dims(arg1, arg2)
  1268. arg1_broadcasted = (
  1269. arg1 if arg1_expand_size == arg1.shape else arg1.expand(arg1_expand_size)
  1270. )
  1271. arg2_broadcasted = (
  1272. arg2 if arg2_expand_size == arg2.shape else arg2.expand(arg2_expand_size)
  1273. )
  1274. return arg1_broadcasted, arg2_broadcasted
  1275. def linalg_solve_is_vector_rhs(input: Tensor, other: Tensor) -> bool:
  1276. expected_batched_rhs_shape = input.shape[:-1]
  1277. vector_case = other.ndim == 1 or (
  1278. input.ndim - 1 == other.ndim and other.shape == expected_batched_rhs_shape
  1279. )
  1280. return vector_case
  1281. @register_meta(aten._linalg_solve_ex)
  1282. def _linalg_solve_ex(
  1283. A: Tensor,
  1284. B: Tensor,
  1285. *,
  1286. left: bool = True,
  1287. check_errors: bool = False,
  1288. result: Optional[Tensor] = None,
  1289. LU: Optional[Tensor] = None,
  1290. pivots: Optional[Tensor] = None,
  1291. info: Optional[Tensor] = None,
  1292. ) -> tuple[Tensor, Tensor, Tensor, Tensor]:
  1293. checkFloatingOrComplex(A, "linalg.solve")
  1294. torch._check(
  1295. A.dtype == B.dtype,
  1296. lambda: (
  1297. f"linalg.solve: Expected A and B to have the same dtype, but found A of type "
  1298. f"{A.dtype} and B of type {B.dtype} instead"
  1299. ),
  1300. )
  1301. vector_case = linalg_solve_is_vector_rhs(A, B)
  1302. B_ = B.unsqueeze(-1) if vector_case else B
  1303. checkInputsSolver(A, B_, left, "linalg.solve")
  1304. B_broad_shape, _ = _linalg_broadcast_batch_dims(B_, A)
  1305. torch._check(
  1306. left or not vector_case,
  1307. lambda: (
  1308. "linalg.solve: Vector broadcasting of the left hand side is not supported for left=False. "
  1309. "In this case linalg.solve is equivalent to B / A.squeeze(-1)"
  1310. ),
  1311. )
  1312. result_shape = B_broad_shape[:-1] if vector_case else B_broad_shape
  1313. result_ = torch.empty_strided(
  1314. size=result_shape,
  1315. stride=make_contiguous_strides_for(result_shape, not left),
  1316. dtype=B.dtype,
  1317. device=B.device,
  1318. )
  1319. shape = A.shape
  1320. LU_ = torch.empty_strided(
  1321. size=shape,
  1322. stride=make_contiguous_strides_for(shape, False),
  1323. dtype=A.dtype,
  1324. device=A.device,
  1325. )
  1326. pivots_ = A.new_empty(shape[:-1], dtype=torch.int32)
  1327. info_ = A.new_empty(shape[:-2], dtype=torch.int32)
  1328. out = (result, LU, pivots, info)
  1329. res = (result_, LU_, pivots_, info_)
  1330. if all(x is not None for x in out):
  1331. for r, o in zip(res, out):
  1332. # resize and copy operations are done in-place
  1333. _maybe_resize_out(o, r.shape) # type: ignore[arg-type]
  1334. # strides are not copied in out_wrapper
  1335. o.as_strided_(r.shape, r.stride()) # type: ignore[union-attr]
  1336. _safe_copy_out(copy_from=r, copy_to=o, exact_dtype=False) # type: ignore[arg-type]
  1337. return res
  1338. @register_meta([aten.linalg_solve_triangular.default, aten.linalg_solve_triangular.out])
  1339. def linalg_solve_triangular_meta(
  1340. A: Tensor,
  1341. B: Tensor,
  1342. *,
  1343. upper: bool,
  1344. left: bool = True,
  1345. unitriangular: bool = False,
  1346. out: Optional[Tensor] = None,
  1347. ) -> Tensor:
  1348. if out is None:
  1349. out = A.new_empty([0])
  1350. assert isinstance(out, TensorLike)
  1351. checkInputsSolver(A, B, left, "linalg.solve_triangular")
  1352. B_, A_ = _linalg_broadcast_batch_dims_name(B, A, None)
  1353. avoid_copy_A = A_.transpose(-2, -1).is_contiguous() and A_.is_conj()
  1354. if avoid_copy_A:
  1355. out = _maybe_resize_out(out, B_.shape)
  1356. else:
  1357. # reimplementation of resize_output with result F-contig
  1358. if _resize_output_check(out, B_.shape):
  1359. out.resize_(B_.transpose(-2, -1).shape)
  1360. out.transpose_(-2, -1)
  1361. return out # type: ignore[return-value]
  1362. @register_meta(aten.triangular_solve)
  1363. @out_wrapper("X", "M", exact_dtype=True)
  1364. def triangular_solve_meta(
  1365. self: Tensor,
  1366. A: Tensor,
  1367. upper: bool = True,
  1368. transpose: bool = False,
  1369. unitriangular: bool = False,
  1370. ) -> tuple[Tensor, Tensor]:
  1371. torch._check(
  1372. self.ndim >= 2,
  1373. lambda: (
  1374. f"torch.triangular_solve: Expected b to have at least 2 dimensions, "
  1375. f"but it has {self.ndim} dimensions instead"
  1376. ),
  1377. )
  1378. torch._check(
  1379. A.ndim >= 2,
  1380. lambda: (
  1381. f"torch.triangular_solve: Expected A to have at least 2 dimensions, "
  1382. f"but it has {A.ndim} dimensions instead"
  1383. ),
  1384. )
  1385. linearSolveCheckInputs(self, A, "triangular_solve")
  1386. if A.layout == torch.strided:
  1387. self_broadcast_size, A_broadcast_size = _linalg_broadcast_batch_dims(self, A)
  1388. solution = torch.empty_strided(
  1389. size=self_broadcast_size,
  1390. stride=make_contiguous_strides_for(self_broadcast_size, row_major=False),
  1391. dtype=self.dtype,
  1392. device=self.device,
  1393. )
  1394. cloned_coefficient = torch.empty_strided(
  1395. size=A_broadcast_size,
  1396. stride=make_contiguous_strides_for(A_broadcast_size, row_major=False),
  1397. dtype=A.dtype,
  1398. device=A.device,
  1399. )
  1400. elif A.layout == torch.sparse_csr or A.layout == torch.sparse_bsr:
  1401. solution = torch.empty_like(self)
  1402. cloned_coefficient = self.new_empty([0])
  1403. else:
  1404. torch._check(False, lambda: "triangular_solve: Got an unexpected layout.")
  1405. return solution, cloned_coefficient # type: ignore[possibly-undefined]
  1406. # From aten/src/ATen/native/LinearAlgebra.cpp
  1407. @register_meta(aten._linalg_det.default)
  1408. def _linalg_det_meta(A):
  1409. squareCheckInputs(A, "linalg.det")
  1410. checkFloatingOrComplex(A, "linalg.det")
  1411. det = A.new_empty(A.shape[:-2])
  1412. LU = A.new_empty(A.shape)
  1413. LU.as_strided_(A.shape, make_contiguous_strides_for(A.shape, row_major=False))
  1414. pivots = A.new_empty(A.shape[:-1], dtype=torch.int32)
  1415. return det, LU, pivots
  1416. @register_meta(aten.ormqr)
  1417. @out_wrapper()
  1418. def ormqr(
  1419. input: Tensor,
  1420. tau: Tensor,
  1421. other: Tensor,
  1422. left: bool = True,
  1423. transpose: bool = False,
  1424. ) -> Tensor:
  1425. torch._check(
  1426. input.ndim >= 2, lambda: "torch.ormqr: input must have at least 2 dimensions."
  1427. )
  1428. torch._check(
  1429. other.ndim >= 2, lambda: "torch.ormqr: other must have at least 2 dimensions."
  1430. )
  1431. left_size_condition = -2 if left else -1
  1432. torch._check(
  1433. other.shape[left_size_condition] >= tau.shape[-1],
  1434. lambda: f"torch.ormqr: other.shape[{left_size_condition}] must be greater than or equal to tau.shape[-1]",
  1435. )
  1436. torch._check(
  1437. other.shape[left_size_condition] == input.shape[-2],
  1438. lambda: f"torch.ormqr: other.shape[{left_size_condition}] must be equal to input.shape[-2]",
  1439. )
  1440. torch._check(
  1441. tau.shape[-1] <= input.shape[-1],
  1442. lambda: "torch.ormqr: tau.shape[-1] must be less than or equal to input.shape[-1]",
  1443. )
  1444. torch._check(
  1445. input.ndim - tau.ndim == 1,
  1446. lambda: (
  1447. f"torch.ormqr: Expected tau to have one dimension less than input, "
  1448. f"but got tau.ndim equal to {tau.ndim} and input.ndim is equal to {input.ndim}"
  1449. ),
  1450. )
  1451. torch._check(
  1452. input.ndim == other.ndim,
  1453. lambda: (
  1454. f"torch.ormqr: Expected other to have the same number of dimensions as input, "
  1455. f"but got other.ndim equal to {other.ndim} and input.ndim is equal to {input.ndim}"
  1456. ),
  1457. )
  1458. if input.ndim > 2:
  1459. expected_batch_shape = input.shape[:-2]
  1460. actual_batch_tau_shape = tau.shape[:-1]
  1461. torch._check(
  1462. actual_batch_tau_shape == expected_batch_shape,
  1463. lambda: (
  1464. f"torch.ormqr: Expected batch dimensions of tau to be "
  1465. f"equal to input.shape[:-2], but got {actual_batch_tau_shape}"
  1466. ),
  1467. )
  1468. actual_batch_other_shape = other.shape[:-2]
  1469. torch._check(
  1470. actual_batch_other_shape == expected_batch_shape,
  1471. lambda: (
  1472. f"torch.ormqr: Expected batch dimensions of other to be "
  1473. f"equal to input.shape[:-2], but got {actual_batch_other_shape}"
  1474. ),
  1475. )
  1476. torch._check(
  1477. tau.dtype == input.dtype,
  1478. lambda: (
  1479. f"torch.ormqr: Expected input and tau to have the same dtype, "
  1480. f"but input has dtype {input.dtype} and tau has dtype {tau.dtype}"
  1481. ),
  1482. )
  1483. torch._check(
  1484. other.dtype == input.dtype,
  1485. lambda: (
  1486. f"torch.ormqr: Expected input and other to have the same dtype, "
  1487. f"but input has dtype {input.dtype} and other has dtype {other.dtype}"
  1488. ),
  1489. )
  1490. checkSameDevice("torch.ormqr", tau, input, "tau")
  1491. checkSameDevice("torch.ormqr", other, input, "other")
  1492. return torch.empty_strided(
  1493. size=other.shape,
  1494. stride=make_contiguous_strides_for(other.shape, row_major=False),
  1495. dtype=other.dtype,
  1496. device=other.device,
  1497. )
  1498. def _padding_check_valid_input(input, padding, *, dim):
  1499. torch._check(
  1500. len(padding) == 2 * dim,
  1501. lambda: f"padding size is expected to be {2 * dim}, but got: {len(padding)}",
  1502. )
  1503. input_dim = input.ndim
  1504. is_batch_mode = input_dim == (dim + 2)
  1505. valid_batch_mode = is_batch_mode
  1506. valid_non_batch_mode = not is_batch_mode
  1507. if is_batch_mode:
  1508. # allow batch size of 0-dim.
  1509. for d in range(1, input_dim):
  1510. valid_batch_mode = valid_batch_mode and input.size(d) != 0
  1511. else:
  1512. for d in range(0, input_dim):
  1513. valid_non_batch_mode = valid_non_batch_mode and input.size(d) != 0
  1514. # allow empty batch size but not other dimensions.
  1515. torch._check(
  1516. valid_batch_mode or valid_non_batch_mode,
  1517. lambda: (
  1518. f"Expected {dim + 1}D or {dim + 2}D (batch mode) tensor with possibly 0 batch size "
  1519. f"and other non-zero dimensions for input, but got: {input.shape}"
  1520. ),
  1521. )
  1522. def _pad1d_common(input, padding, *, is_reflection):
  1523. dim_plane = 0
  1524. dim_w = 1
  1525. nbatch = 1
  1526. if input.ndim == 3:
  1527. nbatch = input.size(0)
  1528. dim_w += 1
  1529. dim_plane += 1
  1530. _padding_check_valid_input(input, padding, dim=1)
  1531. pad_l, pad_r = padding
  1532. nplane = input.size(dim_plane)
  1533. input_w = input.size(dim_w)
  1534. output_w = input_w + pad_l + pad_r
  1535. if is_reflection:
  1536. torch._check(
  1537. pad_l < input_w and pad_r < input_w,
  1538. lambda: (
  1539. f"Argument #4: Padding size should be less than the corresponding input dimension, "
  1540. f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}"
  1541. ),
  1542. )
  1543. torch._check(
  1544. output_w >= 1,
  1545. lambda: f"input (W: {input_w}) is too small. Calculated output W: {output_w}",
  1546. )
  1547. if input.ndim == 2:
  1548. return input.new_empty((nplane, output_w))
  1549. else:
  1550. return input.new_empty((nbatch, nplane, output_w))
  1551. @register_meta(aten.reflection_pad1d)
  1552. @out_wrapper()
  1553. def meta_reflection_pad1d(input, padding):
  1554. return _pad1d_common(input, padding, is_reflection=True)
  1555. @register_meta(aten.replication_pad1d)
  1556. @out_wrapper()
  1557. def meta_replication_pad1d(input, padding):
  1558. torch._check(
  1559. input.dtype != torch.bool,
  1560. lambda: f""""replication_pad1d" not implemented for '{input.dtype.__str__()}'""",
  1561. )
  1562. return _pad1d_common(input, padding, is_reflection=False)
  1563. def _pad1d_backward_common(grad_output, input, padding, *, is_reflection):
  1564. dim_w = 1
  1565. if not is_reflection:
  1566. torch._check(len(padding) == 2, lambda: "padding size is expected to be 2")
  1567. if input.ndim == 3:
  1568. dim_w += 1
  1569. pad_l, pad_r = padding
  1570. input_w = input.size(dim_w)
  1571. output_w = input_w + pad_l + pad_r
  1572. if is_reflection:
  1573. torch._check(
  1574. pad_l < input_w and pad_r < input_w,
  1575. lambda: (
  1576. f"Argument #4: Padding size should be less than the corresponding input dimension, "
  1577. f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}"
  1578. ),
  1579. )
  1580. torch._check(
  1581. output_w == grad_output.size(dim_w),
  1582. lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}",
  1583. )
  1584. return input.new_empty(input.shape)
  1585. @register_meta(aten.reflection_pad1d_backward)
  1586. @out_wrapper("grad_input")
  1587. def meta_reflection_pad1d_backward(grad_output, input, padding):
  1588. return _pad1d_backward_common(grad_output, input, padding, is_reflection=True)
  1589. @register_meta(aten.replication_pad1d_backward)
  1590. @out_wrapper("grad_input")
  1591. def meta_replication_pad1d_backward(grad_output, input, padding):
  1592. return _pad1d_backward_common(grad_output, input, padding, is_reflection=False)
  1593. def _pad2d_common(input, padding, *, is_reflection):
  1594. dim_w = 2
  1595. dim_h = 1
  1596. dim_slices = 0
  1597. nbatch = 1
  1598. _padding_check_valid_input(input, padding, dim=2)
  1599. ndim = input.ndim
  1600. if ndim == 4:
  1601. nbatch = input.size(0)
  1602. dim_w += 1
  1603. dim_h += 1
  1604. dim_slices += 1
  1605. pad_l, pad_r, pad_t, pad_b = padding
  1606. nplane = input.size(dim_slices)
  1607. input_h = input.size(dim_h)
  1608. input_w = input.size(dim_w)
  1609. output_h = input_h + pad_t + pad_b
  1610. output_w = input_w + pad_l + pad_r
  1611. if is_reflection:
  1612. torch._check(
  1613. pad_l < input_w and pad_r < input_w,
  1614. lambda: (
  1615. f"Argument #4: Padding size should be less than the corresponding input dimension, "
  1616. f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}"
  1617. ),
  1618. )
  1619. torch._check(
  1620. pad_t < input_h and pad_b < input_h,
  1621. lambda: (
  1622. f"Argument #6: Padding size should be less than the corresponding input dimension, "
  1623. f"but got: padding ({pad_t}, {pad_b}) at dimension {dim_h} of input {input.shape}"
  1624. ),
  1625. )
  1626. torch._check(
  1627. output_w >= 1 or output_h >= 1,
  1628. lambda: (
  1629. f"input (H: {input_h} W: {input_w}) is too small. "
  1630. f"Calculated output H: {output_h} W: {output_w}"
  1631. ),
  1632. )
  1633. if input.ndim == 3:
  1634. return input.new_empty((nplane, output_h, output_w))
  1635. else:
  1636. return input.new_empty((nbatch, nplane, output_h, output_w))
  1637. @register_meta(aten.reflection_pad2d)
  1638. @out_wrapper()
  1639. def meta_reflection_pad2d(input, padding):
  1640. return _pad2d_common(input, padding, is_reflection=True)
  1641. @register_meta(aten.replication_pad2d)
  1642. @out_wrapper()
  1643. def meta_replication_pad2d(input, padding):
  1644. torch._check(
  1645. input.dtype != torch.bool,
  1646. lambda: f""""replication_pad2d" not implemented for '{input.dtype.__str__()}'""",
  1647. )
  1648. return _pad2d_common(input, padding, is_reflection=False)
  1649. @register_meta(
  1650. [
  1651. aten.reflection_pad2d_backward.default,
  1652. aten.reflection_pad2d_backward.grad_input,
  1653. aten.replication_pad2d_backward.default,
  1654. aten.replication_pad2d_backward.grad_input,
  1655. ]
  1656. )
  1657. @out_wrapper("grad_input")
  1658. def meta_pad2d_backward(grad_output, self, padding):
  1659. dim_w = 2
  1660. dim_h = 1
  1661. dim_plane = 0
  1662. self_shape = self.shape
  1663. if self.dim() == 4:
  1664. dim_w += 1
  1665. dim_h += 1
  1666. dim_plane += 1
  1667. pad_l, pad_r, pad_t, pad_b = padding
  1668. input_h = self_shape[dim_h]
  1669. input_w = self_shape[dim_w]
  1670. output_h = input_h + pad_t + pad_b
  1671. output_w = input_w + pad_l + pad_r
  1672. torch._check(
  1673. output_w == grad_output.size(dim_w),
  1674. lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}",
  1675. )
  1676. torch._check(
  1677. output_h == grad_output.size(dim_h),
  1678. lambda: f"grad_output height unexpected. Expected: {output_h}, Got: {grad_output.size(dim_h)}",
  1679. )
  1680. return self.new_empty(self.shape)
  1681. def _pad3d_common(input, padding, *, is_reflection):
  1682. dim_w = 3
  1683. dim_h = 2
  1684. dim_d = 1
  1685. dim_plane = 0
  1686. _padding_check_valid_input(input, padding, dim=3)
  1687. batch_mode = input.ndim == 5
  1688. if batch_mode:
  1689. nbatch = input.size(0)
  1690. dim_w += 1
  1691. dim_h += 1
  1692. dim_d += 1
  1693. dim_plane += 1
  1694. pad_l, pad_r, pad_t, pad_b, pad_f, pad_bk = padding
  1695. nplane = input.size(dim_plane)
  1696. input_d = input.size(dim_d)
  1697. input_h = input.size(dim_h)
  1698. input_w = input.size(dim_w)
  1699. output_d = input_d + pad_f + pad_bk
  1700. output_h = input_h + pad_t + pad_b
  1701. output_w = input_w + pad_l + pad_r
  1702. if is_reflection:
  1703. torch._check(
  1704. pad_l < input_w and pad_r < input_w,
  1705. lambda: (
  1706. f"Argument #4: Padding size should be less than the corresponding input dimension, "
  1707. f"but got: padding ({pad_l}, {pad_r}) at dimension {dim_w} of input {input.shape}"
  1708. ),
  1709. )
  1710. torch._check(
  1711. pad_t < input_h and pad_b < input_h,
  1712. lambda: (
  1713. f"Argument #6: Padding size should be less than the corresponding input dimension, "
  1714. f"but got: padding ({pad_t}, {pad_b}) at dimension {dim_h} of input {input.shape}"
  1715. ),
  1716. )
  1717. torch._check(
  1718. pad_f < input_d and pad_bk < input_d,
  1719. lambda: (
  1720. f"Argument #8: Padding size should be less than the corresponding input dimension, "
  1721. f"but got: padding ({pad_f}, {pad_bk}) at dimension {dim_d} of input {input.shape}"
  1722. ),
  1723. )
  1724. torch._check(
  1725. output_w >= 1 or output_h >= 1 or output_d >= 1,
  1726. lambda: (
  1727. f"input (D: {input_d} H: {input_h} W: {input_w}) is too small. "
  1728. f"Calculated output D: {output_d} H: {output_h} W: {output_w}"
  1729. ),
  1730. )
  1731. if batch_mode:
  1732. return input.new_empty((nbatch, nplane, output_d, output_h, output_w)) # type: ignore[possibly-undefined]
  1733. else:
  1734. return input.new_empty((nplane, output_d, output_h, output_w))
  1735. @register_meta(aten.reflection_pad3d)
  1736. @out_wrapper()
  1737. def meta_reflection_pad3d(input, padding):
  1738. return _pad3d_common(input, padding, is_reflection=True)
  1739. @register_meta(aten.replication_pad3d)
  1740. @out_wrapper()
  1741. def meta_replication_pad3d(input, padding):
  1742. torch._check(
  1743. input.dtype != torch.bool,
  1744. lambda: f""""replication_pad3d" not implemented for '{input.dtype.__str__()}'""",
  1745. )
  1746. return _pad3d_common(input, padding, is_reflection=False)
  1747. @register_meta(
  1748. [
  1749. aten.reflection_pad3d_backward.default,
  1750. aten.reflection_pad3d_backward.grad_input,
  1751. aten.replication_pad3d_backward.default,
  1752. aten.replication_pad3d_backward.grad_input,
  1753. ]
  1754. )
  1755. @out_wrapper("grad_input")
  1756. def meta_pad3d_backward(grad_output, input, padding):
  1757. torch._check(len(padding) == 6, lambda: "padding size is expected to be 6")
  1758. assert input.ndim > 3
  1759. assert grad_output.ndim == input.ndim
  1760. dim_w = 3
  1761. dim_h = 2
  1762. dim_d = 1
  1763. if input.ndim == 5:
  1764. dim_w += 1
  1765. dim_h += 1
  1766. dim_d += 1
  1767. pad_l, pad_r, pad_t, pad_b, pad_f, pad_bk = padding
  1768. input_d = input.size(dim_d)
  1769. input_h = input.size(dim_h)
  1770. input_w = input.size(dim_w)
  1771. output_d = input_d + pad_f + pad_bk
  1772. output_h = input_h + pad_t + pad_b
  1773. output_w = input_w + pad_l + pad_r
  1774. torch._check(
  1775. output_w == grad_output.size(dim_w),
  1776. lambda: f"grad_output width unexpected. Expected: {output_w}, Got: {grad_output.size(dim_w)}",
  1777. )
  1778. torch._check(
  1779. output_h == grad_output.size(dim_h),
  1780. lambda: f"grad_output height unexpected. Expected: {output_h}, Got: {grad_output.size(dim_h)}",
  1781. )
  1782. torch._check(
  1783. output_d == grad_output.size(dim_d),
  1784. lambda: f"grad_output depth unexpected. Expected: {output_d}, Got: {grad_output.size(dim_d)}",
  1785. )
  1786. return input.new_empty(input.shape)
  1787. @register_meta(aten._pdist_forward)
  1788. @out_wrapper()
  1789. def meta__pdist_forward(self: Tensor, p: float = 2) -> Tensor:
  1790. torch._check(
  1791. self.is_contiguous(), lambda: "_pdist_forward requires contiguous input"
  1792. )
  1793. n = self.size(0)
  1794. if n <= 1:
  1795. return self.new_empty([0]).to(memory_format=torch.legacy_contiguous_format) # type: ignore[call-overload]
  1796. else:
  1797. return self.new_empty((n * (n - 1) // 2,)).to(
  1798. memory_format=torch.legacy_contiguous_format
  1799. ) # type: ignore[call-overload]
  1800. @register_meta(aten._pdist_backward)
  1801. @out_wrapper()
  1802. def meta__pdist_backward(grad: Tensor, self: Tensor, p: float, pdist: Tensor) -> Tensor:
  1803. torch._check(
  1804. self.is_contiguous(), lambda: "_pdist_backward requires self to be contiguous"
  1805. )
  1806. torch._check(
  1807. pdist.is_contiguous(), lambda: "_pdist_backward requires pdist to be contiguous"
  1808. )
  1809. return torch.empty_like(self, memory_format=torch.legacy_contiguous_format)
  1810. @register_meta([aten.baddbmm.default, aten.baddbmm.out])
  1811. @out_wrapper(exact_dtype=True)
  1812. def meta_baddbmm(self, batch1, batch2, *, beta=1, alpha=1):
  1813. from torch.fx.experimental.symbolic_shapes import guard_or_true, sym_eq
  1814. dim1 = batch1.size(0)
  1815. dim2 = batch1.size(1)
  1816. dim3 = batch2.size(2)
  1817. if guard_or_true(torch.sym_not(sym_eq(self.shape, (dim1, dim2, dim3)))):
  1818. self = self.expand((dim1, dim2, dim3))
  1819. torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor")
  1820. torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor")
  1821. if not exp_config.skip_dtype_check_in_meta_registrations:
  1822. torch._check(
  1823. self.dtype == batch1.dtype == batch2.dtype,
  1824. lambda: f"Input dtypes must be the same, got: input: {self.dtype}, batch1: {batch1.dtype}, batch2: {batch2.dtype}",
  1825. )
  1826. batch1_sizes = batch1.shape
  1827. batch2_sizes = batch2.shape
  1828. bs = batch1_sizes[0]
  1829. contraction_size = batch1_sizes[2]
  1830. torch._check(
  1831. batch2_sizes[0] == bs and batch2_sizes[1] == contraction_size,
  1832. lambda: (
  1833. f"Expected size for first two dimensions of batch2 tensor to be: "
  1834. f"[{bs}, {contraction_size}] but got: [{batch2_sizes[0]}, {batch2_sizes[1]}]."
  1835. ),
  1836. )
  1837. return self.new_empty(self.size())
  1838. @register_meta([aten.bernoulli.default, aten.bernoulli.out])
  1839. @out_wrapper()
  1840. def meta_bernoulli(self, *, generator=None):
  1841. # https://github.com/pytorch/pytorch/issues/88612
  1842. return torch.empty_like(self, memory_format=torch.contiguous_format)
  1843. @register_meta(aten.bernoulli_.float)
  1844. def meta_bernoulli_(self, p=0.5, generator=None):
  1845. return self
  1846. @register_meta(aten.bernoulli.p)
  1847. def meta_bernoulli_p(self, p=0.5, generator=None):
  1848. # https://github.com/pytorch/pytorch/issues/88612
  1849. return torch.empty_like(self, memory_format=torch.contiguous_format)
  1850. @register_meta([aten.poisson.default, aten.poisson.out])
  1851. @out_wrapper()
  1852. def meta_poisson(self, generator=None):
  1853. return torch.empty_like(self)
  1854. @register_meta(aten._fused_moving_avg_obs_fq_helper.default)
  1855. def meta__fused_moving_avg_obs_fq_helper(
  1856. self,
  1857. observer_on,
  1858. fake_quant_on,
  1859. running_min,
  1860. running_max,
  1861. scale,
  1862. zero_point,
  1863. averaging_const,
  1864. quant_min,
  1865. quant_max,
  1866. ch_axis,
  1867. per_row_fake_quant=False,
  1868. symmetric_quant=False,
  1869. ):
  1870. torch._check(
  1871. ch_axis < self.dim(),
  1872. lambda: "Error in fused_moving_avg_obs_fake_quant_cpu: ch_axis must be < self.dim()",
  1873. )
  1874. mask = torch.empty_like(self, dtype=torch.bool)
  1875. return (torch.empty_like(self), mask)
  1876. @register_meta(aten.mm)
  1877. @out_wrapper(exact_dtype=True)
  1878. def meta_mm(a, b):
  1879. torch._check(a.dim() == 2, lambda: "a must be 2D")
  1880. torch._check(b.dim() == 2, lambda: "b must be 2D")
  1881. N, M1 = a.shape
  1882. M2, P = b.shape
  1883. torch._check(
  1884. M1 == M2,
  1885. lambda: f"a and b must have same reduction dim, but got [{N}, {M1}] X [{M2}, {P}].",
  1886. )
  1887. return a.new_empty(N, P)
  1888. def _compute_reduction_shape(self, dims, keepdim):
  1889. if keepdim:
  1890. return tuple(self.shape[i] if i not in dims else 1 for i in range(self.ndim))
  1891. return utils.compute_reduction_output_shape(self.shape, dims)
  1892. # FakeTensors (meta tensors with a device) will report device as meta
  1893. # when running meta kernels. Here, access the "fake device" of FakeTensor if it
  1894. # exists so meta kernels which have diverge per device will be more
  1895. # accurate when run with FakeTensors
  1896. def device_hint(tensor) -> "str":
  1897. if isinstance(tensor, torch._subclasses.FakeTensor):
  1898. return tensor.fake_device.type
  1899. elif (
  1900. hasattr(tensor, "device")
  1901. and hasattr(tensor.device, "type")
  1902. and tensor.device.type != "meta"
  1903. ):
  1904. return tensor.device.type
  1905. else:
  1906. return "cuda" # default to cuda
  1907. def calc_conv_nd_return_shape(
  1908. input_tensor: torch.Tensor,
  1909. weight: torch.Tensor,
  1910. stride: Union[list[int], int],
  1911. padding: Union[list[int], int],
  1912. dilation: Union[list[int], int],
  1913. is_transposed: bool,
  1914. groups: int,
  1915. output_padding: Optional[Union[list[int], int]] = None,
  1916. ):
  1917. def _formula(ln: int, p: int, d: int, k: int, s: int) -> int:
  1918. """
  1919. Formula to apply to calculate the length of some dimension of the output
  1920. See: https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html
  1921. Args:
  1922. ln: length of the dimension
  1923. p: padding in that dim
  1924. d: dilation in that dim
  1925. k: kernel size in that dim
  1926. s: stride in that dim
  1927. Returns:
  1928. The output length
  1929. """
  1930. return (ln + 2 * p - d * (k - 1) - 1) // s + 1
  1931. def _formula_transposed(ln: int, p: int, d: int, k: int, s: int, op: int) -> int:
  1932. """
  1933. Formula to apply to calculate the length of some dimension of the output
  1934. if transposed convolution is used.
  1935. See: https://pytorch.org/docs/stable/generated/torch.nn.ConvTranspose2d.html
  1936. Args:
  1937. ln: length of the dimension
  1938. p: padding in that dim
  1939. d: dilation in that dim
  1940. k: kernel size in that dim
  1941. s: stride in that dim
  1942. op: output padding in that dim
  1943. Returns:
  1944. The output length
  1945. """
  1946. return (ln - 1) * s - 2 * p + d * (k - 1) + op + 1
  1947. kernel_size = weight.shape[2:]
  1948. dims = input_tensor.shape[2:]
  1949. if is_transposed:
  1950. out_channels = groups * weight.shape[1]
  1951. else:
  1952. out_channels = weight.shape[0]
  1953. if weight.shape[1] * groups != input_tensor.shape[1]:
  1954. raise RuntimeError("Invalid channel dimensions")
  1955. ret_shape = [input_tensor.shape[0], out_channels]
  1956. if isinstance(stride, IntLike):
  1957. stride = [stride] * len(dims)
  1958. elif len(stride) == 1:
  1959. stride = [stride[0]] * len(dims)
  1960. if isinstance(padding, IntLike):
  1961. padding = [padding] * len(dims)
  1962. elif len(padding) == 1:
  1963. padding = [padding[0]] * len(dims)
  1964. if isinstance(dilation, IntLike):
  1965. dilation = [dilation] * len(dims)
  1966. elif len(dilation) == 1:
  1967. dilation = [dilation[0]] * len(dims)
  1968. output_padding_list: Optional[list[int]] = None
  1969. if output_padding:
  1970. if isinstance(output_padding, IntLike):
  1971. output_padding_list = [output_padding] * len(dims)
  1972. elif len(output_padding) == 1:
  1973. output_padding_list = [output_padding[0]] * len(dims)
  1974. else:
  1975. output_padding_list = output_padding
  1976. for i in range(len(dims)):
  1977. # If output_padding is present, we are dealing with a transposed convolution
  1978. if output_padding_list:
  1979. ret_shape.append(
  1980. _formula_transposed(
  1981. dims[i],
  1982. padding[i],
  1983. dilation[i],
  1984. kernel_size[i],
  1985. stride[i],
  1986. output_padding_list[i],
  1987. )
  1988. )
  1989. else:
  1990. ret_shape.append(
  1991. _formula(dims[i], padding[i], dilation[i], kernel_size[i], stride[i])
  1992. )
  1993. from torch.fx.experimental.symbolic_shapes import sym_or
  1994. torch._check(
  1995. sym_or(*[x > 0 for x in ret_shape[2:]]),
  1996. lambda: f"Given input size per channel: {list(dims)}. "
  1997. f"Calculated output size per channel: {ret_shape[2:]}. "
  1998. f"Output size is too small",
  1999. )
  2000. return ret_shape
  2001. def is_channels_last(ten):
  2002. return torch._prims_common.suggest_memory_format(ten) == torch.channels_last
  2003. @register_meta(aten.miopen_batch_norm.default)
  2004. def meta_miopen_batch_norm(
  2005. input_tensor: torch.Tensor,
  2006. weight: torch.Tensor,
  2007. bias: Optional[torch.Tensor],
  2008. running_mean: Optional[torch.Tensor],
  2009. running_var: Optional[torch.Tensor],
  2010. training: bool,
  2011. exponential_average_factor: float,
  2012. epsilon: float,
  2013. ):
  2014. # In batch norm the output is of the same shape as the input
  2015. out_shape = input_tensor.shape
  2016. # If tensor is provided for running_mean and running_var then use this. If these are not
  2017. # provided then we return the shape of weight tensor. Similar to how this is handled in the decomposition
  2018. save_mean_shape = running_mean.shape if running_mean is not None else weight.shape
  2019. save_var_shape = running_var.shape if running_var is not None else weight.shape
  2020. def pick_memory_format():
  2021. if is_channels_last(input_tensor):
  2022. return torch.channels_last
  2023. if input_tensor.is_contiguous(memory_format=torch.contiguous_format):
  2024. return torch.contiguous_format
  2025. return torch.contiguous_format
  2026. out = input_tensor.new_empty(out_shape).to(memory_format=pick_memory_format())
  2027. if training:
  2028. save_mean = input_tensor.new_empty(save_mean_shape)
  2029. save_var = input_tensor.new_empty(save_var_shape)
  2030. else:
  2031. save_mean = input_tensor.new_empty((0,))
  2032. save_var = input_tensor.new_empty((0,))
  2033. return out, save_mean, save_var
  2034. @register_meta(aten.convolution.default)
  2035. def meta_conv(
  2036. input_tensor: torch.Tensor,
  2037. weight: torch.Tensor,
  2038. bias: torch.Tensor,
  2039. stride: list[int],
  2040. padding: list[int],
  2041. dilation: list[int],
  2042. is_transposed: bool,
  2043. output_padding: list[int],
  2044. groups: int,
  2045. ):
  2046. def pick_memory_format():
  2047. if device_hint(input_tensor) == "cuda":
  2048. if is_channels_last(input_tensor) or is_channels_last(weight):
  2049. return torch.channels_last
  2050. else:
  2051. if is_channels_last(input_tensor):
  2052. return torch.channels_last
  2053. if input_tensor.is_contiguous(memory_format=torch.contiguous_format):
  2054. return torch.contiguous_format
  2055. elif input_tensor.is_contiguous(memory_format=torch.preserve_format):
  2056. return torch.preserve_format
  2057. shape_out = calc_conv_nd_return_shape(
  2058. input_tensor,
  2059. weight,
  2060. stride,
  2061. padding,
  2062. dilation,
  2063. is_transposed,
  2064. groups,
  2065. output_padding if is_transposed else None,
  2066. )
  2067. input_channels_dim = 1
  2068. output_channels_dim = 1
  2069. if input_tensor.size(input_channels_dim) == 0:
  2070. shape_out[output_channels_dim] = 0
  2071. out = input_tensor.new_empty(shape_out)
  2072. out = out.to(memory_format=pick_memory_format()) # type: ignore[call-overload]
  2073. return out
  2074. if torch._C._has_mkldnn:
  2075. _meta_lib_dont_use_me_use_register_meta_for_mkldnn = torch.library.Library(
  2076. "mkldnn", "IMPL", "Meta"
  2077. )
  2078. @register_meta(torch.ops.mkldnn._convolution_pointwise.default)
  2079. def meta_mkldnn_convolution_default(
  2080. input_tensor,
  2081. weight,
  2082. bias,
  2083. padding,
  2084. stride,
  2085. dilation,
  2086. groups,
  2087. attr,
  2088. scalars,
  2089. algorithm,
  2090. ):
  2091. shape_out = calc_conv_nd_return_shape(
  2092. input_tensor, weight, stride, padding, dilation, False, groups, []
  2093. )
  2094. out = input_tensor.new_empty(shape_out)
  2095. out_memory_format = torch.channels_last
  2096. if input_tensor.dim() == 5:
  2097. out_memory_format = torch.channels_last_3d
  2098. out = out.to(memory_format=out_memory_format) # type: ignore[call-overload]
  2099. return out
  2100. @register_meta(torch.ops.mkldnn._linear_pointwise.default)
  2101. def meta_linear_pointwise_default(
  2102. input_tensor, weight, bias, attr, scalars, algorithm
  2103. ):
  2104. return input_tensor.new_empty((*input_tensor.shape[:-1], weight.shape[0]))
  2105. if torch._C.has_mkl:
  2106. _meta_lib_dont_use_me_use_register_meta_for_mkl = torch.library.Library(
  2107. "mkl", "IMPL", "Meta"
  2108. )
  2109. @register_meta(torch.ops.mkl._mkl_linear)
  2110. def meta_mkl_linear(input_tensor, packed_weight, orig_weight, bias, batch_size):
  2111. return input_tensor.new_empty(
  2112. (*input_tensor.shape[:-1], orig_weight.shape[0])
  2113. )
  2114. _meta_lib_dont_use_me_use_register_meta_for_onednn = torch.library.Library(
  2115. "onednn", "IMPL", "Meta"
  2116. )
  2117. @register_meta(torch.ops.onednn.qconv2d_pointwise.default)
  2118. @register_meta(torch.ops.onednn.qconv_pointwise.default)
  2119. def meta_qconv_pointwise(
  2120. x,
  2121. x_scale,
  2122. x_zp,
  2123. w, # prepacked_weight
  2124. w_scale,
  2125. w_zp,
  2126. bias,
  2127. stride,
  2128. padding,
  2129. dilation,
  2130. groups,
  2131. output_scale,
  2132. output_zero_point,
  2133. output_dtype,
  2134. attr,
  2135. scalars,
  2136. algorithm,
  2137. ):
  2138. shape_out = calc_conv_nd_return_shape(
  2139. x,
  2140. w,
  2141. stride,
  2142. padding,
  2143. dilation,
  2144. False,
  2145. groups,
  2146. None,
  2147. )
  2148. if output_dtype is None:
  2149. output_dtype = x.dtype
  2150. assert output_dtype in [
  2151. torch.float32,
  2152. torch.bfloat16,
  2153. torch.uint8,
  2154. torch.int8,
  2155. torch.float8_e4m3fn,
  2156. ]
  2157. out = x.new_empty(shape_out, dtype=output_dtype)
  2158. assert len(shape_out) in [3, 4, 5], (
  2159. "Expect output to be 3d/4d/5d for conv1d/2d/3d"
  2160. )
  2161. format = {
  2162. 3: torch.contiguous_format,
  2163. 4: torch.channels_last,
  2164. 5: torch.channels_last_3d,
  2165. }[len(shape_out)]
  2166. out = out.to(memory_format=format)
  2167. return out
  2168. @register_meta(torch.ops.onednn.qconv2d_pointwise.binary)
  2169. def meta_qconv2d_pointwise_binary(
  2170. x,
  2171. x_scale,
  2172. x_zp,
  2173. w,
  2174. w_scale,
  2175. w_zp,
  2176. accum,
  2177. bias,
  2178. stride,
  2179. padding,
  2180. dilation,
  2181. groups,
  2182. output_scale,
  2183. output_zero_point,
  2184. output_dtype,
  2185. accum_scale,
  2186. accum_zero_point,
  2187. binary_op_name,
  2188. alpha,
  2189. unary_op_name,
  2190. unary_op_args,
  2191. unary_op_algorithm,
  2192. ):
  2193. assert binary_op_name == "sum"
  2194. return accum
  2195. @register_meta(torch.ops.onednn.qlinear_pointwise.default)
  2196. @register_meta(torch.ops.onednn.qlinear_pointwise.tensor)
  2197. def meta_qlinear_pointwise(
  2198. x,
  2199. x_scale,
  2200. x_zp,
  2201. w,
  2202. w_scale,
  2203. w_zp,
  2204. bias,
  2205. output_scale,
  2206. output_zero_point,
  2207. output_dtype,
  2208. post_op_name,
  2209. post_op_args,
  2210. post_op_algorithm,
  2211. ):
  2212. output_shape = list(x.shape)
  2213. # The weight has been transposed during the qlinear weight prepack process.
  2214. output_shape[-1] = w.shape[1]
  2215. assert output_dtype in [
  2216. torch.float32,
  2217. torch.bfloat16,
  2218. torch.int8,
  2219. torch.uint8,
  2220. torch.float8_e4m3fn,
  2221. ]
  2222. out = x.new_empty(output_shape, dtype=output_dtype)
  2223. return out
  2224. @register_meta(torch.ops.onednn.qlinear_pointwise.binary)
  2225. @register_meta(torch.ops.onednn.qlinear_pointwise.binary_tensor)
  2226. def meta_qlinear_pointwise_binary(
  2227. x,
  2228. x_scale,
  2229. x_zp,
  2230. w,
  2231. w_scale,
  2232. w_zp,
  2233. x_2,
  2234. bias,
  2235. output_scale,
  2236. output_zero_point,
  2237. output_dtype,
  2238. x2_scale,
  2239. x2_zp,
  2240. binary_op_name,
  2241. alpha,
  2242. unary_op_name,
  2243. unary_op_args,
  2244. unary_op_algorithm,
  2245. ):
  2246. if binary_op_name == "sum":
  2247. return x_2
  2248. output_shape = list(x.shape)
  2249. # The weight has been transposed during the qlinear weight prepack process.
  2250. output_shape[-1] = w.shape[1]
  2251. assert output_dtype in [
  2252. torch.float32,
  2253. torch.bfloat16,
  2254. torch.uint8,
  2255. torch.int8,
  2256. torch.float8_e4m3fn,
  2257. ]
  2258. out = x.new_empty(output_shape, dtype=output_dtype)
  2259. return out
  2260. @register_meta(torch.ops.onednn.linear_dynamic_fp16.default)
  2261. @register_meta(torch.ops.onednn.linear_relu_dynamic_fp16.default)
  2262. def meta_linear_dynamic_fp16(
  2263. x,
  2264. w,
  2265. bias,
  2266. ):
  2267. output_shape = list(x.shape)
  2268. # The weight has been transposed during the qlinear weight prepack process.
  2269. output_shape[-1] = w.shape[1]
  2270. out = x.new_empty(output_shape)
  2271. return out
  2272. _meta_lib_dont_use_me_use_register_meta_for_quantized = torch.library.Library(
  2273. "quantized", "IMPL", "Meta"
  2274. )
  2275. @register_meta(torch.ops.quantized.max_pool2d)
  2276. def meta_quantized_max_pool2d(
  2277. input,
  2278. kernel_size,
  2279. stride=(),
  2280. padding=(0,),
  2281. dilation=(1,),
  2282. ceil_mode=False,
  2283. ):
  2284. (
  2285. nInputPlane,
  2286. outputHeight,
  2287. outputWidth,
  2288. ) = max_pool2d_checks_and_compute_shape(
  2289. input, kernel_size, stride, padding, dilation, ceil_mode
  2290. )
  2291. nbatch = input.size(-4) if input.dim() == 4 else 1
  2292. memory_format = torch.channels_last
  2293. if input.dim() == 3:
  2294. size = [nInputPlane, outputHeight, outputWidth]
  2295. else:
  2296. size = [nbatch, nInputPlane, outputHeight, outputWidth]
  2297. return torch.empty(
  2298. size,
  2299. dtype=input.dtype,
  2300. device=input.device,
  2301. memory_format=memory_format,
  2302. )
  2303. @register_meta(torch.ops.quantized.int4mm_packed_weight_cpu)
  2304. def meta_int4mm_packed_weight_cpu(x, w, q_group_size, q_scale_and_zeros):
  2305. torch._check(x.dim() == 2, f"x must be a 2D tensor, got {x.dim()}D")
  2306. torch._check(w.dim() == 2, f"w must be a 2D tensor, got {w.dim()}D")
  2307. torch._check(
  2308. x.dtype in [torch.float32, torch.float16, torch.bfloat16],
  2309. f"expected x to be f32/f16/bf16, got {x.dtype}",
  2310. )
  2311. torch._check(w.dtype == torch.uint8, f"expected w to be uint8, got {w.dtype}")
  2312. torch._check(
  2313. q_group_size.dtype == torch.int64,
  2314. f"q_group_size must be int64, got {q_group_size.dtype}",
  2315. )
  2316. torch._check(
  2317. q_scale_and_zeros.dtype == x.dtype,
  2318. f"q_scale_and_zeros must have the same dtype as x, got {q_scale_and_zeros.dtype}",
  2319. )
  2320. return x.new_empty(x.size(0), w.size(0), dtype=x.dtype)
  2321. # from check_dim_size() in aten/src/ATen/TensorUtils.cpp.
  2322. def check_dim_size(tensor, dim, dim_size, size):
  2323. torch._check(
  2324. tensor.dim() == dim and tensor.shape[dim_size] == size,
  2325. lambda: f"Expected a tensor of dimension {dim} and tensor.size[{dim_size}] == {size}, "
  2326. + f"but got : dimension {tensor.dim()} and tensor.size[{dim_size}] = {tensor.shape[dim_size]}",
  2327. )
  2328. @register_meta(aten.avg_pool2d.default)
  2329. def meta_avg_pool2d(
  2330. input,
  2331. kernel_size,
  2332. stride=(),
  2333. padding=(0,),
  2334. ceil_mode=False,
  2335. count_include_pad=True,
  2336. divisor_override=None,
  2337. ):
  2338. def unpack(name, val):
  2339. torch._check(
  2340. len(val) in [1, 2],
  2341. lambda: f"avg_pool2d: {name} must either be a single int, or a tuple of two ints",
  2342. )
  2343. H = val[0]
  2344. W = H if len(val) == 1 else val[1]
  2345. return H, W
  2346. kH, kW = unpack("kernel_size", kernel_size)
  2347. torch._check(
  2348. len(stride) in [0, 1, 2],
  2349. lambda: "avg_pool2d: stride must either be omitted, a single int, or a tuple of two ints",
  2350. )
  2351. torch._check(
  2352. input.dtype not in [torch.uint8, torch.uint16, torch.uint32, torch.uint64],
  2353. lambda: f""""avg_pool2d" not implemented for '{input.dtype.__str__()}'""",
  2354. )
  2355. if len(stride) == 0:
  2356. dH, dW = kH, kW
  2357. elif len(stride) == 1:
  2358. dH, dW = stride[0], stride[0]
  2359. else:
  2360. dH, dW = unpack("stride", stride)
  2361. padH, padW = unpack("padding", padding)
  2362. torch._check(
  2363. divisor_override is None or divisor_override != 0,
  2364. lambda: "divisor must be not zero",
  2365. )
  2366. nbatch = input.size(-4) if input.dim() == 4 else 1
  2367. nInputPlane = input.size(-3)
  2368. inputHeight = input.size(-2)
  2369. inputWidth = input.size(-1)
  2370. outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode)
  2371. outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode)
  2372. memory_format = utils.suggest_memory_format(input)
  2373. pool2d_shape_check(
  2374. input,
  2375. kH,
  2376. kW,
  2377. dH,
  2378. dW,
  2379. padH,
  2380. padW,
  2381. 1,
  2382. 1,
  2383. nInputPlane,
  2384. inputHeight,
  2385. inputWidth,
  2386. outputHeight,
  2387. outputWidth,
  2388. memory_format,
  2389. )
  2390. if input.dim() == 3:
  2391. size = [nInputPlane, outputHeight, outputWidth]
  2392. else:
  2393. size = [nbatch, nInputPlane, outputHeight, outputWidth]
  2394. return torch.empty(
  2395. size,
  2396. dtype=input.dtype,
  2397. device=input.device,
  2398. memory_format=memory_format,
  2399. )
  2400. # from avg_pool2d_backward_shape_check() in aten/src/ATen/native/Pool.h.
  2401. def avg_pool2d_backward_shape_check(
  2402. input,
  2403. gradOutput,
  2404. nbatch,
  2405. kH,
  2406. kW,
  2407. dH,
  2408. dW,
  2409. padH,
  2410. padW,
  2411. nInputPlane,
  2412. inputHeight,
  2413. inputWidth,
  2414. outputHeight,
  2415. outputWidth,
  2416. mem_format,
  2417. ):
  2418. pool2d_shape_check(
  2419. input,
  2420. kH,
  2421. kW,
  2422. dH,
  2423. dW,
  2424. padH,
  2425. padW,
  2426. 1,
  2427. 1,
  2428. nInputPlane,
  2429. inputHeight,
  2430. inputWidth,
  2431. outputHeight,
  2432. outputWidth,
  2433. mem_format,
  2434. )
  2435. ndim = input.dim()
  2436. nOutputPlane = nInputPlane
  2437. check_dim_size(gradOutput, ndim, ndim - 3, nOutputPlane)
  2438. check_dim_size(gradOutput, ndim, ndim - 2, outputHeight)
  2439. check_dim_size(gradOutput, ndim, ndim - 1, outputWidth)
  2440. # Don't override the C++ registration.
  2441. @register_meta(aten.avg_pool2d_backward.default)
  2442. def meta_avg_pool2d_backward(
  2443. gradOutput_,
  2444. input,
  2445. kernel_size,
  2446. stride,
  2447. padding,
  2448. ceil_mode,
  2449. count_include_pad,
  2450. divisor_override,
  2451. ):
  2452. # From aten/src/ATen/native/AveragePool2d.cpp structured kernel meta func.
  2453. torch._check(
  2454. len(kernel_size) == 1 or len(kernel_size) == 2,
  2455. lambda: "avg_pool2d: kernel_size must either be a single int, or a tuple of two ints",
  2456. )
  2457. kH = kernel_size[0]
  2458. kW = kH if len(kernel_size) == 1 else kernel_size[1]
  2459. torch._check(
  2460. len(stride) == 0 or len(stride) == 1 or len(stride) == 2,
  2461. lambda: "avg_pool2d: stride must either be omitted, a single int, or a tuple of two ints",
  2462. )
  2463. dH = kH if len(stride) == 0 else stride[0]
  2464. dW = kW if len(stride) == 0 else dH if len(stride) == 1 else stride[1]
  2465. torch._check(
  2466. len(padding) == 1 or len(padding) == 2,
  2467. lambda: "avg_pool2d: padding must either be a single int, or a tuple of two ints",
  2468. )
  2469. padH = padding[0]
  2470. padW = padH if len(padding) == 1 else padding[1]
  2471. torch._check(
  2472. divisor_override is None or divisor_override != 0,
  2473. lambda: "divisor must be not zero",
  2474. )
  2475. input_size = input.shape
  2476. nbatch = input_size[-4] if input.dim() == 4 else 1
  2477. nInputPlane = input_size[-3]
  2478. inputHeight = input_size[-2]
  2479. inputWidth = input_size[-1]
  2480. outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, 1, ceil_mode)
  2481. outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, 1, ceil_mode)
  2482. mem_format = utils.suggest_memory_format(input)
  2483. avg_pool2d_backward_shape_check(
  2484. input,
  2485. gradOutput_,
  2486. nbatch,
  2487. kH,
  2488. kW,
  2489. dH,
  2490. dW,
  2491. padH,
  2492. padW,
  2493. nInputPlane,
  2494. inputHeight,
  2495. inputWidth,
  2496. outputHeight,
  2497. outputWidth,
  2498. mem_format,
  2499. )
  2500. return torch.empty(
  2501. input_size,
  2502. dtype=input.dtype,
  2503. device=input.device,
  2504. memory_format=mem_format,
  2505. )
  2506. @register_meta(aten.avg_pool3d)
  2507. @out_wrapper()
  2508. def meta_avg_pool3d(
  2509. input,
  2510. kernel_size,
  2511. stride=(),
  2512. padding=(0,),
  2513. ceil_mode=False,
  2514. count_include_pad=True,
  2515. divisor_override=None,
  2516. ):
  2517. torch._check(
  2518. len(kernel_size) in (1, 3),
  2519. lambda: "avg_pool3d: kernel_size must be a single int, or a tuple of three ints",
  2520. )
  2521. kT = kernel_size[0]
  2522. kH = kT if len(kernel_size) == 1 else kernel_size[1]
  2523. kW = kT if len(kernel_size) == 1 else kernel_size[2]
  2524. torch._check(
  2525. not stride or len(stride) in (1, 3),
  2526. lambda: "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints",
  2527. )
  2528. torch._check(
  2529. input.dtype not in [torch.uint8, torch.uint16, torch.uint32, torch.uint64],
  2530. lambda: f""""avg_pool3d" not implemented for '{input.dtype.__str__()}'""",
  2531. )
  2532. dT = kT if not stride else stride[0]
  2533. dH = kH if not stride else (dT if len(stride) == 1 else stride[1])
  2534. dW = kW if not stride else (dT if len(stride) == 1 else stride[2])
  2535. torch._check(
  2536. len(padding) in (1, 3),
  2537. lambda: "avg_pool3d: padding must be a single int, or a tuple of three ints",
  2538. )
  2539. padT = padding[0]
  2540. padH = padT if len(padding) == 1 else padding[1]
  2541. padW = padT if len(padding) == 1 else padding[2]
  2542. torch._check(
  2543. input.ndim in (4, 5),
  2544. lambda: "non-empty 4D or 5D (batch mode) tensor expected for input",
  2545. )
  2546. torch._check(
  2547. not divisor_override or divisor_override != 0,
  2548. lambda: "divisor must be not zero",
  2549. )
  2550. nbatch = input.size(0)
  2551. nslices = input.size(-4)
  2552. itime = input.size(-3)
  2553. iheight = input.size(-2)
  2554. iwidth = input.size(-1)
  2555. otime = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode)
  2556. oheight = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode)
  2557. owidth = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode)
  2558. pool3d_shape_check(
  2559. input,
  2560. nslices,
  2561. kT,
  2562. kH,
  2563. kW,
  2564. dT,
  2565. dH,
  2566. dW,
  2567. padT,
  2568. padH,
  2569. padW,
  2570. 1,
  2571. 1,
  2572. 1,
  2573. itime,
  2574. iheight,
  2575. iwidth,
  2576. otime,
  2577. oheight,
  2578. owidth,
  2579. "avg_pool3d()",
  2580. check_input_size=True,
  2581. )
  2582. if input.ndim == 4:
  2583. return input.new_empty((nslices, otime, oheight, owidth))
  2584. else:
  2585. return input.new_empty((nbatch, nslices, otime, oheight, owidth))
  2586. @register_meta(aten.avg_pool3d_backward)
  2587. @out_wrapper("grad_input")
  2588. def meta_avg_pool3d_backward(
  2589. grad_output,
  2590. input,
  2591. kernel_size,
  2592. stride,
  2593. padding,
  2594. ceil_mode,
  2595. count_include_pad,
  2596. divisor_override,
  2597. ):
  2598. torch._check(
  2599. len(kernel_size) in (1, 3),
  2600. lambda: "avg_pool3d: kernel_size must be a single int, or a tuple of three ints",
  2601. )
  2602. kT = kernel_size[0]
  2603. kH = kT if len(kernel_size) == 1 else kernel_size[1]
  2604. kW = kT if len(kernel_size) == 1 else kernel_size[2]
  2605. torch._check(
  2606. not stride or len(stride) in (1, 3),
  2607. lambda: "avg_pool3d: stride must be omitted, a single int, or a tuple of three ints",
  2608. )
  2609. dT = kT if not stride else stride[0]
  2610. dH = kH if not stride else (dT if len(stride) == 1 else stride[1])
  2611. dW = kW if not stride else (dT if len(stride) == 1 else stride[2])
  2612. torch._check(
  2613. len(padding) in (1, 3),
  2614. lambda: "avg_pool3d: padding must be a single int, or a tuple of three ints",
  2615. )
  2616. padT = padding[0]
  2617. padH = padT if len(padding) == 1 else padding[1]
  2618. padW = padT if len(padding) == 1 else padding[2]
  2619. torch._check(
  2620. input.ndim in (4, 5),
  2621. lambda: "non-empty 4D or 5D (batch mode) tensor expected for input",
  2622. )
  2623. torch._check(
  2624. not divisor_override or divisor_override != 0,
  2625. lambda: "divisor must be not zero",
  2626. )
  2627. nslices = input.size(-4)
  2628. itime = input.size(-3)
  2629. iheight = input.size(-2)
  2630. iwidth = input.size(-1)
  2631. otime_for_shape_check = pooling_output_shape(itime, kT, padT, dT, 1, ceil_mode)
  2632. oheight_for_shape_check = pooling_output_shape(iheight, kH, padH, dH, 1, ceil_mode)
  2633. owidth_for_shape_check = pooling_output_shape(iwidth, kW, padW, dW, 1, ceil_mode)
  2634. avg_pool3d_backward_shape_check(
  2635. input,
  2636. grad_output,
  2637. nslices,
  2638. kT,
  2639. kH,
  2640. kW,
  2641. dT,
  2642. dH,
  2643. dW,
  2644. padT,
  2645. padH,
  2646. padW,
  2647. itime,
  2648. iheight,
  2649. iwidth,
  2650. otime_for_shape_check,
  2651. oheight_for_shape_check,
  2652. owidth_for_shape_check,
  2653. "avg_pool3d_backward()",
  2654. )
  2655. return input.new_empty(input.shape)
  2656. @register_meta(aten._adaptive_avg_pool2d.default)
  2657. def meta_adaptive_avg_pool2d(self, output_size):
  2658. torch._check(
  2659. self.ndim == 3 or self.ndim == 4,
  2660. lambda: f"Expected 3D or 4D tensor, but got {self.shape}",
  2661. )
  2662. output_shape = self.shape[:-2] + tuple(output_size)
  2663. memory_format = utils.suggest_memory_format(self)
  2664. # need to set memory_format to preserve the memory format of the input
  2665. # channel last input should have channel last output
  2666. return torch.empty(
  2667. output_shape,
  2668. dtype=self.dtype,
  2669. device=self.device,
  2670. memory_format=memory_format,
  2671. )
  2672. @register_meta(aten._adaptive_avg_pool3d.default)
  2673. def meta_adaptive_avg_pool3d(self, output_size):
  2674. torch._check(
  2675. self.ndim == 4 or self.ndim == 5,
  2676. lambda: f"Expected 4D or 5D tensor, but got {self.shape}",
  2677. )
  2678. return self.new_empty(self.shape[:-3] + tuple(output_size))
  2679. @register_meta(aten._adaptive_avg_pool2d_backward.default)
  2680. def meta__adaptive_avg_pool2d_backward(grad_out, self):
  2681. ndim = grad_out.ndim
  2682. for i in range(1, ndim):
  2683. torch._check(
  2684. grad_out.size(i) > 0,
  2685. lambda: f"adaptive_avg_pool2d_backward(): Expected grad_output to have non-zero \
  2686. size for non-batch dimensions, {grad_out.shape} with dimension {i} being empty",
  2687. )
  2688. torch._check(
  2689. ndim == 3 or ndim == 4,
  2690. lambda: f"adaptive_avg_pool2d_backward(): Expected 3D or 4D tensor, but got {self.shape}",
  2691. )
  2692. torch._check(
  2693. self.dtype == grad_out.dtype,
  2694. lambda: f"expected dtype {self.dtype} for `grad_output` but got dtype {grad_out.dtype}",
  2695. )
  2696. memory_format = torch.contiguous_format
  2697. if is_channels_last(self):
  2698. memory_format = torch.channels_last
  2699. return self.new_empty(self.shape).to(memory_format=memory_format)
  2700. @register_meta(aten._adaptive_avg_pool3d_backward)
  2701. @out_wrapper("grad_input")
  2702. def meta__adaptive_avg_pool3d_backward(grad_output, self):
  2703. _adaptive_pool_empty_output_check(grad_output, "adaptive_avg_pool3d_backward")
  2704. return torch.empty_like(self, memory_format=torch.legacy_contiguous_format)
  2705. def _adaptive_pool_empty_output_check(grad_output: Tensor, arg_name: str):
  2706. ndim = grad_output.ndim
  2707. for i in range(1, ndim):
  2708. torch._check(
  2709. grad_output.size(i) > 0,
  2710. lambda: (
  2711. f"{arg_name}(): Expected grad_output to have non-zero size for non-batch dimensions, "
  2712. f"but grad_output has sizes {grad_output.shape} with dimension {i} being empty"
  2713. ),
  2714. )
  2715. @register_meta(aten.adaptive_max_pool2d)
  2716. @out_wrapper("out", "indices")
  2717. def meta_adaptive_max_pool2d(input, output_size):
  2718. ndim = input.ndim
  2719. torch._check(
  2720. ndim in (3, 4),
  2721. lambda: f"adaptive_max_pool2d(): Expected 3D or 4D tensor, but got: {input.shape}",
  2722. )
  2723. for i in range(1, ndim):
  2724. torch._check(
  2725. input.size(i) > 0,
  2726. lambda: (
  2727. f"adaptive_max_pool2d(): Expected input to have non-zero size for non-batch dimensions, "
  2728. f"but input has sizes {input.shape} with dimension {i} being empty"
  2729. ),
  2730. )
  2731. torch._check(
  2732. len(output_size) == 2,
  2733. lambda: "adaptive_max_pool2d(): internal error: output_size.size() must be 2",
  2734. )
  2735. dimH = 1
  2736. sizeB = 1
  2737. sizeD = 0
  2738. if input.ndim == 4:
  2739. sizeB = input.size(0)
  2740. dimH += 1
  2741. sizeD = input.size(dimH - 1)
  2742. osizeH, osizeW = output_size
  2743. if input.ndim == 3:
  2744. out_shape = (sizeD, osizeH, osizeW)
  2745. out = input.new_empty(out_shape)
  2746. indices = input.new_empty(out_shape, dtype=torch.int64)
  2747. return out, indices
  2748. else:
  2749. out_shape = (sizeB, sizeD, osizeH, osizeW) # type: ignore[assignment]
  2750. memory_format = utils.suggest_memory_format(input)
  2751. out = input.new_empty(out_shape).to(memory_format=memory_format)
  2752. indices = input.new_empty(out_shape, dtype=torch.int64).to(
  2753. memory_format=memory_format
  2754. )
  2755. return out, indices
  2756. @register_meta(aten.adaptive_max_pool2d_backward)
  2757. @out_wrapper("grad_input")
  2758. def meta_adaptive_max_pool2d_backward(grad_output, input, indices):
  2759. ndim = grad_output.ndim
  2760. torch._check(
  2761. ndim in (3, 4),
  2762. lambda: f"adaptive_max_pooling2d_backward(): Expected 3D or 4D grad_output, but got: {grad_output.shape}",
  2763. )
  2764. _adaptive_pool_empty_output_check(grad_output, "adaptive_max_pool2d_backward")
  2765. torch._check(
  2766. input.dtype == grad_output.dtype,
  2767. lambda: f"expected dtype {input.dtype} for `grad_output` but got dtype {grad_output.dtype}",
  2768. )
  2769. memory_format = utils.suggest_memory_format(input)
  2770. return input.new_empty(input.shape).to(memory_format=memory_format)
  2771. @register_meta(aten.adaptive_max_pool3d)
  2772. @out_wrapper("out", "indices")
  2773. def meta_adaptive_max_pool3d(input, output_size):
  2774. ndim = input.ndim
  2775. torch._check(
  2776. ndim in (4, 5),
  2777. lambda: f"adaptive_max_pool3d(): Expected 4D or 5D tensor, but got: {input.shape}",
  2778. )
  2779. for i in range(1, ndim):
  2780. torch._check(
  2781. input.size(i) > 0,
  2782. lambda: (
  2783. f"adaptive_max_pool3d(): Expected input to have non-zero size for non-batch dimensions, "
  2784. f"but input has sizes {input.shape} with dimension {i} being empty"
  2785. ),
  2786. )
  2787. torch._check(
  2788. len(output_size) == 3,
  2789. lambda: "adaptive_max_pool3d(): internal error: output_size.size() must be 3",
  2790. )
  2791. dimD = 0
  2792. sizeB = 1
  2793. sizeD = 0
  2794. if ndim == 5:
  2795. sizeB = input.size(0)
  2796. dimD += 1
  2797. sizeD = input.size(dimD)
  2798. osizeT, osizeH, osizeW = output_size
  2799. if ndim == 4:
  2800. out_shape = (sizeD, osizeT, osizeH, osizeW)
  2801. else:
  2802. out_shape = (sizeB, sizeD, osizeT, osizeH, osizeW) # type: ignore[assignment]
  2803. out = input.new_empty(out_shape)
  2804. indices = input.new_empty(out_shape, dtype=torch.int64)
  2805. return out, indices
  2806. @register_meta(aten.adaptive_max_pool3d_backward)
  2807. @out_wrapper("grad_input")
  2808. def meta_adaptive_max_pool3d_backward(grad_output, input, indices):
  2809. _adaptive_pool_empty_output_check(grad_output, "adaptive_max_pool3d_backward")
  2810. return input.new_empty(input.shape)
  2811. @register_meta(aten.repeat_interleave.Tensor)
  2812. def meta_repeat_interleave_Tensor(repeats, output_size=None):
  2813. if output_size is None:
  2814. raise RuntimeError("cannot repeat_interleave a meta tensor without output_size")
  2815. return repeats.new_empty(output_size)
  2816. @register_meta([aten.complex.default, aten.complex.out])
  2817. @out_wrapper()
  2818. def meta_complex(real, imag):
  2819. assert real.dtype.is_floating_point
  2820. assert imag.dtype.is_floating_point
  2821. result = elementwise_meta(
  2822. real.to(corresponding_complex_dtype(real.dtype)),
  2823. imag.to(corresponding_complex_dtype(imag.dtype)),
  2824. type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
  2825. )
  2826. return result
  2827. @register_meta([aten.nonzero_static.default, aten.nonzero_static.out])
  2828. @out_wrapper()
  2829. def nonzero_static(self, *, size, fill_value: int = -1):
  2830. return self.new_empty((size, self.dim()), dtype=torch.long)
  2831. @register_meta([torch.ops.aten.nonzero.default, torch.ops.aten.nonzero.out])
  2832. @out_wrapper()
  2833. def nonzero(self):
  2834. torch._check_not_implemented(
  2835. exp_config.meta_nonzero_assume_all_nonzero,
  2836. lambda: "The register_meta function for torch.nonzero() raises unimplemented by default, "
  2837. "as a correct data-independent implementation does not exist. This implementation "
  2838. "returns a fake value, assuming all elements of the tensor are non-zero. "
  2839. "To enable this registration, please set "
  2840. "'torch.fx.experimental._config.meta_nonzero_assume_all_nonzero' to True.",
  2841. )
  2842. return torch.empty_strided(
  2843. (self.numel(), self.dim()),
  2844. (1, self.numel()),
  2845. dtype=torch.long,
  2846. device=self.device,
  2847. )
  2848. @register_meta([aten.index.Tensor, aten._unsafe_index.Tensor])
  2849. def meta_index_Tensor(self, indices):
  2850. torch._check(bool(indices), lambda: "at least one index must be provided")
  2851. # aten::index is the internal advanced indexing implementation
  2852. # checkIndexTensorTypes and expandTensors
  2853. result: list[Optional[Tensor]] = []
  2854. for i, index in enumerate(indices):
  2855. if index is not None:
  2856. torch._check(
  2857. index.dtype in [torch.long, torch.int, torch.int8, torch.bool],
  2858. lambda: "tensors used as indices must be long, int, byte or bool tensors",
  2859. )
  2860. if index.dtype in [torch.int8, torch.bool]:
  2861. nonzero = index.nonzero()
  2862. k = len(result)
  2863. torch._check_index(
  2864. k + index.ndim <= self.ndim,
  2865. lambda: f"too many indices for tensor of dimension {self.ndim}",
  2866. )
  2867. for j in range(index.ndim):
  2868. torch._check_index(
  2869. index.shape[j] == self.shape[k + j],
  2870. lambda: f"The shape of the mask {index.shape} at index {i} "
  2871. f"does not match the shape of the indexed tensor {self.shape} at index {k + j}",
  2872. )
  2873. result.append(nonzero.select(1, j))
  2874. else:
  2875. result.append(index)
  2876. else:
  2877. result.append(index)
  2878. indices = result
  2879. torch._check(
  2880. len(indices) <= self.ndim,
  2881. lambda: f"too many indices for tensor of dimension {self.ndim} (got {len(indices)})",
  2882. )
  2883. # expand_outplace
  2884. import torch._refs as refs # avoid import cycle in mypy
  2885. indices = list(refs._maybe_broadcast(*indices))
  2886. # add missing null tensors
  2887. while len(indices) < self.ndim:
  2888. indices.append(None)
  2889. # hasContiguousSubspace
  2890. # true if all non-null tensors are adjacent
  2891. # See:
  2892. # https://numpy.org/doc/stable/user/basics.indexing.html#combining-advanced-and-basic-indexing
  2893. # https://stackoverflow.com/questions/53841497/why-does-numpy-mixed-basic-advanced-indexing-depend-on-slice-adjacency
  2894. state = 0
  2895. has_contiguous_subspace = False
  2896. for index in indices:
  2897. if state == 0:
  2898. if index is not None:
  2899. state = 1
  2900. elif state == 1:
  2901. if index is None:
  2902. state = 2
  2903. else:
  2904. if index is not None:
  2905. break
  2906. else:
  2907. has_contiguous_subspace = True
  2908. # transposeToFront
  2909. # This is the logic that causes the newly inserted dimensions to show up
  2910. # at the beginning of the tensor, if they're not contiguous
  2911. if not has_contiguous_subspace:
  2912. dims = []
  2913. transposed_indices = []
  2914. for i, index in enumerate(indices):
  2915. if index is not None:
  2916. dims.append(i)
  2917. transposed_indices.append(index)
  2918. for i, index in enumerate(indices):
  2919. if index is None:
  2920. dims.append(i)
  2921. transposed_indices.append(index)
  2922. self = self.permute(dims)
  2923. indices = transposed_indices
  2924. # AdvancedIndex::AdvancedIndex
  2925. # Now we can assume the indices have contiguous subspace
  2926. # This is simplified from AdvancedIndex which goes to more effort
  2927. # to put the input and indices in a form so that TensorIterator can
  2928. # take them. If we write a ref for this, probably that logic should
  2929. # get implemented
  2930. before_shape: list[int] = []
  2931. after_shape: list[int] = []
  2932. replacement_shape: list[int] = []
  2933. for dim, index in enumerate(indices):
  2934. if index is None:
  2935. if replacement_shape:
  2936. after_shape.append(self.shape[dim])
  2937. else:
  2938. before_shape.append(self.shape[dim])
  2939. else:
  2940. replacement_shape = list(index.shape)
  2941. def _restride_src(self):
  2942. """
  2943. This follows restride_src in TensorAdvancedIndexing.cpp
  2944. """
  2945. shape = before_shape + replacement_shape + after_shape
  2946. strides = list(self.stride())
  2947. strides[len(before_shape) : len(self.shape) - len(after_shape)] = [0] * len(
  2948. replacement_shape
  2949. )
  2950. return self.as_strided(shape, strides)
  2951. out = self.new_empty(before_shape + replacement_shape + after_shape)
  2952. from torch.fx.experimental.symbolic_shapes import guard_or_false
  2953. if guard_or_false(self.numel() == 0):
  2954. # No need to worry about the output strides if self is empty.
  2955. return out
  2956. # Try to follow eager to decide the output stride based on self.
  2957. # Note that perm here is the reverse of the 'perm_' decided by
  2958. # TensorIteratorBase::reorder_dimensions
  2959. restrided_self = _restride_src(self)
  2960. perm = utils.compute_elementwise_output_logical_to_physical_perm(restrided_self)
  2961. # Follow TensorIteratorBase::allocate_or_resize_outputs
  2962. if list(perm) != list(range(len(perm))):
  2963. perm_shape = utils.apply_perm(out.shape, perm)
  2964. new_stride = utils.make_contiguous_strides_for(perm_shape)
  2965. new_stride = utils.apply_perm(new_stride, utils.invert_perm(perm))
  2966. out = out.as_strided(out.size(), new_stride)
  2967. return out
  2968. @register_meta([aten.convolution_backward.default])
  2969. def meta_convolution_backward(
  2970. grad_output_,
  2971. input_,
  2972. weight_,
  2973. bias_sizes_opt,
  2974. stride,
  2975. padding,
  2976. dilation,
  2977. transposed,
  2978. output_padding,
  2979. groups,
  2980. output_mask,
  2981. ):
  2982. # High level logic taken from slow_conv3d_backward_cpu which should
  2983. # be representative of all convolution_backward impls
  2984. backend_grad_input = None
  2985. backend_grad_weight = None
  2986. backend_grad_bias = None
  2987. if output_mask[0]:
  2988. backend_grad_input = grad_output_.new_empty(input_.size())
  2989. if output_mask[1]:
  2990. backend_grad_weight = grad_output_.new_empty(weight_.size())
  2991. if output_mask[2]:
  2992. backend_grad_bias = grad_output_.new_empty(bias_sizes_opt)
  2993. return (backend_grad_input, backend_grad_weight, backend_grad_bias)
  2994. @register_meta([aten.addbmm.default, aten.addbmm.out])
  2995. @out_wrapper(exact_dtype=True)
  2996. def meta_addbmm(self, batch1, batch2, *, beta=1, alpha=1):
  2997. dim1 = batch1.size(1)
  2998. dim2 = batch2.size(2)
  2999. self = self.expand((dim1, dim2))
  3000. torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor")
  3001. torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor")
  3002. torch._check(
  3003. batch1.size(0) == batch2.size(0),
  3004. lambda: f"batch1 and batch2 must have same number of batches, got {batch1.size(0)} and {batch2.size(0)}",
  3005. )
  3006. torch._check(
  3007. batch1.size(2) == batch2.size(1),
  3008. lambda: (
  3009. f"Incompatible matrix sizes for bmm ({batch1.size(1)}x{batch1.size(2)} "
  3010. f"and {batch2.size(1)}x{batch2.size(2)})"
  3011. ),
  3012. )
  3013. torch._check(
  3014. self.size(0) == dim1 and self.size(1) == dim2,
  3015. lambda: "self tensor does not match matmul output shape",
  3016. )
  3017. return self.new_empty(self.size())
  3018. @register_meta([aten.randint_like.Tensor])
  3019. def meta_randint_like(self, high, **kwargs):
  3020. return self.new_empty(self.size())
  3021. @register_meta([aten._fused_adam_.default, aten._fused_adamw_.default])
  3022. def meta__fused_adam_(
  3023. self,
  3024. grads,
  3025. exp_avgs,
  3026. exp_avg_sqs,
  3027. max_exp_avg_sqs,
  3028. state_steps,
  3029. *,
  3030. lr,
  3031. beta1,
  3032. beta2,
  3033. weight_decay,
  3034. eps,
  3035. amsgrad,
  3036. maximize,
  3037. grad_scale=None,
  3038. found_inf=None,
  3039. ):
  3040. for l in [self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps]:
  3041. torch._check(
  3042. isinstance(l, list),
  3043. lambda: f"exponent must be a tensor list but got {type(l)}",
  3044. )
  3045. @register_meta([aten._fused_adam.default])
  3046. def meta__fused_adam(
  3047. self,
  3048. grads,
  3049. exp_avgs,
  3050. exp_avg_sqs,
  3051. max_exp_avg_sqs,
  3052. state_steps,
  3053. *,
  3054. lr,
  3055. beta1,
  3056. beta2,
  3057. weight_decay,
  3058. eps,
  3059. amsgrad,
  3060. maximize,
  3061. grad_scale=None,
  3062. found_inf=None,
  3063. ):
  3064. for l in [self, grads, exp_avgs, exp_avg_sqs, max_exp_avg_sqs, state_steps]:
  3065. torch._check(
  3066. isinstance(l, list),
  3067. lambda: f"exponent must be a tensor list but got {type(l)}",
  3068. )
  3069. def empty_like_list(tensor_list):
  3070. return [torch.empty_like(t) for t in tensor_list]
  3071. return (
  3072. empty_like_list(self),
  3073. empty_like_list(grads),
  3074. empty_like_list(exp_avgs),
  3075. empty_like_list(exp_avg_sqs),
  3076. empty_like_list(max_exp_avg_sqs),
  3077. )
  3078. @register_meta([aten._int_mm])
  3079. @out_wrapper()
  3080. def meta__int_mm(a, b):
  3081. torch._check(a.dim() == 2, lambda: "a must be a 2D tensor")
  3082. torch._check(b.dim() == 2, lambda: "b must be a 2D tensor")
  3083. torch._check(
  3084. a.dtype is torch.int8,
  3085. lambda: f"expected self to be int8, got {a.dtype}",
  3086. )
  3087. torch._check(
  3088. b.dtype is torch.int8,
  3089. lambda: f"expected mat2 to be int8, got {b.dtype}",
  3090. )
  3091. torch._check(
  3092. a.size(1) == b.size(0),
  3093. lambda: (
  3094. f"Incompatible matrix sizes for _int_mm ({a.size(0)}x{a.size(1)} "
  3095. f"and {b.size(0)}x{b.size(1)})"
  3096. ),
  3097. )
  3098. return a.new_empty((a.size(0), b.size(1)), dtype=torch.int32)
  3099. @register_meta([aten._convert_weight_to_int4pack])
  3100. def meta__convert_weight_to_int4pack(w, inner_k_tiles):
  3101. torch._check(w.dim() == 2, lambda: "w must be a 2D tensor")
  3102. torch._check(
  3103. w.dtype is torch.uint8,
  3104. lambda: f"expected w to be uint8, got {w.dtype}",
  3105. )
  3106. n = w.size(0)
  3107. k = w.size(1) * 2 # w is [n][k / 2] uint8
  3108. return w.new_empty(
  3109. (
  3110. n // 8,
  3111. k // (inner_k_tiles * 16),
  3112. 32,
  3113. inner_k_tiles // 2,
  3114. ),
  3115. dtype=torch.int32,
  3116. )
  3117. @register_meta([aten._convert_weight_to_int4pack_for_cpu])
  3118. def meta__convert_weight_to_int4pack_for_cpu(w, inner_k_tiles):
  3119. torch._check(w.dim() == 2, lambda: "w must be a 2D tensor")
  3120. torch._check(
  3121. w.dtype is torch.int32,
  3122. lambda: f"expected w to be int32, got {w.dtype}",
  3123. )
  3124. n = w.size(0)
  3125. k = w.size(1) # w is [n][k] int32
  3126. return w.new_empty(
  3127. (n, k // 2),
  3128. dtype=torch.uint8,
  3129. )
  3130. @register_meta([aten._weight_int4pack_mm])
  3131. def meta__weight_int4pack_mm(x, w, q_group_size, q_scale_and_zeros):
  3132. torch._check(x.dim() == 2, lambda: "x must be a 2D tensor")
  3133. torch._check(w.dim() == 4, lambda: "w must be a 4D tensor")
  3134. torch._check(
  3135. x.dtype in [torch.float32, torch.float16, torch.bfloat16],
  3136. lambda: f"expected x to be f32/f16/bf16, got {x.dtype}",
  3137. )
  3138. torch._check(
  3139. w.dtype is torch.int32,
  3140. lambda: f"expected w to be int32, got {w.dtype}",
  3141. )
  3142. return x.new_empty(x.size(0), w.size(0) * 8, dtype=x.dtype)
  3143. @register_meta([aten._weight_int4pack_mm_for_cpu])
  3144. def meta__weight_int4pack_mm_for_cpu(x, w, q_group_size, q_scale_and_zeros):
  3145. torch._check(x.dim() == 2, lambda: "x must be a 2D tensor")
  3146. torch._check(w.dim() == 2, lambda: "w must be a 2D tensor")
  3147. torch._check(
  3148. x.dtype in [torch.float32, torch.float16, torch.bfloat16],
  3149. lambda: f"expected x to be f32/f16/bf16, got {x.dtype}",
  3150. )
  3151. torch._check(
  3152. w.dtype is torch.uint8,
  3153. lambda: f"expected w to be uint8, got {w.dtype}",
  3154. )
  3155. return x.new_empty(x.size(0), w.size(0), dtype=x.dtype)
  3156. @register_meta([aten._weight_int4pack_mm_with_scales_and_zeros])
  3157. def _weight_int4pack_mm_with_scales_and_zeros(x, w, q_group_size, qScale, qZeros):
  3158. torch._check(x.dim() == 2, lambda: "x must be a 2D tensor")
  3159. torch._check(w.dim() == 2, lambda: "w must be a 2D tensor")
  3160. torch._check(
  3161. x.dtype in [torch.float32, torch.float16, torch.bfloat16],
  3162. lambda: f"expected x to be f32/f16/bf16, got {x.dtype}",
  3163. )
  3164. torch._check(
  3165. w.dtype is torch.int32,
  3166. lambda: f"expected w to be int32, got {w.dtype}",
  3167. )
  3168. return x.new_empty(x.size(0), w.size(0), dtype=x.dtype)
  3169. def kai_roundup(a: int, b: int) -> int:
  3170. return ((a + b - 1) // b) * b
  3171. def get_kai_packed_weight_size(n_bits, N, K, groupsize):
  3172. if n_bits == 4:
  3173. if groupsize == K: # channelwise
  3174. # dotprod params only [1x8x32_neon_dotprod]
  3175. kai_nr = 8
  3176. kai_kr = 16
  3177. kai_sr = 2
  3178. kai_num_bytes_sum_rhs = 4 # sizeof(int32_t)
  3179. kai_num_bytes_multiplier_rhs = 4 # sizeof(float)
  3180. kai_num_bytes_bias = 4 # sizeof(float)
  3181. def kai_k_roundedup(k, kr, sr):
  3182. # Since we pack a float and int32 value at the end of the row,
  3183. # we must make sure that k is a multiple of 4 for alignment
  3184. kr_sr_roundedup4 = kai_roundup(kr * sr, 4)
  3185. return kai_roundup(k, kr_sr_roundedup4)
  3186. def kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0(
  3187. k, nr, kr, sr
  3188. ):
  3189. k_internal = kai_k_roundedup(k, kr, sr)
  3190. assert (k_internal % 2) == 0, "k_internal must be even"
  3191. return nr * (
  3192. (k_internal // 2)
  3193. + kai_num_bytes_multiplier_rhs
  3194. + kai_num_bytes_sum_rhs
  3195. + kai_num_bytes_bias
  3196. )
  3197. def kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0(
  3198. n, k, nr, kr, sr
  3199. ):
  3200. num_rows = kai_roundup(n, nr) // nr
  3201. return (
  3202. num_rows
  3203. * kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0(
  3204. k, nr, kr, sr
  3205. )
  3206. )
  3207. return kai_get_rhs_packed_size_rhs_pack_nxk_qsi4cxp_qsu4cxs1s0(
  3208. N, K, kai_nr, kai_kr, kai_sr
  3209. )
  3210. elif groupsize % 32 == 0 and K % groupsize == 0: # groupwise
  3211. kai_nr = 8
  3212. kai_kr = 16
  3213. kai_sr = 2
  3214. kai_num_bytes_sum_rhs = 4
  3215. kai_num_bytes_bias = 4
  3216. kai_nr_multiple_of = 4
  3217. kai_bl_multiple_of = 32
  3218. def kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0(
  3219. n, k, nr, kr, sr, bl
  3220. ):
  3221. assert (bl % kr) == 0
  3222. assert (nr % kai_nr_multiple_of) == 0
  3223. assert (bl % kai_bl_multiple_of) == 0
  3224. num_rows = kai_roundup(n, nr) // nr
  3225. return (
  3226. num_rows
  3227. * kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0(
  3228. k, nr, kr, sr, bl
  3229. )
  3230. )
  3231. def kai_get_rhs_packed_stride_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0(
  3232. k, nr, kr, sr, bl
  3233. ):
  3234. assert (bl % kr) == 0
  3235. assert (nr % kai_nr_multiple_of) == 0
  3236. assert (bl % kai_bl_multiple_of) == 0
  3237. # kr and sr are unused in the calculation
  3238. num_bytes_multiplier_rhs = kai_get_bf16_datatype_size_in_bytes()
  3239. num_blocks_per_row = kai_num_blocks_per_row(k, bl)
  3240. num_bytes_per_block = kai_num_bytes_per_block(
  3241. bl, num_bytes_multiplier_rhs
  3242. )
  3243. return nr * (
  3244. (num_bytes_per_block * num_blocks_per_row)
  3245. + kai_num_bytes_sum_rhs
  3246. + kai_num_bytes_bias
  3247. )
  3248. # This function returns size of these datatypes stored as enum. We modify it to just return bf16 datatype
  3249. # https://gitlab.arm.com/kleidi/kleidiai/-/blob/main/kai/kai_common.h?ref_type=heads#L55
  3250. def kai_get_bf16_datatype_size_in_bytes():
  3251. return 2 # 2 bytes
  3252. def kai_num_blocks_per_row(k, bl):
  3253. assert (bl % kai_bl_multiple_of) == 0
  3254. return kai_roundup(k, bl) // bl
  3255. def kai_num_bytes_per_block(bl, num_bytes_multiplier_rhs):
  3256. assert (bl % kai_bl_multiple_of) == 0
  3257. return (bl // 2) + num_bytes_multiplier_rhs
  3258. return kai_get_rhs_packed_size_rhs_pack_nxk_qsi4c32p_qsu4c32s1s0(
  3259. N, K, kai_nr, kai_kr, kai_sr, groupsize
  3260. )
  3261. @register_meta([aten._dyn_quant_pack_4bit_weight])
  3262. def meta__dyn_quant_pack_4bit_weight(
  3263. weights, scales_zeros, bias: Optional[Tensor], block_size, in_features, out_features
  3264. ):
  3265. torch._check(
  3266. weights.dtype is torch.uint8,
  3267. lambda: f"expected w to be uint8, got {weights.dtype}",
  3268. )
  3269. if torch.backends.kleidiai.is_available() and (
  3270. (block_size == in_features and scales_zeros.dtype == torch.float)
  3271. or (
  3272. block_size < in_features
  3273. and block_size % 32 == 0
  3274. and in_features % block_size == 0
  3275. and scales_zeros.dtype == torch.bfloat16
  3276. )
  3277. ):
  3278. packed_weight_size = get_kai_packed_weight_size(
  3279. 4, out_features, in_features, block_size
  3280. )
  3281. return weights.new_empty(int(packed_weight_size), dtype=torch.uint8)
  3282. packed_weight_size = weights.numel() + scales_zeros.numel()
  3283. return weights.new_empty(packed_weight_size, dtype=torch.float)
  3284. @register_meta([aten._dyn_quant_matmul_4bit])
  3285. def meta__dyn_quant_matmul_4bit(
  3286. inp,
  3287. packed_weights,
  3288. block_size,
  3289. in_features,
  3290. out_features,
  3291. ):
  3292. torch._check(inp.dim() == 2, lambda: "input must be a 2D tensor")
  3293. torch._check(
  3294. inp.dtype in [torch.float32],
  3295. lambda: f"expected input to be f32, got {inp.dtype}",
  3296. )
  3297. M = inp.size(0)
  3298. return inp.new_empty(M, out_features, dtype=inp.dtype)
  3299. @register_meta([aten._weight_int8pack_mm])
  3300. def meta__weight_int8pack_mm(x, w, q_scales):
  3301. torch._check(x.dim() == 2, lambda: "x must be a 2D tensor")
  3302. torch._check(
  3303. x.dtype in [torch.float32, torch.float16, torch.bfloat16],
  3304. lambda: f"expected x to be f32/f16/bf16, got {x.dtype}",
  3305. )
  3306. torch._check(w.dim() == 2, lambda: "w must be a 2D tensor")
  3307. torch._check(
  3308. w.dtype is torch.int8,
  3309. lambda: f"expected w to be int8, got {w.dtype}",
  3310. )
  3311. return x.new_empty(x.size(0), w.size(0), dtype=x.dtype)
  3312. @register_meta(aten._cdist_forward.default)
  3313. def meta_cdist_forward(x1, x2, p, compute_mode):
  3314. torch._check(
  3315. x1.dim() >= 2,
  3316. lambda: f"cdist only supports at least 2D tensors, X1 got: {x1.dim()}D",
  3317. )
  3318. torch._check(
  3319. x2.dim() >= 2,
  3320. lambda: f"cdist only supports at least 2D tensors, X2 got: {x2.dim()}D",
  3321. )
  3322. torch._check(
  3323. x1.size(-1) == x2.size(-1),
  3324. lambda: f"X1 and X2 must have the same number of columns. X1: {x1.size(-1)} X2: {x2.size(-1)}",
  3325. )
  3326. torch._check(
  3327. utils.is_float_dtype(x1.dtype),
  3328. lambda: "cdist only supports floating-point dtypes, X1 got: {x1.dtype}",
  3329. )
  3330. torch._check(
  3331. utils.is_float_dtype(x2.dtype),
  3332. lambda: "cdist only supports floating-point dtypes, X2 got: {x2.dtype}",
  3333. )
  3334. torch._check(p >= 0, lambda: "cdist only supports non-negative p values")
  3335. torch._check(
  3336. compute_mode in (None, 1, 2),
  3337. lambda: f"possible modes: None, 1, 2, but was: {compute_mode}",
  3338. )
  3339. r1 = x1.size(-2)
  3340. r2 = x2.size(-2)
  3341. batch_tensor1 = x1.shape[:-2]
  3342. batch_tensor2 = x2.shape[:-2]
  3343. output_shape = list(torch.broadcast_shapes(batch_tensor1, batch_tensor2))
  3344. output_shape.extend([r1, r2])
  3345. return x1.new_empty(output_shape)
  3346. @register_meta(aten._cdist_backward)
  3347. @out_wrapper()
  3348. def meta_cdist_backward(grad, x1, x2, p, cdist):
  3349. c1 = x1.shape[-1]
  3350. r1 = x1.shape[-2]
  3351. r2 = x2.shape[-2]
  3352. batch_tensor1 = x1.shape[:-2]
  3353. batch_tensor2 = x2.shape[:-2]
  3354. expand_batch_portion = list(torch.broadcast_shapes(batch_tensor1, batch_tensor2))
  3355. tensor1_expand_size = expand_batch_portion.copy()
  3356. tensor1_expand_size.extend([r1, c1])
  3357. batch_product = math.prod(expand_batch_portion)
  3358. if r1 == 0 or r2 == 0 or c1 == 0 or batch_product == 0:
  3359. return torch.zeros_like(x1)
  3360. if tensor1_expand_size != list(x1.shape):
  3361. x1 = x1.expand(tensor1_expand_size)
  3362. return torch.empty_like(x1, memory_format=torch.contiguous_format)
  3363. # NB: This meta function accepts non-meta arguments! When this behavior
  3364. # was originally introduced this was accidental, but it is now load bearing
  3365. # as people are using this so that they can conveniently test code involving
  3366. # embeddings (feeding CPU tensor inputs with meta device EmbeddingBag module)
  3367. @register_meta(aten._embedding_bag.default)
  3368. def meta_embedding_bag(
  3369. weight,
  3370. indices,
  3371. offsets,
  3372. scale_grad_by_freq=False,
  3373. mode=0,
  3374. sparse=False,
  3375. per_sample_weights=None,
  3376. include_last_offset=False,
  3377. padding_idx=-1,
  3378. ):
  3379. torch._check(
  3380. indices.dtype in (torch.long, torch.int),
  3381. lambda: f"expected indices to be long or int, got {indices.dtype}",
  3382. )
  3383. torch._check(
  3384. offsets.dtype in (torch.long, torch.int),
  3385. lambda: f"expected offsets to be long or int, got {offsets.dtype}",
  3386. )
  3387. torch._check(
  3388. utils.is_float_dtype(weight.dtype),
  3389. lambda: f"expected weight to be floating point type, got {weight.dtype}",
  3390. )
  3391. num_bags = offsets.size(0)
  3392. if include_last_offset:
  3393. torch._check(
  3394. num_bags >= 1,
  3395. lambda: "include_last_offset: numBags should be at least 1",
  3396. )
  3397. num_bags -= 1
  3398. output = weight.new_empty(num_bags, weight.size(1))
  3399. if per_sample_weights is not None:
  3400. torch._check(
  3401. mode == MODE_SUM,
  3402. lambda: "embedding_bag: per_sample_weights only supported with mode='sum'",
  3403. )
  3404. torch._check(
  3405. per_sample_weights.ndim == 1,
  3406. lambda: f"expected per_sample_weights to be 1D tensor, got {per_sample_weights.ndim}D",
  3407. )
  3408. torch._check(
  3409. per_sample_weights.numel() == indices.numel(),
  3410. lambda: (
  3411. f"expected per_sample_weights.numel() ({per_sample_weights.numel()} "
  3412. f"to be the same as indices.numel() ({indices.numel()})"
  3413. ),
  3414. )
  3415. def is_fast_path_index_select_scale(src, scale, output, padding_idx):
  3416. return (
  3417. is_fast_path_index_select(src, output, padding_idx) and scale.stride(0) == 1
  3418. )
  3419. def is_fast_path_index_select(src, output, padding_idx):
  3420. return (
  3421. (src.dtype == torch.float or src.dtype == torch.half)
  3422. and src.stride(1) == 1
  3423. and output.stride(1) == 1
  3424. and padding_idx < 0
  3425. )
  3426. def is_fast_path(src, scale, output, padding_idx):
  3427. if scale is not None:
  3428. return is_fast_path_index_select_scale(src, scale, output, padding_idx)
  3429. else:
  3430. return is_fast_path_index_select(src, output, padding_idx)
  3431. if device_hint(offsets) != "cpu":
  3432. offset2bag = indices.new_empty(indices.size(0))
  3433. bag_size = indices.new_empty(offsets.size())
  3434. if mode == MODE_MAX:
  3435. max_indices = indices.new_empty(num_bags, weight.size(1))
  3436. else:
  3437. max_indices = indices.new_empty(0)
  3438. else:
  3439. fast_path_sum = is_fast_path(weight, per_sample_weights, output, padding_idx)
  3440. if mode in (MODE_MEAN, MODE_MAX) or not fast_path_sum:
  3441. offset2bag = offsets.new_empty(indices.size(0))
  3442. else:
  3443. offset2bag = offsets.new_empty(0)
  3444. bag_size = offsets.new_empty(num_bags)
  3445. # This part of the logic comes from make_max_indices_out in EmbeddingBag.cpp
  3446. numBags = offsets.shape[0]
  3447. if mode == MODE_MAX:
  3448. if include_last_offset:
  3449. torch._check(
  3450. numBags >= 1,
  3451. lambda: "include_last_offset: numBags should be at least 1",
  3452. )
  3453. numBags -= 1
  3454. max_indices = offsets.new_empty(numBags, weight.shape[1])
  3455. else:
  3456. max_indices = offsets.new_empty(bag_size.size())
  3457. return output, offset2bag, bag_size, max_indices
  3458. @register_meta(aten._embedding_bag_forward_only.default)
  3459. def meta_embedding_bag_forward_only(weight, indices, offsets, *args):
  3460. output, offset2bag, bag_size, max_indices = meta_embedding_bag(
  3461. weight, indices, offsets, *args
  3462. )
  3463. if device_hint(offsets) == "cpu":
  3464. bag_size = offsets.new_empty(offsets.size())
  3465. return output, offset2bag, bag_size, max_indices
  3466. def _get_reduction_dtype(input, dtype, promote_int_to_long=True):
  3467. # if specified, dtype takes precedence
  3468. if dtype:
  3469. return dtype
  3470. if input.dtype.is_floating_point or input.dtype.is_complex:
  3471. return input.dtype
  3472. elif promote_int_to_long:
  3473. return torch.long
  3474. return input.dtype
  3475. @register_meta([aten.nansum.default, aten.nansum.out])
  3476. @out_wrapper()
  3477. def meta_nansum(input, dims=None, keepdim=False, *, dtype=None):
  3478. output_dtype = _get_reduction_dtype(input, dtype, promote_int_to_long=True)
  3479. dims = utils.reduction_dims(input.shape, dims)
  3480. output_shape = _compute_reduction_shape(input, dims, keepdim)
  3481. return input.new_empty(output_shape, dtype=output_dtype)
  3482. @register_meta([aten.median.default, aten.nanmedian.default])
  3483. def meta_median(input):
  3484. output_shape = utils.compute_reduction_output_shape(
  3485. input.shape, tuple(range(input.dim()))
  3486. )
  3487. return input.new_empty(output_shape)
  3488. @register_meta(
  3489. [
  3490. aten.median.dim,
  3491. aten.median.dim_values,
  3492. aten.nanmedian.dim,
  3493. aten.nanmedian.dim_values,
  3494. aten.mode.default,
  3495. aten.mode.values,
  3496. ]
  3497. )
  3498. @out_wrapper("values", "indices")
  3499. def meta_median_mode_dim(input, dim=-1, keepdim=False):
  3500. if device_hint(input) == "cuda":
  3501. utils.alert_not_deterministic("median CUDA with indices output")
  3502. dim = utils.reduction_dims(input.shape, (dim,))
  3503. output_shape = _compute_reduction_shape(input, dim, keepdim)
  3504. return (
  3505. input.new_empty(output_shape),
  3506. input.new_empty(output_shape, dtype=torch.long),
  3507. )
  3508. @register_meta(aten.logical_not_.default)
  3509. def meta_logical_not_(self):
  3510. return self
  3511. @register_meta(aten.repeat.default)
  3512. def meta_repeat(self, repeats):
  3513. torch._check(
  3514. len(repeats) >= self.dim(),
  3515. lambda: "Number of dimensions of repeat dims can not be smaller than number of dimensions of tensor",
  3516. )
  3517. for i, rep in enumerate(repeats):
  3518. torch._check(
  3519. rep >= 0,
  3520. lambda: f"Repeats cannot be negative, found {rep} at index {i}",
  3521. )
  3522. # Add new leading dimensions to the tensor if the
  3523. # number of target dimensions is larger than the
  3524. # number of source dimensions.
  3525. num_new_dimensions = len(repeats) - self.dim()
  3526. padded_size = (1,) * num_new_dimensions + tuple(self.shape)
  3527. target_size = [padded_size[i] * repeats[i] for i in range(len(repeats))]
  3528. return self.new_empty(target_size)
  3529. @register_meta(aten.zero_.default)
  3530. def meta_zero_(self):
  3531. return self
  3532. @register_meta(
  3533. [
  3534. aten.mul_.Scalar,
  3535. aten.div_.Scalar,
  3536. aten.mul_.Tensor,
  3537. aten.div_.Tensor,
  3538. aten.logical_and_.default,
  3539. aten.logical_or_.default,
  3540. aten.logical_xor_.default,
  3541. ],
  3542. )
  3543. def meta_binop_inplace(self, other):
  3544. if isinstance(other, torch.Tensor):
  3545. check_inplace_broadcast(self.shape, other.shape)
  3546. return self
  3547. @register_meta(
  3548. [
  3549. aten.add_.Scalar,
  3550. aten.sub_.Scalar,
  3551. aten.add_.Tensor,
  3552. aten.sub_.Tensor,
  3553. ],
  3554. )
  3555. def meta_binop_inplace_alpha(self, other, alpha=1):
  3556. """
  3557. Some checks for inplace ops.
  3558. Checks for promotion rules for some dtypes.
  3559. int.add/sub_(float) and bool.add/sub_(others) are rejected.
  3560. Promoting in these in-place operations would require reallocating
  3561. and copying over elements, hence not allowed.
  3562. Checks for alpha param.
  3563. """
  3564. def is_integeric(arg):
  3565. if isinstance(arg, TensorLike):
  3566. return utils.is_integer_dtype(arg.dtype)
  3567. else:
  3568. return isinstance(arg, IntLike)
  3569. def is_floatic(arg):
  3570. if isinstance(arg, TensorLike):
  3571. return utils.is_float_dtype(arg.dtype)
  3572. else:
  3573. return isinstance(arg, FloatLike)
  3574. def is_booleanic(arg):
  3575. if isinstance(arg, TensorLike):
  3576. return utils.is_boolean_dtype(arg.dtype)
  3577. else:
  3578. return isinstance(arg, BoolLike)
  3579. # Do not allow int+float->int in-place
  3580. if is_integeric(self) and is_floatic(other):
  3581. raise RuntimeError(
  3582. "Promotion of int.add/sub_(float) in in-place ops are not possible due to element size change."
  3583. )
  3584. # Do not allow bool+other->bool in-place
  3585. if is_booleanic(self) and not is_booleanic(other):
  3586. raise RuntimeError(
  3587. "Promotion of book.add/sub_(others) in in-place ops are not possible due to element size change."
  3588. )
  3589. if isinstance(other, torch.Tensor):
  3590. check_inplace_broadcast(self.shape, other.shape)
  3591. return self
  3592. @register_meta(
  3593. [
  3594. aten.add.Scalar,
  3595. aten.sub.Scalar,
  3596. ],
  3597. )
  3598. def meta_binop_alpha(self, other, alpha=1):
  3599. return elementwise_meta(
  3600. self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
  3601. )
  3602. @register_meta([aten.round.default, aten.round.decimals])
  3603. def meta_round(self, **kwargs):
  3604. return elementwise_meta(
  3605. self, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
  3606. )
  3607. def shift_dtype_check(fn_name, self, val):
  3608. torch._check(
  3609. utils.is_integer_dtype(self.dtype),
  3610. lambda: f"{fn_name}: Expected input tensor to have an integral dtype. Got {self.dtype}",
  3611. )
  3612. if isinstance(val, torch.Tensor):
  3613. torch._check(
  3614. utils.is_integer_dtype(val.dtype),
  3615. lambda: f"{fn_name}: Expected shift value to have an integral dtype. Got {val.dtype}",
  3616. )
  3617. else:
  3618. torch._check(
  3619. isinstance(val, IntLike),
  3620. lambda: f"{fn_name}: Expected shift value to be an int. Got {val}",
  3621. )
  3622. @register_meta([aten.__rshift__.Tensor, aten.__rshift__.Scalar])
  3623. def meta_rshifts(self, other):
  3624. shift_dtype_check("rshift", self, other)
  3625. return elementwise_meta(
  3626. self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
  3627. )
  3628. @register_meta([aten.__lshift__.Tensor, aten.__lshift__.Scalar])
  3629. def meta_lshifts(self, other):
  3630. shift_dtype_check("lshift", self, other)
  3631. return elementwise_meta(
  3632. self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
  3633. )
  3634. @register_meta(aten.zero.default)
  3635. def meta_zero(self):
  3636. return self.new_empty(self.shape)
  3637. @register_meta([aten.fill_.Tensor, aten.fill_.Scalar])
  3638. def meta_fill_(self, val):
  3639. return self
  3640. @register_meta([aten.fill.Tensor, aten.fill.Scalar])
  3641. def meta_fill(self, val):
  3642. return torch.empty_like(self)
  3643. @register_meta(aten.relu_.default)
  3644. def meta_relu_(self):
  3645. return self
  3646. @register_meta(aten._add_relu.Tensor)
  3647. @out_wrapper()
  3648. def meta__add_relu(self, other, alpha=1) -> Tensor:
  3649. return elementwise_meta(
  3650. self, other, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
  3651. )
  3652. @register_meta([aten.rrelu_with_noise])
  3653. @out_wrapper()
  3654. def meta_rrelu_with_noise(
  3655. self, noise, lower=0.125, upper=0.3333333333333333, training=False, generator=None
  3656. ):
  3657. return torch.empty_like(self)
  3658. @register_meta([aten.rrelu_with_noise_functional])
  3659. def meta_rrelu_with_noise_functional(
  3660. self, noise, lower=0.125, upper=0.3333333333333333, training=False, generator=None
  3661. ):
  3662. return torch.empty_like(self), torch.empty_like(noise)
  3663. @register_meta([aten.rrelu_with_noise_])
  3664. def meta_rrelu_with_noise_(
  3665. self, lower=0.125, upper=0.3333333333333333, training=False, generator=None
  3666. ):
  3667. return self
  3668. @register_meta([aten.index_put.default, aten._unsafe_index_put.default])
  3669. def meta_index_put(self, indices, values, accumulate=False):
  3670. return torch.empty_like(self)
  3671. @register_meta(aten.masked_fill_.Scalar)
  3672. def meta_masked_fill_(self, mask, value):
  3673. check_inplace_broadcast(self.shape, mask.shape)
  3674. return self
  3675. @register_meta(aten._masked_scale.default)
  3676. def meta__masked_scale(self, mask, scale):
  3677. masked_scale = self.new_empty(self.size()).to(
  3678. memory_format=utils.suggest_memory_format(self)
  3679. )
  3680. return masked_scale
  3681. @register_meta(aten.masked_scatter_)
  3682. def meta_masked_scatter_(self, mask, source):
  3683. torch._check(
  3684. mask.dtype in (torch.bool, torch.uint8), lambda: "Mask must be bool or uint8"
  3685. )
  3686. torch._check(
  3687. self.dtype == source.dtype,
  3688. lambda: "masked_scatter: expected self and source to have same "
  3689. f"dtypes but got {self.dtype} and {source.dtype}",
  3690. )
  3691. return self
  3692. @register_meta(aten.masked_scatter)
  3693. @out_wrapper()
  3694. def meta_masked_scatter(self, mask, source):
  3695. self, mask = _maybe_broadcast(self, mask)
  3696. output = torch.empty_like(self, memory_format=torch.contiguous_format)
  3697. return meta_masked_scatter_(output, mask, source)
  3698. @register_meta(aten.masked_scatter_backward)
  3699. def meta_masked_scatter_backward(self, mask, sizes):
  3700. return self.new_empty(sizes)
  3701. @register_meta(aten.index_put_.default)
  3702. def meta_index_put_(self, indices, values, accumulate=False):
  3703. return self
  3704. def common_meta_baddbmm_bmm(batch1, batch2, is_bmm, self_baddbmm=None, out_dtype=None):
  3705. torch._check(batch1.dim() == 3, lambda: "batch1 must be a 3D tensor")
  3706. torch._check(batch2.dim() == 3, lambda: "batch2 must be a 3D tensor")
  3707. batch1_sizes = batch1.size()
  3708. batch2_sizes = batch2.size()
  3709. bs = batch1_sizes[0]
  3710. contraction_size = batch1_sizes[2]
  3711. res_rows = batch1_sizes[1]
  3712. res_cols = batch2_sizes[2]
  3713. output_size = (bs, res_rows, res_cols)
  3714. torch._check(
  3715. batch2_sizes[0] == bs and batch2_sizes[1] == contraction_size,
  3716. lambda: f"Expected size for first two dimensions of batch2 tensor to be: [{bs}"
  3717. f", {contraction_size}] but got: [{batch2_sizes[0]}, {batch2_sizes[1]}].",
  3718. )
  3719. if out_dtype:
  3720. supported_out_dtype = (
  3721. batch1.dtype == torch.float16 or batch1.dtype == torch.bfloat16
  3722. ) and out_dtype == torch.float32
  3723. torch._check(
  3724. out_dtype == batch1.dtype or supported_out_dtype,
  3725. lambda: "out_dtype only supported for torch.float32 output with float16/bfloat16 inputs or same as input dtypes",
  3726. )
  3727. output = batch2.new_empty(output_size).to(out_dtype)
  3728. else:
  3729. # TODO: handle out
  3730. output = batch2.new_empty(output_size)
  3731. if not is_bmm and self_baddbmm is not None:
  3732. torch._check(self_baddbmm.dim() == 3, lambda: "self must be a 3D tensor")
  3733. torch._check(
  3734. self_baddbmm.size() == output_size,
  3735. lambda: f"Expected an input tensor shape with shape {output_size} but got shape: {self_baddbmm.size()}",
  3736. )
  3737. return output
  3738. @register_meta(aten.bmm.default)
  3739. def meta_bmm(self, mat2):
  3740. return common_meta_baddbmm_bmm(self, mat2, True)
  3741. @register_meta(aten.bmm.dtype)
  3742. def meta_bmm_dtype(self, mat2, out_dtype):
  3743. return common_meta_baddbmm_bmm(self, mat2, True, out_dtype=out_dtype)
  3744. def div_rtn(x, y):
  3745. q = x // y
  3746. r = x % y
  3747. # WARNING: explicit bool conversion here is necessary;
  3748. # would be fixed by SymBool
  3749. if r != 0 and (bool(r < 0) != bool(y < 0)):
  3750. q -= 1
  3751. return q
  3752. def pooling_output_shape_pad_lr(
  3753. inputSize,
  3754. kernelSize,
  3755. pad_l,
  3756. pad_r,
  3757. stride,
  3758. dilation,
  3759. ceil_mode,
  3760. ):
  3761. outputSize = (
  3762. div_rtn(
  3763. inputSize
  3764. + pad_l
  3765. + pad_r
  3766. - dilation * (kernelSize - 1)
  3767. - 1
  3768. + (stride - 1 if ceil_mode else 0),
  3769. stride,
  3770. )
  3771. + 1
  3772. )
  3773. if ceil_mode:
  3774. if (outputSize - 1) * stride >= inputSize + pad_l:
  3775. outputSize -= 1
  3776. return outputSize
  3777. def pooling_output_shape(inputSize, kernelSize, pad, stride, dilation, ceil_mode):
  3778. torch._check(stride != 0, lambda: "stride should not be zero")
  3779. torch._check(pad >= 0, lambda: f"pad must be non-negative, but got pad: {pad}")
  3780. torch._check(
  3781. pad <= ((kernelSize - 1) * dilation + 1) // 2,
  3782. lambda: (
  3783. f"pad should be at most half of effective kernel size, but got pad={pad}, "
  3784. f"kernel_size={kernelSize} and dilation={dilation}"
  3785. ),
  3786. )
  3787. return pooling_output_shape_pad_lr(
  3788. inputSize, kernelSize, pad, pad, stride, dilation, ceil_mode
  3789. )
  3790. def pool2d_shape_check(
  3791. input,
  3792. kH,
  3793. kW,
  3794. dH,
  3795. dW,
  3796. padH,
  3797. padW,
  3798. dilationH,
  3799. dilationW,
  3800. nInputPlane,
  3801. inputHeight,
  3802. inputWidth,
  3803. outputHeight,
  3804. outputWidth,
  3805. memory_format,
  3806. ):
  3807. ndim = input.dim()
  3808. nOutputPlane = nInputPlane
  3809. torch._check(
  3810. kW > 0 and kH > 0,
  3811. lambda: "kernel size should be greater than zero, but got kH: {kH}, kW: {kW}",
  3812. )
  3813. torch._check(
  3814. dW > 0 and dH > 0,
  3815. lambda: "stride should be greater than zero, but got dH: {dH}, dW: {dW}",
  3816. )
  3817. torch._check(
  3818. dilationH > 0 and dilationW > 0,
  3819. lambda: "dilation should be greater than zero, but got dilationH: {dilationH}, dilationW: {dilationW}",
  3820. )
  3821. valid_dims = input.size(1) != 0 and input.size(2) != 0
  3822. if memory_format == torch.channels_last:
  3823. torch._check(
  3824. ndim == 4 and valid_dims and input.size(3) != 0,
  3825. lambda: "Expected 4D (batch mode) tensor expected for input with channels_last layout"
  3826. " with optional 0 dim batch size for input, but got: {input.size()}",
  3827. )
  3828. else:
  3829. torch._check(
  3830. (ndim == 3 and input.size(0) != 0 and valid_dims)
  3831. or (ndim == 4 and valid_dims and input.size(3) != 0),
  3832. lambda: f"Expected 3D or 4D (batch mode) tensor with optional 0 dim batch size for input, but got: {input.size()}",
  3833. )
  3834. torch._check(
  3835. kW // 2 >= padW and kH // 2 >= padH,
  3836. lambda: "pad should be smaller than or equal to half of kernel size, but got "
  3837. f"padW = {padW}, padH = {padH}, kW = {kW}, kH = {kH}",
  3838. )
  3839. torch._check(
  3840. outputWidth >= 1 and outputHeight >= 1,
  3841. lambda: f"Given input size: ({nInputPlane}x{inputHeight}x{inputWidth}). "
  3842. f"Calculated output size: ({nOutputPlane}x{outputHeight}x{outputWidth}). "
  3843. "Output size is too small",
  3844. )
  3845. def pool3d_shape_check(
  3846. input: Tensor,
  3847. nslices: int,
  3848. kT: int,
  3849. kH: int,
  3850. kW: int,
  3851. dT: int,
  3852. dH: int,
  3853. dW: int,
  3854. pT: int,
  3855. pH: int,
  3856. pW: int,
  3857. dilationT: int,
  3858. dilationH: int,
  3859. dilationW: int,
  3860. itime: int,
  3861. iheight: int,
  3862. iwidth: int,
  3863. otime: int,
  3864. oheight: int,
  3865. owidth: int,
  3866. fn_name: str,
  3867. check_input_size: bool = False,
  3868. ):
  3869. ndim = input.ndim
  3870. torch._check(
  3871. kT > 0 and kW > 0 and kH > 0,
  3872. lambda: (
  3873. f"kernel size should be greater than zero, but got "
  3874. f"kT: {kT}, kH: {kH}, kW: {kW}"
  3875. ),
  3876. )
  3877. torch._check(
  3878. dT > 0 and dW > 0 and dH > 0,
  3879. lambda: (
  3880. f"stride should be greater than zero, but got dT: {dT}, dH: {dH}, dW: {dW}"
  3881. ),
  3882. )
  3883. torch._check(
  3884. dilationT > 0 and dilationW > 0 and dilationH > 0,
  3885. lambda: (
  3886. f"dilation should be greater than zero, but got "
  3887. f"dilationT: {dilationT}, dilationH: {dilationH}, dilationW: {dilationW}"
  3888. ),
  3889. )
  3890. torch._check(
  3891. ndim in (4, 5),
  3892. lambda: f"{fn_name}: Expected 4D or 5D tensor for input, but got: {input.shape}",
  3893. )
  3894. for i in range(ndim):
  3895. if ndim == 5 and i == 0:
  3896. # size of batch-dim can be 0.
  3897. continue
  3898. torch._check(
  3899. input.size(i) > 0,
  3900. lambda: (
  3901. f"{fn_name}: Expected input's non-batch dimensions to have positive length,"
  3902. f" but input has a shape of {input.shape}"
  3903. f" and non-batch dimension {input.size(i)} has length zero!"
  3904. ),
  3905. )
  3906. if check_input_size: # AveragePool3d
  3907. torch._check(
  3908. itime >= kT and iheight >= kH and iwidth >= kW,
  3909. lambda: (
  3910. f"input image (T: {itime} H: {iheight} W: {iwidth}) smaller than "
  3911. f"kernel size (kT: {kT} kH: {kH} kW: {kW})"
  3912. ),
  3913. )
  3914. torch._check(
  3915. kT / 2 >= pT and kW / 2 >= pW and kH / 2 >= pH,
  3916. lambda: (
  3917. f"pad should be smaller than or equal to half of kernel size, but got "
  3918. f"kT: {kT} kW: {kW} kH: {kH} padT: {pT} padW: {pW} padH: {pH}"
  3919. ),
  3920. )
  3921. torch._check(
  3922. otime >= 1 and owidth >= 1 and oheight >= 1,
  3923. lambda: (
  3924. f"Given input size: ({nslices}x{itime}x{iheight}x{iwidth}). "
  3925. f"Calculated output size: ({nslices}x{otime}x{oheight}x{owidth}). "
  3926. f"Output size is too small"
  3927. ),
  3928. )
  3929. def max_pool3d_backward_shape_check(
  3930. input,
  3931. grad_output,
  3932. indices,
  3933. nslices,
  3934. kT,
  3935. kH,
  3936. kW,
  3937. dT,
  3938. dH,
  3939. dW,
  3940. pT,
  3941. pH,
  3942. pW,
  3943. dilationT,
  3944. dilationH,
  3945. dilationW,
  3946. itime,
  3947. iheight,
  3948. iwidth,
  3949. otime,
  3950. oheight,
  3951. owidth,
  3952. fn_name,
  3953. ):
  3954. ndim = input.ndim
  3955. pool3d_shape_check(
  3956. input,
  3957. nslices,
  3958. kT,
  3959. kH,
  3960. kW,
  3961. dT,
  3962. dH,
  3963. dW,
  3964. pT,
  3965. pH,
  3966. pW,
  3967. dilationT,
  3968. dilationH,
  3969. dilationW,
  3970. itime,
  3971. iheight,
  3972. iwidth,
  3973. otime,
  3974. oheight,
  3975. owidth,
  3976. fn_name,
  3977. )
  3978. check_dim_size(grad_output, ndim, ndim - 4, nslices)
  3979. check_dim_size(grad_output, ndim, ndim - 3, otime)
  3980. check_dim_size(grad_output, ndim, ndim - 2, oheight)
  3981. check_dim_size(grad_output, ndim, ndim - 1, owidth)
  3982. check_dim_size(indices, ndim, ndim - 4, nslices)
  3983. check_dim_size(indices, ndim, ndim - 3, otime)
  3984. check_dim_size(indices, ndim, ndim - 2, oheight)
  3985. check_dim_size(indices, ndim, ndim - 1, owidth)
  3986. def avg_pool3d_backward_shape_check(
  3987. input: Tensor,
  3988. grad_output: Tensor,
  3989. nslices: int,
  3990. kT: int,
  3991. kH: int,
  3992. kW: int,
  3993. dT: int,
  3994. dH: int,
  3995. dW: int,
  3996. pT: int,
  3997. pH: int,
  3998. pW: int,
  3999. itime: int,
  4000. iheight: int,
  4001. iwidth: int,
  4002. otime: int,
  4003. oheight: int,
  4004. owidth: int,
  4005. fn_name: str,
  4006. ):
  4007. ndim = input.ndim
  4008. pool3d_shape_check(
  4009. input,
  4010. nslices,
  4011. kT,
  4012. kH,
  4013. kW,
  4014. dT,
  4015. dH,
  4016. dW,
  4017. pT,
  4018. pH,
  4019. pW,
  4020. 1,
  4021. 1,
  4022. 1,
  4023. itime,
  4024. iheight,
  4025. iwidth,
  4026. otime,
  4027. oheight,
  4028. owidth,
  4029. fn_name,
  4030. True,
  4031. )
  4032. check_dim_size(grad_output, ndim, ndim - 4, nslices)
  4033. check_dim_size(grad_output, ndim, ndim - 3, otime)
  4034. check_dim_size(grad_output, ndim, ndim - 2, oheight)
  4035. check_dim_size(grad_output, ndim, ndim - 1, owidth)
  4036. def max_pool2d_checks_and_compute_shape(
  4037. input,
  4038. kernel_size,
  4039. stride,
  4040. padding,
  4041. dilation,
  4042. ceil_mode,
  4043. ):
  4044. # Reference: aten/src/ATen/native/DilatedMaxPool2d.cpp
  4045. def unpack(name, val):
  4046. torch._check(
  4047. len(val) in [1, 2],
  4048. lambda: f"max_pool2d: {name} must either be a single int, or a tuple of two ints",
  4049. )
  4050. H = val[0]
  4051. W = H if len(val) == 1 else val[1]
  4052. return H, W
  4053. kH, kW = unpack("kernel_size", kernel_size)
  4054. torch._check(
  4055. len(stride) in [0, 1, 2],
  4056. lambda: "max_pool2d: stride must either be omitted, a single int, or a tuple of two ints",
  4057. )
  4058. if len(stride) == 0:
  4059. dH, dW = kH, kW
  4060. else:
  4061. dH, dW = unpack("stride", stride)
  4062. padH, padW = unpack("padding", padding)
  4063. dilationH, dilationW = unpack("dilation", dilation)
  4064. nInputPlane = input.size(-3)
  4065. inputHeight = input.size(-2)
  4066. inputWidth = input.size(-1)
  4067. memory_format = utils.suggest_memory_format(input)
  4068. if memory_format == torch.channels_last:
  4069. torch._check(
  4070. input.dim() == 4,
  4071. lambda: "non-empty 4D (batch mode) tensor expected for input with channels_last layout",
  4072. )
  4073. elif memory_format == torch.contiguous_format:
  4074. torch._check(
  4075. input.dim() in [3, 4],
  4076. lambda: "non-empty 3D or 4D (batch mode) tensor expected for input",
  4077. )
  4078. else:
  4079. torch._check(
  4080. False,
  4081. lambda: "Unsupported memory format. Supports only ChannelsLast, Contiguous",
  4082. )
  4083. outputHeight = pooling_output_shape(inputHeight, kH, padH, dH, dilationH, ceil_mode)
  4084. outputWidth = pooling_output_shape(inputWidth, kW, padW, dW, dilationW, ceil_mode)
  4085. pool2d_shape_check(
  4086. input,
  4087. kH,
  4088. kW,
  4089. dH,
  4090. dW,
  4091. padH,
  4092. padW,
  4093. dilationH,
  4094. dilationW,
  4095. nInputPlane,
  4096. inputHeight,
  4097. inputWidth,
  4098. outputHeight,
  4099. outputWidth,
  4100. memory_format,
  4101. )
  4102. return nInputPlane, outputHeight, outputWidth
  4103. @register_meta(aten.max_pool2d_with_indices_backward.default)
  4104. def meta_max_pool2d_with_indices_backward(
  4105. grad_output,
  4106. self,
  4107. kernel_size,
  4108. stride,
  4109. padding,
  4110. dilation,
  4111. ceil_mode,
  4112. indices,
  4113. ):
  4114. (
  4115. nInputPlane,
  4116. outputHeight,
  4117. outputWidth,
  4118. ) = max_pool2d_checks_and_compute_shape(
  4119. self, kernel_size, stride, padding, dilation, ceil_mode
  4120. )
  4121. torch._check(
  4122. self.dtype == grad_output.dtype,
  4123. lambda: f"Expected dtype {self.dtype} for `gradOutput` but got dtype {grad_output.dtype}",
  4124. )
  4125. nOutputPlane = nInputPlane
  4126. ndim = self.ndim
  4127. def _check_dim_size(t):
  4128. check_dim_size(t, ndim, ndim - 3, nOutputPlane)
  4129. check_dim_size(t, ndim, ndim - 2, outputHeight)
  4130. check_dim_size(t, ndim, ndim - 1, outputWidth)
  4131. _check_dim_size(grad_output)
  4132. _check_dim_size(indices)
  4133. memory_format = utils.suggest_memory_format(self)
  4134. return torch.empty(
  4135. self.shape,
  4136. dtype=self.dtype,
  4137. device=self.device,
  4138. memory_format=memory_format,
  4139. )
  4140. @register_meta(aten.max_pool2d_with_indices.default)
  4141. def meta_max_pool2d_with_indices(
  4142. input,
  4143. kernel_size,
  4144. stride=(),
  4145. padding=(0,),
  4146. dilation=(1,),
  4147. ceil_mode=False,
  4148. ):
  4149. (
  4150. nInputPlane,
  4151. outputHeight,
  4152. outputWidth,
  4153. ) = max_pool2d_checks_and_compute_shape(
  4154. input, kernel_size, stride, padding, dilation, ceil_mode
  4155. )
  4156. nbatch = input.size(-4) if input.dim() == 4 else 1
  4157. memory_format = utils.suggest_memory_format(input)
  4158. if input.dim() == 3:
  4159. size = [nInputPlane, outputHeight, outputWidth]
  4160. else:
  4161. size = [nbatch, nInputPlane, outputHeight, outputWidth]
  4162. return (
  4163. torch.empty(
  4164. size,
  4165. dtype=input.dtype,
  4166. device=input.device,
  4167. memory_format=memory_format,
  4168. ),
  4169. torch.empty(
  4170. size,
  4171. dtype=torch.int64,
  4172. device=input.device,
  4173. memory_format=memory_format,
  4174. ),
  4175. )
  4176. @register_meta(aten.fractional_max_pool2d.default)
  4177. def meta_fractional_max_pool2d(self, kernel_size, output_size, random_samples):
  4178. torch._check(
  4179. self.ndim in (3, 4),
  4180. lambda: f"fractional_max_pool2d: Expected 3D or 4D tensor, but got: {self.ndim}",
  4181. )
  4182. ndim = self.ndim
  4183. for d in range(ndim - 3, ndim):
  4184. torch._check(
  4185. self.size(d) > 0,
  4186. f"fractional_max_pool2d: Expected input to have non-zero "
  4187. f" size for non-batch dimensions, but got {self.size()} with dimension {d} empty",
  4188. )
  4189. # the check and message are out of sync, but this matches the structured meta
  4190. torch._check(
  4191. len(kernel_size) == 2,
  4192. lambda: "fractional_max_pool2d: kernel_size must"
  4193. "either be a single int or tuple of Ints",
  4194. )
  4195. torch._check(
  4196. len(output_size) == 2,
  4197. lambda: "fractional_max_pool2d: output_size must "
  4198. "either be a single int or tuple of Ints",
  4199. )
  4200. input_channels = self.size(-3)
  4201. input_height = self.size(-2)
  4202. input_width = self.size(-1)
  4203. if ndim == 4:
  4204. input_batch = self.size(0)
  4205. else:
  4206. input_batch = 1
  4207. torch._check(
  4208. self.dtype == random_samples.dtype,
  4209. lambda: "Expect _random_samples to have the same dtype as input",
  4210. )
  4211. torch._check(
  4212. random_samples.ndim == 3,
  4213. lambda: f"Expect _random samples to have 3 dimensions got, {random_samples.ndim}",
  4214. )
  4215. n = random_samples.size(0)
  4216. c = random_samples.size(1)
  4217. d = random_samples.size(2)
  4218. torch._check(
  4219. n >= input_batch,
  4220. "Expect _random_samples.size(0) no less then input batch size.",
  4221. )
  4222. torch._check(
  4223. c == input_channels,
  4224. lambda: "Expect _random_samples.size(1) equals to input channel size.",
  4225. )
  4226. torch._check(d == 2, lambda: f"Expect _random_samples.size(2) equals to 2 got {d}.")
  4227. torch._check(
  4228. output_size[0] + kernel_size[0] - 1 <= input_height,
  4229. lambda: f"fractional_max_pool2d: kernel height {kernel_size[0]} is too large relative to input height {input_height}",
  4230. )
  4231. torch._check(
  4232. output_size[1] + kernel_size[1] - 1 <= input_width,
  4233. lambda: f"fractional_max_pool2d: kernel width {kernel_size[1]} is too large relative to input width {input_width}",
  4234. )
  4235. if self.dim() == 4:
  4236. size = [input_batch, input_channels, output_size[0], output_size[1]]
  4237. else:
  4238. size = [input_channels, output_size[0], output_size[1]]
  4239. return (
  4240. torch.empty(
  4241. size,
  4242. dtype=self.dtype,
  4243. device=self.device,
  4244. ),
  4245. torch.empty(
  4246. size,
  4247. dtype=torch.int64,
  4248. device=self.device,
  4249. ),
  4250. )
  4251. @register_meta(aten.max_pool3d_with_indices)
  4252. @out_wrapper("out", "indices")
  4253. def meta_max_pool3d_with_indices(
  4254. input,
  4255. kernel_size,
  4256. stride=(),
  4257. padding=(0,),
  4258. dilation=(1,),
  4259. ceil_mode=False,
  4260. ):
  4261. torch._check(
  4262. len(kernel_size) in (1, 3),
  4263. lambda: "max_pool3d: kernel_size must either be a single int, or a tuple of three ints",
  4264. )
  4265. kT = kernel_size[0]
  4266. kH = kT if len(kernel_size) == 1 else kernel_size[1]
  4267. kW = kT if len(kernel_size) == 1 else kernel_size[2]
  4268. torch._check(
  4269. not stride or len(stride) in (1, 3),
  4270. lambda: "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints",
  4271. )
  4272. dT = kT if not stride else stride[0]
  4273. dH = kH if not stride else (dT if len(stride) == 1 else stride[1])
  4274. dW = kW if not stride else (dT if len(stride) == 1 else stride[2])
  4275. torch._check(
  4276. len(padding) in (1, 3),
  4277. lambda: "max_pool3d: padding must either be a single int, or a tuple of three ints",
  4278. )
  4279. pT = padding[0]
  4280. pH = pT if len(padding) == 1 else padding[1]
  4281. pW = pT if len(padding) == 1 else padding[2]
  4282. torch._check(
  4283. len(dilation) in (1, 3),
  4284. lambda: "max_pool3d: dilation must be either a single int, or a tuple of three ints",
  4285. )
  4286. dilationT = dilation[0]
  4287. dilationH = dilationT if len(dilation) == 1 else dilation[1]
  4288. dilationW = dilationT if len(dilation) == 1 else dilation[2]
  4289. torch._check(
  4290. input.ndim in (4, 5),
  4291. lambda: "non-empty 4D or 5D (batch mode) tensor expected for input",
  4292. )
  4293. nbatch = input.size(-5) if input.ndim == 5 else 1
  4294. nslices = input.size(-4)
  4295. itime = input.size(-3)
  4296. iheight = input.size(-2)
  4297. iwidth = input.size(-1)
  4298. otime = pooling_output_shape(itime, kT, pT, dT, dilationT, ceil_mode)
  4299. oheight = pooling_output_shape(iheight, kH, pH, dH, dilationH, ceil_mode)
  4300. owidth = pooling_output_shape(iwidth, kW, pW, dW, dilationW, ceil_mode)
  4301. pool3d_shape_check(
  4302. input,
  4303. nslices,
  4304. kT,
  4305. kH,
  4306. kW,
  4307. dT,
  4308. dH,
  4309. dW,
  4310. pT,
  4311. pH,
  4312. pW,
  4313. dilationT,
  4314. dilationH,
  4315. dilationW,
  4316. itime,
  4317. iheight,
  4318. iwidth,
  4319. otime,
  4320. oheight,
  4321. owidth,
  4322. "max_pool3d_with_indices()",
  4323. )
  4324. channels_last = (
  4325. input.ndim == 5 and utils.suggest_memory_format(input) == torch.channels_last_3d
  4326. )
  4327. if input.ndim == 4:
  4328. input_channels_last_check = input.unsqueeze(0)
  4329. channels_last = (
  4330. not input_channels_last_check.is_contiguous()
  4331. ) and input_channels_last_check.is_contiguous(
  4332. memory_format=torch.channels_last_3d
  4333. )
  4334. out_shape = (nslices, otime, oheight, owidth)
  4335. else:
  4336. out_shape = (nbatch, nslices, otime, oheight, owidth) # type: ignore[assignment]
  4337. out = input.new_empty(out_shape)
  4338. indices = input.new_empty(out_shape, dtype=torch.int64)
  4339. if channels_last:
  4340. out = out.to(memory_format=torch.channels_last_3d)
  4341. indices = indices.to(memory_format=torch.channels_last_3d)
  4342. return out, indices
  4343. @register_meta(aten.max_pool3d_with_indices_backward)
  4344. @out_wrapper("grad_input")
  4345. def meta_max_pool3d_with_indices_backward(
  4346. grad_output,
  4347. input,
  4348. kernel_size,
  4349. stride,
  4350. padding,
  4351. dilation,
  4352. ceil_mode,
  4353. indices,
  4354. ):
  4355. torch._check(
  4356. len(kernel_size) in (1, 3),
  4357. lambda: "max_pool3d: kernel_size must either be a single int, or a tuple of three ints",
  4358. )
  4359. kT = kernel_size[0]
  4360. kH = kT if len(kernel_size) == 1 else kernel_size[1]
  4361. kW = kT if len(kernel_size) == 1 else kernel_size[2]
  4362. torch._check(
  4363. not stride or len(stride) in (1, 3),
  4364. lambda: "max_pool3d: stride must either be omitted, a single int, or a tuple of three ints",
  4365. )
  4366. dT = kT if not stride else stride[0]
  4367. dH = kH if not stride else (dT if len(stride) == 1 else stride[1])
  4368. dW = kW if not stride else (dT if len(stride) == 1 else stride[2])
  4369. torch._check(
  4370. len(padding) in (1, 3),
  4371. lambda: "max_pool3d: padding must either be a single int, or a tuple of three ints",
  4372. )
  4373. pT = padding[0]
  4374. pH = pT if len(padding) == 1 else padding[1]
  4375. pW = pT if len(padding) == 1 else padding[2]
  4376. torch._check(
  4377. len(dilation) in (1, 3),
  4378. lambda: "max_pool3d: dilation must be either a single int, or a tuple of three ints",
  4379. )
  4380. dilationT = dilation[0]
  4381. dilationH = dilationT if len(dilation) == 1 else dilation[1]
  4382. dilationW = dilationT if len(dilation) == 1 else dilation[2]
  4383. torch._check(
  4384. input.ndim in (4, 5),
  4385. lambda: "non-empty 4D or 5D (batch mode) tensor expected for input",
  4386. )
  4387. nslices = input.size(-4)
  4388. itime = input.size(-3)
  4389. iheight = input.size(-2)
  4390. iwidth = input.size(-1)
  4391. otime = grad_output.size(-3)
  4392. oheight = grad_output.size(-2)
  4393. owidth = grad_output.size(-1)
  4394. max_pool3d_backward_shape_check(
  4395. input,
  4396. grad_output,
  4397. indices,
  4398. nslices,
  4399. kT,
  4400. kH,
  4401. kW,
  4402. dT,
  4403. dH,
  4404. dW,
  4405. pT,
  4406. pH,
  4407. pW,
  4408. dilationT,
  4409. dilationH,
  4410. dilationW,
  4411. itime,
  4412. iheight,
  4413. iwidth,
  4414. otime,
  4415. oheight,
  4416. owidth,
  4417. "max_pool3d_with_indices_backward()",
  4418. )
  4419. channels_last = (
  4420. input.ndim == 5 and utils.suggest_memory_format(input) == torch.channels_last_3d
  4421. )
  4422. if input.ndim == 4:
  4423. input_channels_last_check = input.unsqueeze(0)
  4424. channels_last = (
  4425. not input_channels_last_check.is_contiguous()
  4426. ) and input_channels_last_check.is_contiguous(
  4427. memory_format=torch.channels_last_3d
  4428. )
  4429. grad_input = input.new_empty(input.shape)
  4430. if channels_last:
  4431. grad_input = grad_input.to(memory_format=torch.channels_last_3d)
  4432. return grad_input
  4433. def check_grid_sampler_common(input: Tensor, grid: Tensor):
  4434. torch._check(
  4435. input.device == grid.device,
  4436. lambda: (
  4437. f"grid_sampler(): expected input and grid to be on same device, but input "
  4438. f"is on {input.device} and grid is on {grid.device}"
  4439. ),
  4440. )
  4441. torch._check(
  4442. input.layout == torch.strided and grid.layout == torch.strided,
  4443. lambda: (
  4444. f"grid_sampler(): expected input and grid to have torch.strided layout, but "
  4445. f"input has {input.layout} and grid has {grid.layout}"
  4446. ),
  4447. )
  4448. torch._check(
  4449. input.shape[0] == grid.shape[0],
  4450. lambda: (
  4451. f"grid_sampler(): expected grid and input to have same batch size, but got "
  4452. f"input with sizes {input.shape} and grid with sizes {grid.shape}"
  4453. ),
  4454. )
  4455. torch._check(
  4456. grid.shape[-1] == input.ndim - 2,
  4457. lambda: (
  4458. f"grid_sampler(): expected grid to have size {input.ndim - 2} in last "
  4459. f"dimension, but got grid with sizes {grid.shape}"
  4460. ),
  4461. )
  4462. for i in range(2, input.ndim):
  4463. torch._check(
  4464. input.shape[i] > 0,
  4465. lambda: (
  4466. f"grid_sampler(): expected input to have non-empty spatial dimensions, "
  4467. f"but input has sizes {input.shape} with dimension {i} being empty"
  4468. ),
  4469. )
  4470. class GridSamplerInterpolation(Enum):
  4471. BILINEAR = 0
  4472. NEAREST = 1
  4473. BICUBIC = 2
  4474. def check_grid_sampler_3d(input: Tensor, grid: Tensor, interpolation_mode: int):
  4475. torch._check(
  4476. input.ndim == 5 and input.ndim == grid.ndim,
  4477. lambda: (
  4478. f"grid_sampler(): expected 5D input and grid with same number of "
  4479. f"dimensions, but got input with sizes {input.shape}"
  4480. f" and grid with sizes {grid.shape}"
  4481. ),
  4482. )
  4483. torch._check(
  4484. not (
  4485. input.ndim == 5
  4486. and interpolation_mode == GridSamplerInterpolation.BICUBIC.value
  4487. ),
  4488. lambda: "grid_sampler(): bicubic interpolation only supports 4D input",
  4489. )
  4490. @register_meta(aten.grid_sampler_2d_backward.default)
  4491. def grid_sampler_2d_backward_meta(
  4492. grad_output,
  4493. input,
  4494. grid,
  4495. interpolation_mode,
  4496. padding_mode,
  4497. align_corners,
  4498. output_mask,
  4499. ):
  4500. input_requires_grad = output_mask[0]
  4501. if input_requires_grad:
  4502. grad_input = torch.zeros_like(input, memory_format=torch.contiguous_format)
  4503. else:
  4504. grad_input = None
  4505. grad_grid = torch.empty_like(grid, memory_format=torch.contiguous_format)
  4506. return (grad_input, grad_grid)
  4507. @register_meta(aten.grid_sampler_3d)
  4508. @out_wrapper()
  4509. def grid_sampler_3d(
  4510. input,
  4511. grid,
  4512. interpolation_mode,
  4513. padding_mode,
  4514. align_corners,
  4515. ):
  4516. check_grid_sampler_common(input, grid)
  4517. check_grid_sampler_3d(input, grid, interpolation_mode)
  4518. N = input.shape[0]
  4519. C = input.shape[1]
  4520. out_D = grid.shape[1]
  4521. out_H = grid.shape[2]
  4522. out_W = grid.shape[3]
  4523. return input.new_empty((N, C, out_D, out_H, out_W))
  4524. @register_meta(aten.grid_sampler_3d_backward)
  4525. @out_wrapper("grad_input", "grad_grid")
  4526. def grid_sampler_3d_backward(
  4527. grad_output,
  4528. input,
  4529. grid,
  4530. interpolation_mode,
  4531. padding_mode,
  4532. align_corners,
  4533. output_mask,
  4534. ):
  4535. check_grid_sampler_common(input, grid)
  4536. check_grid_sampler_3d(input, grid, interpolation_mode)
  4537. input_requires_grad = output_mask[0]
  4538. if input_requires_grad:
  4539. grad_input = torch.zeros_like(
  4540. input, memory_format=torch.legacy_contiguous_format
  4541. )
  4542. else:
  4543. grad_input = None
  4544. grad_grid = torch.empty_like(grid, memory_format=torch.legacy_contiguous_format)
  4545. return grad_input, grad_grid
  4546. @register_meta([aten.full.default])
  4547. def full(size, fill_value, *args, **kwargs):
  4548. dtype = kwargs.get("dtype", None)
  4549. if not dtype:
  4550. dtype = utils.get_dtype(fill_value)
  4551. kwargs["dtype"] = dtype
  4552. return torch.empty(size, *args, **kwargs)
  4553. # zeros_like is special cased to work for sparse
  4554. @register_meta(aten.zeros_like.default)
  4555. def zeros_like(
  4556. self,
  4557. dtype=None,
  4558. layout=None,
  4559. device=None,
  4560. pin_memory=None,
  4561. memory_format=None,
  4562. ):
  4563. if layout == torch.sparse_coo:
  4564. torch._check(
  4565. memory_format is None,
  4566. lambda: "memory format option is only supported by strided tensors",
  4567. )
  4568. res = torch.empty(
  4569. 0,
  4570. dtype=self.dtype if dtype is None else dtype,
  4571. layout=layout,
  4572. device=self.device if device is None else device,
  4573. pin_memory=pin_memory,
  4574. )
  4575. if self.is_sparse:
  4576. res.sparse_resize_and_clear_(
  4577. self.size(), self.sparse_dim(), self.dense_dim()
  4578. )
  4579. else:
  4580. res.sparse_resize_and_clear_(self.size(), self.dim(), 0)
  4581. res._coalesced_(True)
  4582. return res
  4583. res = aten.empty_like.default(
  4584. self,
  4585. dtype=dtype,
  4586. layout=layout,
  4587. device=device,
  4588. pin_memory=pin_memory,
  4589. memory_format=memory_format,
  4590. )
  4591. # device can be not "meta"
  4592. res.fill_(0)
  4593. return res
  4594. @register_meta([aten.ones.default, aten.ones.out])
  4595. @out_wrapper()
  4596. def meta_ones(
  4597. size,
  4598. *,
  4599. dtype=None,
  4600. layout=None,
  4601. device=None,
  4602. pin_memory=None,
  4603. requires_grad=False,
  4604. ):
  4605. if dtype is None:
  4606. dtype = torch.get_default_dtype()
  4607. if device is None:
  4608. device = torch.get_default_device()
  4609. if layout is None:
  4610. layout = torch.strided
  4611. return torch.empty(
  4612. size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
  4613. )
  4614. @register_meta([aten.zeros.default, aten.zeros.out])
  4615. @out_wrapper()
  4616. def meta_zeros(
  4617. size,
  4618. *,
  4619. dtype=None,
  4620. layout=None,
  4621. device=None,
  4622. pin_memory=None,
  4623. requires_grad=False,
  4624. ):
  4625. if dtype is None:
  4626. dtype = torch.get_default_dtype()
  4627. if device is None:
  4628. device = torch.get_default_device()
  4629. if layout is None:
  4630. layout = torch.strided
  4631. return torch.empty(
  4632. size, dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
  4633. )
  4634. @register_meta(aten.select_scatter.default)
  4635. def meta_select_scatter(self, src, dim, index):
  4636. return utils.clone_preserve_strides(self)
  4637. @register_meta(aten.slice_scatter.default)
  4638. def meta_slice_scatter(self, src, dim=0, start=None, end=None, step=1):
  4639. return utils.clone_preserve_strides(self)
  4640. # TODO: Deduplicate this with canonicalize_dim
  4641. def maybe_wrap_dim(dim: int, dim_post_expr: int, wrap_scalar: bool = True):
  4642. if dim_post_expr <= 0:
  4643. assert wrap_scalar
  4644. dim_post_expr = 1
  4645. min = -dim_post_expr
  4646. max = dim_post_expr - 1
  4647. assert not (dim < min or dim > max), f"dim {dim} out of bounds ({min}, {max})"
  4648. if dim < 0:
  4649. dim += dim_post_expr
  4650. return dim
  4651. def ensure_nonempty_size(t, dim):
  4652. return 1 if t.dim() == 0 else t.shape[dim]
  4653. # From aten/src/ATen/native/ScatterGatherChecks.h
  4654. def gather_shape_check(self, dim, index):
  4655. self_dims = max(self.dim(), 1)
  4656. index_dims = max(index.dim(), 1)
  4657. torch._check(
  4658. self_dims == index_dims,
  4659. lambda: "Index tensor must have the same number of dimensions as input tensor",
  4660. )
  4661. for i in range(self_dims):
  4662. if i != dim:
  4663. torch._check(
  4664. ensure_nonempty_size(index, i) <= ensure_nonempty_size(self, i),
  4665. lambda: f"Size does not match at dimension {i} expected index {index.shape}"
  4666. + f" to be no larger than self {self.shape} apart from dimension {dim}",
  4667. )
  4668. @register_meta(aten.gather.default)
  4669. def meta_gather(self, dim, index, sparse_grad=False):
  4670. from torch.fx.experimental.symbolic_shapes import guard_or_false
  4671. wrapped_dim = maybe_wrap_dim(dim, self.dim())
  4672. is_index_empty = guard_or_false(index.numel() == 0)
  4673. if not is_index_empty:
  4674. torch._check(
  4675. index.dtype == torch.long or index.dtype == torch.int,
  4676. lambda: f"gather(): Expected dtype int32/int64 for index, but got {index.dtype}",
  4677. )
  4678. gather_shape_check(self, wrapped_dim, index)
  4679. return self.new_empty(index.shape)
  4680. # From aten/src/ATen/native/TensorAdvancedIndexing.cpp
  4681. def get_operator_enum(reduce_, use_new_options=False):
  4682. if use_new_options:
  4683. if reduce_ == "sum":
  4684. return "REDUCE_ADD"
  4685. elif reduce_ == "prod":
  4686. return "REDUCE_MULTIPLY"
  4687. elif reduce_ == "mean":
  4688. return "REDUCE_MEAN"
  4689. elif reduce_ == "amax":
  4690. return "REDUCE_MAXIMUM"
  4691. elif reduce_ == "amin":
  4692. return "REDUCE_MINIMUM"
  4693. torch._check(
  4694. False,
  4695. lambda: "reduce argument must be either sum, prod, mean, amax or amin.",
  4696. )
  4697. return
  4698. else:
  4699. if reduce_ == "add":
  4700. return "REDUCE_ADD"
  4701. elif reduce_ == "multiply":
  4702. return "REDUCE_MULTIPLY"
  4703. torch._check(False, lambda: "reduce argument must be either add or multiply.")
  4704. return
  4705. # From aten/src/ATen/native/ScatterGatherChecks.h
  4706. def scatter_gather_dtype_check(method_name, self, index, src_opt=None):
  4707. from torch.fx.experimental.symbolic_shapes import guard_or_true
  4708. if guard_or_true(index.numel() != 0):
  4709. torch._check(
  4710. index.dtype == torch.long or index.dtype == torch.int,
  4711. lambda: f"{method_name}(): Expected dtype int32/int64 for index",
  4712. )
  4713. if src_opt is not None:
  4714. torch._check(
  4715. self.dtype == src_opt.dtype,
  4716. lambda: f"{method_name}(): Expected self.dtype to be equal to src.dtype",
  4717. )
  4718. def ensure_nonempty_dim(dim):
  4719. return max(dim, 1)
  4720. # From aten/src/ATen/native/ScatterGatherChecks.h
  4721. def scatter_shape_check(self, dim, index, src_opt=None):
  4722. from torch.fx.experimental.symbolic_shapes import guard_or_false
  4723. if guard_or_false(index.numel() == 0):
  4724. return
  4725. torch._check(
  4726. ensure_nonempty_dim(self.dim()) == ensure_nonempty_dim(index.dim()),
  4727. lambda: "Index tensor must have the same number of dimensions as self tensor",
  4728. )
  4729. is_wrong_shape = False
  4730. self_dims = ensure_nonempty_dim(self.dim())
  4731. # Check: index.size(d) <= self.size(d) for all d != dim
  4732. for d in range(self_dims):
  4733. index_d_size = ensure_nonempty_size(index, d)
  4734. if d == dim:
  4735. continue
  4736. if index_d_size > ensure_nonempty_size(self, d):
  4737. is_wrong_shape = True
  4738. break
  4739. # Check: index.size(d) <= src.size(d) for all d if src is Tensor
  4740. if not is_wrong_shape and src_opt is not None:
  4741. for d in range(self_dims):
  4742. index_d_size = ensure_nonempty_size(index, d)
  4743. if index_d_size > ensure_nonempty_size(src_opt, d):
  4744. is_wrong_shape = True
  4745. break
  4746. if src_opt is not None:
  4747. torch._check(
  4748. ensure_nonempty_dim(self.dim()) == ensure_nonempty_dim(index.dim()),
  4749. lambda: "Index tensor must have the same number of dimensions as self tensor",
  4750. )
  4751. torch._check(
  4752. not is_wrong_shape,
  4753. lambda: f"Expected index {index.shape} to be no larger than self {self.shape}"
  4754. + f" apart from dimension {dim} and to be no larger than src {src_opt.shape}",
  4755. )
  4756. else:
  4757. torch._check(
  4758. not is_wrong_shape,
  4759. lambda: f"Expected index {index.shape} to be no larger than self {self.shape}"
  4760. + f" apart from dimension {dim}",
  4761. )
  4762. # From aten/src/ATen/native/TensorAdvancedIndexing.cpp
  4763. def scatter_meta_impl(self, dim, index, src=None, reduce_=None, use_new_options=False):
  4764. wrapped_dim = maybe_wrap_dim(dim, self.dim())
  4765. scatter_gather_dtype_check("scatter", self, index, src)
  4766. scatter_shape_check(self, wrapped_dim, index, src)
  4767. if reduce_ is not None:
  4768. # Check if we have a valid reduce operator.
  4769. get_operator_enum(reduce_, use_new_options)
  4770. @register_meta(aten.scatter_add.default)
  4771. def meta_scatter_add(self, dim, index, src):
  4772. scatter_meta_impl(self, dim, index, src, "add")
  4773. return self.new_empty(self.shape)
  4774. @register_meta(aten.scatter_add_)
  4775. def meta_scatter_add_(self, dim, index, src):
  4776. scatter_meta_impl(self, dim, index, src, "add")
  4777. return self
  4778. @register_meta(
  4779. [
  4780. aten.scatter.src,
  4781. aten.scatter.value,
  4782. aten.scatter.reduce,
  4783. aten.scatter.value_reduce,
  4784. ]
  4785. )
  4786. @out_wrapper()
  4787. def meta_scatter(self, dim, index, src_or_value, reduce=None):
  4788. src = src_or_value if isinstance(src_or_value, torch.Tensor) else None
  4789. scatter_meta_impl(self, dim, index, src, reduce)
  4790. return self.new_empty(self.shape)
  4791. @register_meta(
  4792. [
  4793. aten.scatter_.src,
  4794. aten.scatter_.value,
  4795. aten.scatter_.reduce,
  4796. aten.scatter_.value_reduce,
  4797. ]
  4798. )
  4799. def meta_scatter_(self, dim, index, src_or_value, reduce=None):
  4800. src = src_or_value if isinstance(src_or_value, torch.Tensor) else None
  4801. scatter_meta_impl(self, dim, index, src, reduce)
  4802. return self
  4803. @register_meta([aten._scaled_dot_product_flash_attention])
  4804. def meta__scaled_dot_product_flash_attention(
  4805. query: Tensor,
  4806. key: Tensor,
  4807. value: Tensor,
  4808. dropout_p: float = 0.0,
  4809. is_causal: bool = False,
  4810. return_debug_mask: bool = False,
  4811. scale: Optional[float] = None,
  4812. ):
  4813. batch_size = query.size(0)
  4814. num_heads = query.size(1)
  4815. max_seqlen_batch_q = query.size(2)
  4816. head_dim = query.size(3)
  4817. max_seqlen_batch_k = key.size(2)
  4818. query_t = query.transpose(1, 2)
  4819. attention = torch.empty_like(query_t).transpose(1, 2)
  4820. logsumexp = torch.empty(
  4821. (batch_size, num_heads, max_seqlen_batch_q),
  4822. dtype=torch.float,
  4823. device=query.device,
  4824. )
  4825. if return_debug_mask:
  4826. blocksize_c = 128 if head_dim > 64 else 256
  4827. max_seqlen_k = math.ceil(max_seqlen_batch_q / blocksize_c)
  4828. if max_seqlen_batch_k <= 128:
  4829. max_seqlen_k = 128
  4830. elif max_seqlen_batch_k <= 256:
  4831. max_seqlen_k = 256
  4832. debug_mask = torch.empty(
  4833. (batch_size, num_heads, max_seqlen_batch_q, max_seqlen_k),
  4834. dtype=query.dtype,
  4835. device=query.device,
  4836. )
  4837. else:
  4838. debug_mask = torch.empty(0, dtype=query.dtype, device=query.device)
  4839. # Note [Seed and Offset]: device for seed and offset below depends on whether we are
  4840. # capturing or not, but at the time of tracing we don't know if we
  4841. # are going to use cudagraphs or not, so we return meta tensors here
  4842. # it's possible we'll need to have some special handling in inductor for sdpa
  4843. # See [Note] BC breaking change to flash seed/offset
  4844. if torch.version.hip and torch.cuda.is_available():
  4845. # Maintain old path on AMD
  4846. seed = torch.empty((), dtype=torch.long, device="meta")
  4847. offset = torch.empty((), dtype=torch.long, device="meta")
  4848. else:
  4849. seed = torch.empty((2), dtype=torch.uint64, device="meta")
  4850. offset = torch.empty((), dtype=torch.uint64, device="meta")
  4851. return (
  4852. attention,
  4853. logsumexp,
  4854. None,
  4855. None,
  4856. max_seqlen_batch_q,
  4857. max_seqlen_batch_k,
  4858. seed,
  4859. offset,
  4860. debug_mask,
  4861. )
  4862. def alloc_with_matching_layout(
  4863. query: Tensor,
  4864. res_shape: tuple[int, ...],
  4865. ):
  4866. if tuple(query.shape) == res_shape:
  4867. query_t = query.transpose(1, 2)
  4868. res = torch.empty_like(query_t).transpose(1, 2)
  4869. else:
  4870. dim_order = sorted(
  4871. [0, 1, 2, 3], key=lambda idx: query.stride()[idx], reverse=True
  4872. )
  4873. permuted_shape = [res_shape[idx] for idx in dim_order]
  4874. final_permute = [dim_order.index(i) for i in range(len(dim_order))]
  4875. res = torch.empty(
  4876. permuted_shape, dtype=query.dtype, device=query.device
  4877. ).permute(final_permute)
  4878. return res
  4879. @register_meta([aten._scaled_dot_product_cudnn_attention])
  4880. def meta__scaled_dot_product_cudnn_attention(
  4881. query: Tensor,
  4882. key: Tensor,
  4883. value: Tensor,
  4884. attn_bias: Optional[Tensor],
  4885. compute_log_sumexp: bool,
  4886. dropout_p: float = 0.0,
  4887. is_causal: bool = False,
  4888. return_debug_mask: bool = False,
  4889. scale: Optional[float] = None,
  4890. ):
  4891. B = query.size(0)
  4892. H = query.size(1)
  4893. S_Q = query.size(2)
  4894. S_KV = key.size(2)
  4895. D_V = value.size(-1)
  4896. res_shape = (B, H, S_Q, D_V)
  4897. res = alloc_with_matching_layout(query, res_shape)
  4898. logsum_exp = torch.empty(
  4899. (B, H, S_Q, 1),
  4900. dtype=torch.float,
  4901. device=query.device,
  4902. )
  4903. # See Note [Seed and Offset]
  4904. seed = torch.empty((), dtype=torch.long, device="meta")
  4905. offset = torch.empty((), dtype=torch.long, device="meta")
  4906. return (
  4907. res,
  4908. logsum_exp,
  4909. None,
  4910. None,
  4911. S_Q,
  4912. S_KV,
  4913. seed,
  4914. offset,
  4915. None,
  4916. )
  4917. @register_meta([aten._scaled_dot_product_fused_attention_overrideable])
  4918. def meta__scaled_dot_product_fused_attention_overrideable(
  4919. query: Tensor,
  4920. key: Tensor,
  4921. value: Tensor,
  4922. attn_bias: Optional[Tensor] = None,
  4923. dropout_p: float = 0.0,
  4924. is_causal: bool = False,
  4925. return_debug_mask: bool = False,
  4926. scale: Optional[float] = None,
  4927. ):
  4928. B = query.size(0)
  4929. H_Q = query.size(1)
  4930. S_Q = query.size(2)
  4931. S_KV = key.size(2)
  4932. D_V = value.size(-1)
  4933. res_shape = (B, H_Q, S_Q, D_V)
  4934. res = alloc_with_matching_layout(query, res_shape)
  4935. logsum_exp = torch.empty(
  4936. (B, H_Q, S_Q),
  4937. dtype=torch.float,
  4938. device=query.device,
  4939. )
  4940. # See Note [Seed and Offset]
  4941. seed = torch.empty((), dtype=torch.long, device="meta")
  4942. offset = torch.empty((), dtype=torch.long, device="meta")
  4943. return (
  4944. res,
  4945. logsum_exp,
  4946. None,
  4947. None,
  4948. S_Q,
  4949. S_KV,
  4950. seed,
  4951. offset,
  4952. None,
  4953. )
  4954. @register_meta(
  4955. [
  4956. aten._scaled_dot_product_flash_attention_backward,
  4957. ]
  4958. )
  4959. def meta__scaled_dot_product_flash_backward(
  4960. grad_out: Tensor,
  4961. query: Tensor,
  4962. key: Tensor,
  4963. value: Tensor,
  4964. out: Tensor,
  4965. logsumexp: Tensor,
  4966. cum_seq_q: Tensor,
  4967. cum_seq_k: Tensor,
  4968. max_q: int,
  4969. max_k: int,
  4970. dropout_p: float,
  4971. is_causal: bool,
  4972. philox_seed: Tensor,
  4973. philox_offset: Tensor,
  4974. scale: Optional[float] = None,
  4975. ):
  4976. grad_q = torch.empty_like(query.transpose(1, 2)).transpose(1, 2)
  4977. grad_k = torch.empty_like(key.transpose(1, 2)).transpose(1, 2)
  4978. grad_v = torch.empty_like(value.transpose(1, 2)).transpose(1, 2)
  4979. return grad_q, grad_k, grad_v
  4980. @register_meta(
  4981. [
  4982. aten._scaled_dot_product_flash_attention_for_cpu,
  4983. ]
  4984. )
  4985. def meta__scaled_dot_product_flash_attention_for_cpu(
  4986. query: Tensor,
  4987. key: Tensor,
  4988. value: Tensor,
  4989. dropout_p: float = 0.0,
  4990. is_causal: bool = False,
  4991. attn_mask: Optional[Tensor] = None,
  4992. scale: Optional[float] = None,
  4993. ):
  4994. batch_size = query.size(0)
  4995. num_heads = query.size(1)
  4996. max_seqlen_batch_q = query.size(2)
  4997. attention = torch.empty_like(query)
  4998. logsumexp = torch.empty(
  4999. (
  5000. batch_size,
  5001. max_seqlen_batch_q,
  5002. num_heads,
  5003. ),
  5004. dtype=torch.float,
  5005. device=query.device,
  5006. ).transpose(1, 2)
  5007. return (
  5008. attention,
  5009. logsumexp,
  5010. )
  5011. @register_meta(
  5012. [
  5013. aten._scaled_dot_product_flash_attention_for_cpu_backward,
  5014. ]
  5015. )
  5016. def meta__scaled_dot_product_flash_attention_for_cpu_backward(
  5017. grad_out: Tensor,
  5018. query: Tensor,
  5019. key: Tensor,
  5020. value: Tensor,
  5021. out: Tensor,
  5022. logsumexp: Tensor,
  5023. dropout_p: float,
  5024. is_causal: bool,
  5025. attn_mask: Optional[Tensor] = None,
  5026. scale: Optional[float] = None,
  5027. ):
  5028. # cpus's grad layout is different from cuda's,
  5029. # i.e. (batch_size, seq_len, num_heads, head_dim)
  5030. grad_q = torch.empty_permuted(
  5031. query.size(),
  5032. (0, 2, 1, 3),
  5033. dtype=query.dtype,
  5034. device=query.device,
  5035. )
  5036. grad_k = torch.empty_permuted(
  5037. key.size(),
  5038. (0, 2, 1, 3),
  5039. dtype=key.dtype,
  5040. device=key.device,
  5041. )
  5042. grad_v = torch.empty_permuted(
  5043. value.size(),
  5044. (0, 2, 1, 3),
  5045. dtype=value.dtype,
  5046. device=value.device,
  5047. )
  5048. return grad_q, grad_k, grad_v
  5049. @register_meta([aten._scaled_dot_product_attention_math_for_mps])
  5050. def meta__scaled_dot_product_attention_math_for_mps(
  5051. query: Tensor,
  5052. key: Tensor,
  5053. value: Tensor,
  5054. attn_mask: Optional[Tensor] = None,
  5055. dropout_p: float = 0.0,
  5056. is_causal: bool = False,
  5057. dropout_mask: Optional[Tensor] = None,
  5058. scale: Optional[float] = None,
  5059. ) -> tuple[Tensor, Tensor]:
  5060. def ensure_4d(x):
  5061. if x.dim() == 3:
  5062. return x.unsqueeze(0), True
  5063. elif x.dim() > 4:
  5064. batch_size = 1
  5065. for i in range(x.dim() - 3):
  5066. batch_size *= x.shape[i]
  5067. return x.view(batch_size, x.size(-3), x.size(-2), x.size(-1)), True
  5068. else:
  5069. return x, False
  5070. q_, unsqueezed = ensure_4d(query)
  5071. k_, _ = ensure_4d(key)
  5072. v_, _ = ensure_4d(value)
  5073. batch_size, num_head, q_size, head_size = q_.shape
  5074. _, k_size, max_seq_length, _ = k_.shape
  5075. def sdpa_vector_fast_mps():
  5076. out = q_.new_empty(q_.shape)
  5077. if unsqueezed:
  5078. out = out.view_as(query)
  5079. attn = q_.new_empty((batch_size, num_head, q_size, max_seq_length))
  5080. if unsqueezed:
  5081. if query.dim() == 3:
  5082. attn = attn.squeeze(0)
  5083. else:
  5084. shape = list(query.shape[:-3]) + attn.shape[1:4]
  5085. attn = attn.view(shape)
  5086. return out, attn
  5087. def sdpa_vector_2pass_mps():
  5088. blocks = 32
  5089. out = q_.new_empty(q_.shape)
  5090. intermediate = q_.new_empty((batch_size, num_head, q_size, blocks, head_size))
  5091. return out, intermediate
  5092. if (max_seq_length >= 1024) or (k_size < q_size and max_seq_length >= 4096):
  5093. return sdpa_vector_2pass_mps()
  5094. else:
  5095. return sdpa_vector_fast_mps()
  5096. @register_meta([aten._scaled_dot_product_efficient_attention])
  5097. def meta__scaled_dot_product_efficient_attention(
  5098. query: Tensor,
  5099. key: Tensor,
  5100. value: Tensor,
  5101. attn_bias: Optional[Tensor],
  5102. compute_log_sumexp: bool,
  5103. dropout_p=0.0,
  5104. is_causal: bool = False,
  5105. scale: Optional[float] = None,
  5106. ):
  5107. query = query.transpose(1, 2)
  5108. key = key.transpose(1, 2)
  5109. value = value.transpose(1, 2)
  5110. B = query.size(0)
  5111. M = query.size(1)
  5112. num_heads = query.size(-2)
  5113. Kv = value.size(-1)
  5114. res = torch.empty(B, M, num_heads, Kv, dtype=query.dtype, device=query.device)
  5115. if torch.version.hip and torch.cuda.is_available():
  5116. """Please see: https://github.com/pytorch/pytorch/issues/146848
  5117. longsumexp last dim should be seq length
  5118. """
  5119. logsumexp_dim = M if compute_log_sumexp else 0
  5120. else:
  5121. logsumexp_dim = math.ceil(M / 32) * 32 if compute_log_sumexp else 0
  5122. logsum_exp = torch.empty(
  5123. (B, num_heads, logsumexp_dim),
  5124. dtype=torch.float,
  5125. device=query.device,
  5126. )
  5127. res = res.transpose(1, 2)
  5128. # See Note [Seed and Offset]:
  5129. seed = torch.empty((), dtype=torch.long, device="meta")
  5130. offset = torch.empty((), dtype=torch.long, device="meta")
  5131. return res, logsum_exp, seed, offset
  5132. @register_meta(
  5133. [
  5134. aten._scaled_dot_product_efficient_attention_backward,
  5135. ]
  5136. )
  5137. def meta__scaled_dot_product_efficient_backward(
  5138. grad_out: Tensor,
  5139. query: Tensor,
  5140. key: Tensor,
  5141. value: Tensor,
  5142. attn_bias: Optional[Tensor],
  5143. out: Tensor,
  5144. logsumexp: Tensor,
  5145. philox_seed: Tensor,
  5146. philox_offset: Tensor,
  5147. dropout_p: float,
  5148. grad_input_mask: list[bool],
  5149. is_causal: bool = False,
  5150. scale: Optional[float] = None,
  5151. ):
  5152. batch_size = query.size(0)
  5153. num_heads = query.size(1)
  5154. max_q = query.size(2)
  5155. head_dim = query.size(3)
  5156. head_dim_v = value.size(3)
  5157. max_k = key.size(2)
  5158. grad_q = torch.empty_permuted(
  5159. (batch_size, num_heads, max_q, head_dim),
  5160. (0, 2, 1, 3),
  5161. dtype=query.dtype,
  5162. device=query.device,
  5163. )
  5164. grad_k = torch.empty_permuted(
  5165. (batch_size, num_heads, max_k, head_dim),
  5166. (0, 2, 1, 3),
  5167. dtype=key.dtype,
  5168. device=key.device,
  5169. )
  5170. grad_v = torch.empty_permuted(
  5171. (batch_size, num_heads, max_k, head_dim_v),
  5172. (0, 2, 1, 3),
  5173. dtype=value.dtype,
  5174. device=value.device,
  5175. )
  5176. grad_bias = None
  5177. if attn_bias is not None and grad_input_mask[3]:
  5178. lastDim = attn_bias.size(-1)
  5179. lastDimAligned = lastDim if lastDim % 16 == 0 else lastDim + 16 - lastDim % 16
  5180. new_sizes = list(attn_bias.size())
  5181. new_sizes[-1] = lastDimAligned
  5182. grad_bias = torch.empty(
  5183. new_sizes, dtype=attn_bias.dtype, device=attn_bias.device
  5184. )
  5185. grad_bias = grad_bias[..., :lastDim]
  5186. return grad_q, grad_k, grad_v, grad_bias
  5187. @register_meta(
  5188. [
  5189. aten._scaled_dot_product_cudnn_attention_backward,
  5190. ]
  5191. )
  5192. def meta__scaled_dot_product_cudnn_backward(
  5193. grad_out: Tensor,
  5194. query: Tensor,
  5195. key: Tensor,
  5196. value: Tensor,
  5197. out: Tensor,
  5198. logsumexp: Tensor,
  5199. philox_seed: Tensor,
  5200. philox_offset: Tensor,
  5201. attn_bias: Tensor,
  5202. cum_seq_q: Tensor,
  5203. cum_seq_k: Tensor,
  5204. max_q: int,
  5205. max_k: int,
  5206. dropout_p: float,
  5207. is_causal: bool,
  5208. scale: Optional[float] = None,
  5209. ):
  5210. grad_q = torch.empty_like(query)
  5211. grad_k = torch.empty_like(key)
  5212. grad_v = torch.empty_like(value)
  5213. return grad_q, grad_k, grad_v
  5214. @register_meta(
  5215. [
  5216. aten._flash_attention_forward,
  5217. ]
  5218. )
  5219. def meta__flash_attention_forward(
  5220. query: Tensor,
  5221. key: Tensor,
  5222. value: Tensor,
  5223. cum_seq_q: Optional[Tensor],
  5224. cum_seq_k: Optional[Tensor],
  5225. max_q: int,
  5226. max_k: int,
  5227. dropout_p: float,
  5228. is_causal: bool,
  5229. return_debug_mask: bool,
  5230. scale: Optional[float] = None,
  5231. window_size_left: Optional[int] = None,
  5232. window_size_right: Optional[int] = None,
  5233. seqused_k: Optional[Tensor] = None,
  5234. alibi_slopes: Optional[Tensor] = None,
  5235. ):
  5236. # NB: there are two underlying paths:
  5237. # 1. normal dense path; expect 4D inputs of shape (batch_size, seqlen, num_heads, head_dim)
  5238. # 2. varseqlen path; expect 3D inputs of shape (total, num_heads, head_dim) where total
  5239. # includes all batch item sequences. cum_seq_q / cum_seq_k contain offsets into total
  5240. batch_size = query.size(0) if cum_seq_q is None else cum_seq_q.numel() - 1
  5241. max_seqlen_batch_q = query.size(1) if cum_seq_q is None else max_q
  5242. max_seqlen_batch_k = key.size(1) if cum_seq_k is None else max_k
  5243. num_heads = query.size(-2)
  5244. head_dim = query.size(-1)
  5245. # Cuda Path
  5246. attention = torch.empty_like(query)
  5247. if cum_seq_q is None:
  5248. logsumexp = torch.empty(
  5249. (batch_size, num_heads, max_seqlen_batch_q),
  5250. dtype=torch.float,
  5251. device=query.device,
  5252. )
  5253. else:
  5254. total_q = query.size(0)
  5255. logsumexp = torch.empty(
  5256. (num_heads, total_q), dtype=torch.float, device=query.device
  5257. )
  5258. if return_debug_mask:
  5259. blocksize_c = 128 if head_dim > 64 else 256
  5260. max_seqlen_k = math.ceil(max_seqlen_batch_q / blocksize_c)
  5261. if max_seqlen_batch_k <= 128:
  5262. max_seqlen_k = 128
  5263. elif max_seqlen_batch_k <= 256:
  5264. max_seqlen_k = 256
  5265. debug_mask = torch.empty(
  5266. (batch_size, num_heads, max_seqlen_batch_q, max_seqlen_k),
  5267. dtype=query.dtype,
  5268. device=query.device,
  5269. )
  5270. else:
  5271. debug_mask = torch.empty(0, dtype=query.dtype, device=query.device)
  5272. # See Note [Seed and Offset]
  5273. # See [Note] BC breaking change to flash seed/offset
  5274. seed, offset = None, None
  5275. if torch.version.hip and torch.cuda.is_available():
  5276. # Maintain old path on AMD
  5277. seed = torch.empty((), dtype=torch.long, device="meta")
  5278. offset = torch.empty((), dtype=torch.long, device="meta")
  5279. else:
  5280. seed = torch.empty((2), dtype=torch.uint64, device="meta")
  5281. offset = torch.empty((), dtype=torch.uint64, device="meta")
  5282. return (
  5283. attention,
  5284. logsumexp,
  5285. seed,
  5286. offset,
  5287. debug_mask,
  5288. )
  5289. @register_meta(
  5290. [
  5291. aten._flash_attention_backward,
  5292. ]
  5293. )
  5294. def meta__flash_attention_backward(
  5295. grad_out: Tensor,
  5296. query: Tensor,
  5297. key: Tensor,
  5298. value: Tensor,
  5299. out: Tensor,
  5300. logsumexp: Tensor,
  5301. cum_seq_q: Tensor,
  5302. cum_seq_k: Tensor,
  5303. max_q: int,
  5304. max_k: int,
  5305. dropout_p: float,
  5306. is_causal: bool,
  5307. philox_seed: Tensor,
  5308. philox_offset: Tensor,
  5309. scale: Optional[float] = None,
  5310. window_size_left: Optional[int] = None,
  5311. window_size_right: Optional[int] = None,
  5312. ):
  5313. grad_query = torch.empty_like(query)
  5314. grad_key = torch.empty_like(key)
  5315. grad_value = torch.empty_like(value)
  5316. return grad_query, grad_key, grad_value
  5317. @register_meta(
  5318. [
  5319. aten._efficient_attention_forward,
  5320. ]
  5321. )
  5322. def meta__efficient_attention_forward(
  5323. query: Tensor,
  5324. key: Tensor,
  5325. value: Tensor,
  5326. bias: Optional[Tensor],
  5327. cu_seqlens_q: Optional[Tensor],
  5328. cu_seqlens_k: Optional[Tensor],
  5329. max_seqlen_q: Optional[int],
  5330. max_seqlen_k: Optional[int],
  5331. dropout_p: float,
  5332. custom_mask_type: int,
  5333. compute_log_sumexp: bool = False,
  5334. scale: Optional[float] = None,
  5335. causal_diagonal: Optional[Tensor] = None,
  5336. seqlen_k: Optional[Tensor] = None,
  5337. window_size: Optional[int] = None,
  5338. ):
  5339. B = query.size(0)
  5340. M = query.size(1)
  5341. N = key.size(1)
  5342. num_heads = query.size(-2)
  5343. Kv = value.size(-1)
  5344. res = torch.empty(B, M, num_heads, Kv, dtype=query.dtype, device=query.device)
  5345. logsumexp_batch_dim = cu_seqlens_q.size(0) - 1 if (cu_seqlens_q is not None) else B
  5346. actual_max_seqlen_q = M
  5347. if cu_seqlens_q is not None:
  5348. assert max_seqlen_q is not None
  5349. actual_max_seqlen_q = max_seqlen_q
  5350. actual_max_seqlen_k = max_seqlen_k if max_seqlen_k is not None else N
  5351. logsumexp_dim = (
  5352. math.ceil(actual_max_seqlen_q / 32) * 32 if compute_log_sumexp else 0
  5353. )
  5354. logsum_exp = torch.empty(
  5355. (logsumexp_batch_dim, num_heads, logsumexp_dim),
  5356. dtype=torch.float,
  5357. device=query.device,
  5358. )
  5359. # See Note [Seed and Offset]:
  5360. seed = torch.empty((), dtype=torch.long, device="meta")
  5361. offset = torch.empty((), dtype=torch.long, device="meta")
  5362. return res, logsum_exp, seed, offset, actual_max_seqlen_q, actual_max_seqlen_k
  5363. @register_meta(
  5364. [
  5365. aten._efficient_attention_backward,
  5366. ]
  5367. )
  5368. def meta__efficient_attention_backward(
  5369. grad_out: Tensor,
  5370. query: Tensor,
  5371. key: Tensor,
  5372. value: Tensor,
  5373. bias: Optional[Tensor],
  5374. cu_seqlens_q: Optional[Tensor],
  5375. cu_seqlens_k: Optional[Tensor],
  5376. max_seqlen_q: torch.SymInt,
  5377. max_seqlen_k: torch.SymInt,
  5378. logsumexp: Tensor,
  5379. dropout_p: float,
  5380. philox_seed: Tensor,
  5381. philox_offset: Tensor,
  5382. custom_mask_type: int,
  5383. bias_requires_grad: bool,
  5384. scale: Optional[float] = None,
  5385. num_splits_key: Optional[int] = None,
  5386. shared_storage_dqdkdv: bool = False,
  5387. ):
  5388. if shared_storage_dqdkdv:
  5389. torch._check(
  5390. query.shape[1] == key.shape[1],
  5391. lambda: "seqlen must match for `shared_storage_dqdkdv",
  5392. )
  5393. torch._check(
  5394. query.shape[3] == key.shape[3],
  5395. lambda: "embedding dim must match for `shared_storage_dqdkdv",
  5396. )
  5397. chunk = torch.empty(
  5398. (*query.shape[0:-2], 3, query.shape[-2], query.shape[-1]),
  5399. dtype=query.dtype,
  5400. device=query.device,
  5401. )
  5402. grad_query = chunk.select(-3, 0)
  5403. grad_key = chunk.select(-3, 1)
  5404. grad_value = chunk.select(-3, 2)
  5405. else:
  5406. grad_query = torch.empty_like(query)
  5407. grad_key = torch.empty_like(key)
  5408. grad_value = torch.empty_like(value)
  5409. if bias is not None:
  5410. lastDim = bias.size(-1)
  5411. lastDimAligned = lastDim if lastDim % 16 == 0 else lastDim + 16 - lastDim % 16
  5412. new_sizes = list(bias.size())
  5413. new_sizes[-1] = lastDimAligned
  5414. grad_bias = torch.empty(new_sizes, dtype=bias.dtype, device=bias.device)
  5415. grad_bias = grad_bias[..., :lastDim]
  5416. else:
  5417. grad_bias = torch.empty((), device=query.device)
  5418. return grad_query, grad_key, grad_value, grad_bias
  5419. @register_meta([aten._scaled_mm.default])
  5420. def meta_scaled_mm(
  5421. self: torch.Tensor,
  5422. mat2: torch.Tensor,
  5423. scale_a: torch.Tensor,
  5424. scale_b: torch.Tensor,
  5425. bias: Optional[torch.Tensor] = None,
  5426. scale_result: Optional[torch.Tensor] = None,
  5427. out_dtype: Optional[torch.dtype] = None,
  5428. use_fast_accum: bool = False,
  5429. ):
  5430. def is_fp8_or_fp4_type(dtype):
  5431. return dtype in (
  5432. torch.float8_e4m3fn,
  5433. torch.float8_e5m2,
  5434. torch.float8_e4m3fnuz,
  5435. torch.float8_e5m2fnuz,
  5436. torch.float4_e2m1fn_x2,
  5437. )
  5438. torch._check(
  5439. self.dim() == 2 and mat2.dim() == 2,
  5440. lambda: f"Inputs must be 2D but got self.dim()={self.dim()} and mat2.dim()={mat2.dim()}",
  5441. )
  5442. torch._check(
  5443. is_fp8_or_fp4_type(self.dtype) and is_fp8_or_fp4_type(mat2.dtype),
  5444. lambda: f"Expected both inputs to be fp8 or fp4 types but got self.dtype={self.dtype} and mat2.dtype={mat2.dtype}",
  5445. )
  5446. if device_hint(self) == "cuda":
  5447. def is_row_major(stride):
  5448. return stride[0] > stride[1] and stride[1] == 1
  5449. def is_col_major(stride):
  5450. return stride[0] == 1 and stride[1] > 1
  5451. def has_zero_dim(tensor_2d):
  5452. return tensor_2d.size(0) == 0 or tensor_2d.size(1) == 0
  5453. torch._check(
  5454. is_row_major(self.stride()) or has_zero_dim(self),
  5455. lambda: f"self must be row_major, got stride {self.stride()}",
  5456. )
  5457. torch._check(
  5458. is_col_major(mat2.stride()) or has_zero_dim(mat2),
  5459. lambda: f"mat2 must be col_major, got stride {mat2.stride()}",
  5460. )
  5461. torch._check(
  5462. self.size(1) % 16 == 0,
  5463. lambda: f"Expected self.size(1) to be divisible by 16, but got self.size(1)={self.size(1)}",
  5464. )
  5465. torch._check(
  5466. mat2.size(0) % 16 == 0 and mat2.size(1) % 16 == 0,
  5467. lambda: f"Expected both dimensions of mat2 to be divisible by 16 but got {mat2.shape}",
  5468. )
  5469. # determine scaling type and check input dimensions (refer to Blas.cpp op)
  5470. m, _k = self.shape
  5471. n = mat2.size(1)
  5472. is_blockwise_scaling = (
  5473. scale_a.dtype == torch.float8_e8m0fnu
  5474. and scale_b.dtype == torch.float8_e8m0fnu
  5475. ) or (
  5476. scale_a.dtype == torch.float8_e4m3fn
  5477. and scale_b.dtype == torch.float8_e4m3fn
  5478. )
  5479. if scale_a.numel() == 1 and scale_b.numel() == 1:
  5480. # tensorwise scaling
  5481. torch._check(
  5482. scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32,
  5483. lambda: "For tensorwise scaling, both scale_a and scale_b must be float (fp32) tensors.",
  5484. )
  5485. elif is_blockwise_scaling:
  5486. # blockwise scaling
  5487. if scale_a.dtype == torch.float8_e4m3fn:
  5488. # NVIDIA's nvfp4 recipe:
  5489. # * block size is 16 elements packed (32 unpacked)
  5490. # * _k needs to be translated to the unpacked version
  5491. block_size_k = 16
  5492. _k = _k * 2
  5493. else:
  5494. block_size_k = 32
  5495. block_size_mn = 128
  5496. def ceil_div(a, b):
  5497. return (a + b - 1) // b
  5498. num_k_blocks = ceil_div(_k, block_size_k)
  5499. padded_num_k_blocks = ceil_div(num_k_blocks, 4) * 4
  5500. expected_a_size = (
  5501. block_size_mn * ceil_div(m, block_size_mn) * padded_num_k_blocks
  5502. )
  5503. expected_b_size = (
  5504. block_size_mn * ceil_div(n, block_size_mn) * padded_num_k_blocks
  5505. )
  5506. if (
  5507. scale_a.numel() == expected_a_size
  5508. and scale_b.numel() == expected_b_size
  5509. ):
  5510. torch._check(
  5511. scale_a.is_contiguous(),
  5512. lambda: "scale_a must be contiguous",
  5513. )
  5514. torch._check(
  5515. scale_b.is_contiguous(),
  5516. lambda: "scale_b must be contiguous",
  5517. )
  5518. else:
  5519. torch._check(
  5520. False,
  5521. lambda: (
  5522. "Invalid blockwise scaling configuration. "
  5523. f"For blockwise scaling, scale_a should have {expected_a_size} elements, got {scale_a.numel()}, "
  5524. f"scale_b should have {expected_b_size} elements, got {scale_b.numel()}."
  5525. ),
  5526. )
  5527. else:
  5528. torch._check(
  5529. scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32,
  5530. lambda: "For rowwise scaling, both scale_a and scale_b must be float (fp32) tensors.",
  5531. )
  5532. # for rowwise scaling, enforce 2D input tensors
  5533. torch._check(
  5534. scale_a.dim() == 2 and scale_b.dim() == 2,
  5535. lambda: f"For non-tensorwise scaling, scale tensors must be 2D, but got {scale_a.dim()=} and {scale_b.dim()=}",
  5536. )
  5537. if (
  5538. scale_a.size(0) == m
  5539. and scale_a.size(1) == 1
  5540. and scale_b.size(0) == 1
  5541. and scale_b.size(1) == n
  5542. ):
  5543. # rowwise scaling
  5544. torch._check(
  5545. scale_a.is_contiguous() and scale_b.is_contiguous(),
  5546. lambda: "Both scale_a and scale_b must be contiguous for rowwise scaling.",
  5547. )
  5548. else:
  5549. # does not match any valid scaling type
  5550. torch._check(
  5551. False,
  5552. lambda: (
  5553. "Invalid scaling configuration. "
  5554. "For tensorwise scaling, both scales should be scalar. "
  5555. f"For rowwise scaling, scale_a should be ({m}, 1), scale_b should be (1, {n}). "
  5556. f"Got scale_a.size()=({scale_a.size(0)}, {scale_a.size(1)}) "
  5557. f"and scale_b.size()=({scale_b.size(0)}, {scale_b.size(1)})"
  5558. ),
  5559. )
  5560. _out_dtype = out_dtype if out_dtype is not None else self.dtype
  5561. return torch.empty(self.size(0), mat2.size(1), dtype=_out_dtype, device=self.device)
  5562. @register_meta([aten.scatter_reduce.two, aten.scatter_reduce.two_out])
  5563. @out_wrapper()
  5564. def meta_scatter_reduce_two(self, dim, index, src, reduce, include_self=True):
  5565. scatter_meta_impl(self, dim, index, src, reduce, use_new_options=True)
  5566. return self.new_empty(self.shape)
  5567. @register_meta(aten.scatter_reduce_.two)
  5568. def meta_scatter_reduce__two(self, dim, index, src, reduce, include_self=True):
  5569. scatter_meta_impl(self, dim, index, src, reduce, use_new_options=True)
  5570. return self
  5571. @register_meta([aten.multinomial.default, aten.multinomial.out])
  5572. @out_wrapper()
  5573. def meta_multinomial(input, num_samples, replacement=False, *, generator=None):
  5574. torch._check(
  5575. 0 < input.dim() <= 2,
  5576. lambda: f"The probability distributions dimensions must be 1 or 2, but got {input.dim()}",
  5577. )
  5578. if input.dim() == 1:
  5579. return torch.empty(num_samples, dtype=torch.long, device=input.device)
  5580. return torch.empty(
  5581. input.size(0), num_samples, dtype=torch.long, device=input.device
  5582. )
  5583. def multiply_integers(vs):
  5584. r = 1
  5585. for v in vs:
  5586. r *= v
  5587. return r
  5588. def upsample_common_check(input_size, output_size, num_spatial_dims):
  5589. torch._check(
  5590. len(output_size) == num_spatial_dims,
  5591. lambda: f"It is expected output_size equals to {num_spatial_dims}, but got size {len(output_size)}",
  5592. )
  5593. expected_input_dims = num_spatial_dims + 2 # N, C, ...
  5594. torch._check(
  5595. len(input_size) == expected_input_dims,
  5596. lambda: f"It is expected input_size equals to {expected_input_dims}, but got size {len(input_size)}",
  5597. )
  5598. torch._check(
  5599. all(s > 0 for s in input_size[2:]) and all(s > 0 for s in output_size),
  5600. lambda: f"Input and output sizes should be greater than 0, but got "
  5601. f"input size {input_size} and output size {output_size}",
  5602. )
  5603. nbatch, channels = input_size[:2]
  5604. return (nbatch, channels, *output_size)
  5605. @register_meta(
  5606. [aten.upsample_nearest1d.default, aten._upsample_nearest_exact1d.default]
  5607. )
  5608. def upsample_nearest1d(input, output_size, scales=None):
  5609. torch._check(
  5610. input.numel() != 0 or multiply_integers(input.size()[1:]),
  5611. lambda: f"Non-empty 3D data tensor expected but got a tensor with sizes {input.size()}",
  5612. )
  5613. full_output_size = upsample_common_check(
  5614. input.size(), output_size, num_spatial_dims=1
  5615. )
  5616. return input.new_empty(full_output_size).to(
  5617. memory_format=utils.suggest_memory_format(input)
  5618. )
  5619. @register_meta(
  5620. [aten.upsample_nearest2d.default, aten._upsample_nearest_exact2d.default]
  5621. )
  5622. def upsample_nearest2d(input, output_size, scales_h=None, scales_w=None):
  5623. torch._check(
  5624. input.numel() != 0 or multiply_integers(input.size()[1:]),
  5625. lambda: f"Non-empty 4D data tensor expected but got a tensor with sizes {input.size()}",
  5626. )
  5627. full_output_size = upsample_common_check(
  5628. input.size(), output_size, num_spatial_dims=2
  5629. )
  5630. output = input.new_empty(full_output_size)
  5631. # convert output to correct memory format, if necessary
  5632. memory_format = utils.suggest_memory_format(input)
  5633. # following "heuristic: only use channels_last path when it's faster than the contiguous path"
  5634. _, n_channels, _, _ = input.shape
  5635. if input.device.type == "cuda" and n_channels < 4:
  5636. memory_format = torch.contiguous_format
  5637. output = output.contiguous(memory_format=memory_format)
  5638. return output
  5639. @register_meta(
  5640. [
  5641. aten.upsample_nearest2d_backward.default,
  5642. aten._upsample_nearest_exact2d_backward.default,
  5643. ]
  5644. )
  5645. def upsample_nearest2d_backward(
  5646. grad_output: Tensor,
  5647. output_size: Sequence[Union[int, torch.SymInt]],
  5648. input_size: Sequence[Union[int, torch.SymInt]],
  5649. scales_h: Optional[float] = None,
  5650. scales_w: Optional[float] = None,
  5651. ):
  5652. full_output_size = upsample_common_check(
  5653. input_size, output_size, num_spatial_dims=2
  5654. )
  5655. torch._check(
  5656. grad_output.ndim == 4,
  5657. lambda: f"Expected grad_output to be a tensor of dimension 4 but got: dimension {grad_output.ndim}",
  5658. )
  5659. for i in range(4):
  5660. torch._check(
  5661. grad_output.size(i) == full_output_size[i],
  5662. lambda: (
  5663. f"Expected grad_output to have the same shape as output;"
  5664. f" output.size({i}) = {full_output_size[i]}"
  5665. f" but got grad_output.size({i}) = {grad_output.size(i)}"
  5666. ),
  5667. )
  5668. return grad_output.new_empty(input_size).to(
  5669. memory_format=utils.suggest_memory_format(grad_output)
  5670. ) # type: ignore[call-overload]
  5671. @register_meta(
  5672. [aten.upsample_nearest3d.default, aten._upsample_nearest_exact3d.default]
  5673. )
  5674. def upsample_nearest3d(input, output_size, scales_d=None, scales_h=None, scales_w=None):
  5675. torch._check(
  5676. input.numel() != 0 or multiply_integers(input.size()[1:]),
  5677. lambda: f"Non-empty 5D data tensor expected but got a tensor with sizes {input.size()}",
  5678. )
  5679. full_output_size = upsample_common_check(
  5680. input.size(), output_size, num_spatial_dims=3
  5681. )
  5682. return input.new_empty(full_output_size).to(
  5683. memory_format=utils.suggest_memory_format(input)
  5684. )
  5685. @register_meta(
  5686. [
  5687. aten.sort.default,
  5688. aten.sort.stable,
  5689. aten.sort.values,
  5690. aten.sort.values_stable,
  5691. ]
  5692. )
  5693. def meta_sort(self, stable=None, dim=-1, descending=False, values=None, indices=None):
  5694. v, i = torch.empty_like(self), torch.empty_like(self, dtype=torch.int64)
  5695. if values is not None and indices is not None:
  5696. assert isinstance(values, TensorLike)
  5697. assert isinstance(indices, TensorLike)
  5698. # Makes sure values and indices have the same strides. For cases where
  5699. # these have different shapes, like (5, 10, 5) and (0) in msort.
  5700. out_shape = v.shape
  5701. out_stride = v.stride()
  5702. values = _maybe_resize_out(values, out_shape)
  5703. indices = _maybe_resize_out(indices, out_shape)
  5704. values.as_strided_(out_shape, out_stride)
  5705. indices.as_strided_(out_shape, out_stride)
  5706. _safe_copy_out(copy_from=v, copy_to=values) # type: ignore[arg-type]
  5707. _safe_copy_out(copy_from=i, copy_to=indices) # type: ignore[arg-type]
  5708. return values, indices
  5709. return v, i
  5710. def rnn_cell_checkSizes(
  5711. input_gates,
  5712. hidden_gates,
  5713. input_bias,
  5714. hidden_bias,
  5715. factor,
  5716. prev_hidden,
  5717. ):
  5718. torch._check(input_gates.ndim == 2, lambda: f"{input_gates.ndim} != 2")
  5719. torch._check(
  5720. input_gates.shape == hidden_gates.shape,
  5721. lambda: f"{input_gates.shape} != {hidden_gates.shape}",
  5722. )
  5723. gates_size = input_gates.size(1)
  5724. if input_bias is not None:
  5725. torch._check(input_bias.ndim == 1, lambda: f"{input_bias.ndim} != 1")
  5726. torch._check(
  5727. input_bias.numel() == gates_size,
  5728. lambda: f"{input_bias.numel()} != {gates_size}",
  5729. )
  5730. torch._check(
  5731. input_bias.shape == hidden_bias.shape,
  5732. lambda: f"{input_bias.shape} != {hidden_bias.shape}",
  5733. )
  5734. torch._check(prev_hidden.ndim == 2, lambda: f"{prev_hidden.ndim} != 2")
  5735. expected_prev_hidden_numel = input_gates.size(0) * gates_size // factor
  5736. torch._check(
  5737. prev_hidden.numel() == expected_prev_hidden_numel,
  5738. lambda: f"{prev_hidden.numel()} != {input_gates.size(0)} * {gates_size} // {factor} (aka {expected_prev_hidden_numel})",
  5739. )
  5740. torch._check(
  5741. all(
  5742. x.device == input_gates.device
  5743. for x in [hidden_gates, input_bias, hidden_bias, prev_hidden]
  5744. ),
  5745. lambda: "expected all inputs to be same device",
  5746. )
  5747. @register_meta(aten._thnn_fused_lstm_cell.default)
  5748. def _thnn_fused_lstm_cell_meta(
  5749. input_gates,
  5750. hidden_gates,
  5751. cx,
  5752. input_bias=None,
  5753. hidden_bias=None,
  5754. ):
  5755. rnn_cell_checkSizes(input_gates, hidden_gates, input_bias, hidden_bias, 4, cx)
  5756. workspace = torch.empty_like(input_gates, memory_format=torch.contiguous_format)
  5757. hy = torch.empty_like(cx, memory_format=torch.contiguous_format)
  5758. cy = torch.empty_like(cx, memory_format=torch.contiguous_format)
  5759. return (hy, cy, workspace)
  5760. @register_meta(aten._cudnn_rnn.default)
  5761. def _cudnn_rnn(
  5762. input,
  5763. weight,
  5764. weight_stride0,
  5765. weight_buf,
  5766. hx,
  5767. cx,
  5768. mode,
  5769. hidden_size,
  5770. proj_size,
  5771. num_layers,
  5772. batch_first,
  5773. dropout,
  5774. train,
  5775. bidirectional,
  5776. batch_sizes,
  5777. dropout_state,
  5778. ):
  5779. is_input_packed = len(batch_sizes) != 0
  5780. if is_input_packed:
  5781. seq_length = len(batch_sizes)
  5782. mini_batch = batch_sizes[0]
  5783. batch_sizes_sum = input.shape[0]
  5784. else:
  5785. seq_length = input.shape[1] if batch_first else input.shape[0]
  5786. mini_batch = input.shape[0] if batch_first else input.shape[1]
  5787. batch_sizes_sum = -1
  5788. num_directions = 2 if bidirectional else 1
  5789. out_size = proj_size if proj_size != 0 else hidden_size
  5790. if is_input_packed:
  5791. out_shape = [batch_sizes_sum, out_size * num_directions]
  5792. else:
  5793. out_shape = (
  5794. [mini_batch, seq_length, out_size * num_directions]
  5795. if batch_first
  5796. else [seq_length, mini_batch, out_size * num_directions]
  5797. )
  5798. output = input.new_empty(out_shape)
  5799. cell_shape = [num_layers * num_directions, mini_batch, hidden_size]
  5800. if cx is None:
  5801. cy = torch.empty(0, device=input.device)
  5802. else:
  5803. cy = cx.new_empty(cell_shape)
  5804. hy = hx.new_empty([num_layers * num_directions, mini_batch, out_size])
  5805. # TODO: Query cudnnGetRNNTrainingReserveSize (expose to python)
  5806. reserve_shape = 0 if train else 0
  5807. reserve = input.new_empty(reserve_shape, dtype=torch.uint8)
  5808. return output, hy, cy, reserve, weight_buf
  5809. @register_meta(aten.mkldnn_rnn_layer.default)
  5810. def mkldnn_rnn_layer(
  5811. input,
  5812. w0,
  5813. w1,
  5814. w2,
  5815. w3,
  5816. hx_,
  5817. cx_,
  5818. reverse,
  5819. batch_sizes,
  5820. mode,
  5821. hidden_size,
  5822. num_layers,
  5823. has_biases,
  5824. bidirectional,
  5825. batch_first,
  5826. train,
  5827. ):
  5828. seq_length = input.shape[1] if batch_first else input.shape[0]
  5829. mini_batch = input.shape[0] if batch_first else input.shape[1]
  5830. output_chanels = hidden_size
  5831. out_shape = (
  5832. [mini_batch, seq_length, output_chanels]
  5833. if batch_first
  5834. else [seq_length, mini_batch, output_chanels]
  5835. )
  5836. output = input.new_empty(out_shape)
  5837. if hx_ is None:
  5838. hy = torch.empty(0, device=input.device)
  5839. else:
  5840. hy = hx_.new_empty(hx_.shape)
  5841. if cx_ is None:
  5842. cy = torch.empty(0, device=input.device)
  5843. else:
  5844. cy = cx_.new_empty(cx_.shape)
  5845. workspace = torch.empty(0, device=input.device, dtype=torch.uint8)
  5846. return output, hy, cy, workspace
  5847. def zero_numel_check_dims(self, dim, fn_name):
  5848. if self.ndim == 0:
  5849. torch._check_index(
  5850. dim == 0 or dim == -1,
  5851. lambda: f"{fn_name}: Expected reduction dim -1 or 0 for scalar but got {dim}",
  5852. )
  5853. else:
  5854. torch._check_index(
  5855. self.size(dim) != 0,
  5856. lambda: f"{fn_name}: Expected reduction dim {dim} to have non-zero size.",
  5857. )
  5858. # From aten/src/ATen/native/ReduceOps.cpp
  5859. def check_argmax_argmin(name, self, dim):
  5860. if dim is not None:
  5861. dim = maybe_wrap_dim(dim, self.dim())
  5862. zero_numel_check_dims(self, dim, name)
  5863. else:
  5864. torch._check(
  5865. self.numel() != 0,
  5866. lambda: f"{name}: Expected reduction dim to be specified for input.numel() == 0.",
  5867. )
  5868. @register_meta([aten.argmax.default, aten.argmin.default])
  5869. def argmax_argmin_meta(self, dim=None, keepdim=False):
  5870. check_argmax_argmin("argmax", self, dim)
  5871. dims = utils.reduction_dims(self.shape, (dim,) if dim is not None else None)
  5872. shape = _compute_reduction_shape(self, dims, keepdim)
  5873. return self.new_empty(shape, dtype=torch.int64)
  5874. @register_meta(aten.scalar_tensor.default)
  5875. def scalar_tensor(s, dtype=None, layout=None, device=None, pin_memory=None):
  5876. # NB: It's always wrong to try to create a scalar tensor with the jagged layout.
  5877. # Rather than fix this everywhere, just use the strided layout and let NJT handle
  5878. # scalar tensor broadcasting.
  5879. if layout == torch.jagged:
  5880. layout = torch.strided
  5881. return torch.empty(
  5882. (), dtype=dtype, layout=layout, device=device, pin_memory=pin_memory
  5883. )
  5884. @register_meta(aten.topk.default)
  5885. def topk_meta(self, k, dim=-1, largest=True, sorted=True):
  5886. # From aten/src/ATen/native/Sorting.cpp
  5887. dim = maybe_wrap_dim(dim, self.dim(), wrap_scalar=True)
  5888. sliceSize = 1 if self.dim() == 0 else self.size(dim)
  5889. torch._check_is_size(k)
  5890. torch._check(k <= sliceSize, lambda: "k not in range for dimension")
  5891. topKSize = list(self.shape)
  5892. if len(topKSize) > 0:
  5893. topKSize[dim] = k
  5894. return self.new_empty(topKSize), self.new_empty(topKSize, dtype=torch.int64)
  5895. @register_meta(aten._segment_reduce_backward)
  5896. @out_wrapper()
  5897. def meta__segment_reduce_backward(
  5898. grad, output, data, reduce, lengths=None, offsets=None, axis=0, initial=None
  5899. ):
  5900. assert lengths is not None or offsets is not None, (
  5901. "segment_reduce(): Either lengths or offsets must be defined"
  5902. )
  5903. data_contig = data.contiguous()
  5904. grad_contig = grad.contiguous()
  5905. return torch.empty_like(
  5906. data_contig,
  5907. dtype=grad_contig.dtype,
  5908. device=grad_contig.device,
  5909. layout=grad_contig.layout,
  5910. )
  5911. @register_meta([aten.kthvalue.default, aten.kthvalue.values])
  5912. @out_wrapper("values", "indices")
  5913. def kthvalue_meta(self, k, dim=-1, keepdim=False):
  5914. from torch.fx.experimental.symbolic_shapes import sym_and
  5915. dim = maybe_wrap_dim(dim, self.dim(), wrap_scalar=True)
  5916. dimSize = self.size(dim) if self.dim() > 0 else 1
  5917. torch._check(
  5918. sym_and(k >= 1, k <= dimSize),
  5919. lambda: f"kthvalue(): selected number k out of range for dimension {dim}",
  5920. )
  5921. shape = list(self.shape[:dim] + self.shape[dim + 1 :])
  5922. if keepdim and self.dim() > 0:
  5923. shape.insert(dim, 1)
  5924. return self.new_empty(shape), self.new_empty(shape, dtype=torch.int64)
  5925. legacy_contiguous_memory_format = torch.contiguous_format
  5926. # From aten/src/ATen/native/cuda/RNN.cu
  5927. def checkLSTMBackwardSizes(grad_hy, grad_cy, cx, cy, workspace):
  5928. defined_grad = grad_hy if grad_hy is not None else grad_cy
  5929. torch._check(defined_grad.dim() == 2, lambda: "")
  5930. exp_size = defined_grad.size()
  5931. if grad_hy is not None:
  5932. torch._check(grad_hy.size() == exp_size, lambda: "")
  5933. if grad_cy is not None:
  5934. torch._check(grad_cy.size() == exp_size, lambda: "")
  5935. torch._check(cx.size() == exp_size, lambda: "")
  5936. torch._check(cy.size() == exp_size, lambda: "")
  5937. torch._check(workspace.dim() == 2, lambda: "")
  5938. torch._check(workspace.numel() == exp_size[0] * exp_size[1] * 4, lambda: "")
  5939. # From aten/src/ATen/native/cuda/RNN.cu
  5940. @register_meta(aten._thnn_fused_lstm_cell_backward_impl.default)
  5941. def _thnn_fused_lstm_cell_backward_impl(grad_hy, grad_cy, cx, cy, workspace, has_bias):
  5942. if grad_hy is None and grad_cy is None:
  5943. return None, None, None
  5944. checkLSTMBackwardSizes(grad_hy, grad_cy, cx, cy, workspace)
  5945. grad_gates = torch.empty_like(
  5946. workspace, memory_format=legacy_contiguous_memory_format
  5947. )
  5948. grad_cx = torch.empty_like(cx, memory_format=legacy_contiguous_memory_format)
  5949. grad_bias = grad_gates.sum(0, keepdim=False) if has_bias else None
  5950. return grad_gates, grad_cx, grad_bias
  5951. # From aten/src/ATen/native/mps/operations/Linear.mm
  5952. @register_meta(aten.linear_backward.default)
  5953. def linear_backward(input_, grad_output_, weight_, output_mask):
  5954. grad_input = None
  5955. grad_weight = None
  5956. grad_bias = None
  5957. if output_mask[0]:
  5958. grad_input = grad_output_.new_empty(input_.size())
  5959. if output_mask[1] or output_mask[2]:
  5960. grad_weight = grad_output_.new_empty((grad_output_.size(-1), input_.size(-1)))
  5961. grad_bias = grad_output_.new_empty(grad_output_.size(-1))
  5962. return (grad_input, grad_weight, grad_bias)
  5963. @register_meta(aten.pixel_shuffle.default)
  5964. def meta_pixel_shuffle(self, upscale_factor):
  5965. assert (
  5966. len(self.shape) > 2 and self.shape[-3] % (upscale_factor * upscale_factor) == 0
  5967. ), (
  5968. f"Invalid input shape for pixel_shuffle: {self.shape} with upscale_factor = {upscale_factor}"
  5969. )
  5970. def is_channels_last(ten):
  5971. return torch._prims_common.suggest_memory_format(ten) == torch.channels_last
  5972. def pick_memory_format():
  5973. if is_channels_last(self):
  5974. if device_hint(self) == "cuda":
  5975. return torch.contiguous_format
  5976. else:
  5977. return torch.channels_last
  5978. elif self.is_contiguous(memory_format=torch.contiguous_format):
  5979. return torch.contiguous_format
  5980. elif self.is_contiguous(memory_format=torch.preserve_format):
  5981. return torch.preserve_format
  5982. C = self.shape[-3] // (upscale_factor * upscale_factor)
  5983. Hr = self.shape[-2] * upscale_factor
  5984. Wr = self.shape[-1] * upscale_factor
  5985. out_shape = (*self.shape[:-3], C, Hr, Wr)
  5986. out = self.new_empty(out_shape)
  5987. out = out.to(memory_format=pick_memory_format()) # type: ignore[call-overload]
  5988. return out
  5989. @register_meta(aten.mkldnn_rnn_layer_backward.default)
  5990. def mkldnn_rnn_layer_backward(
  5991. input,
  5992. weight0,
  5993. weight1,
  5994. weight2,
  5995. weight3,
  5996. hx_,
  5997. cx_tmp,
  5998. output,
  5999. hy_,
  6000. cy_,
  6001. grad_output_r_opt,
  6002. grad_hy_r_opt,
  6003. grad_cy_r_opt,
  6004. reverse,
  6005. mode,
  6006. hidden_size,
  6007. num_layers,
  6008. has_biases,
  6009. train,
  6010. bidirectional,
  6011. batch_sizes,
  6012. batch_first,
  6013. workspace,
  6014. ):
  6015. diff_x = input.new_empty(input.shape)
  6016. diff_hx = hx_.new_empty(hx_.shape)
  6017. diff_cx = cx_tmp.new_empty(cx_tmp.shape)
  6018. diff_w1 = weight0.new_empty(weight0.shape)
  6019. diff_w2 = weight1.new_empty(weight1.shape)
  6020. diff_b = weight2.new_empty(weight2.shape)
  6021. return diff_x, diff_w1, diff_w2, diff_b, diff_b, diff_hx, diff_cx
  6022. @register_meta([aten.bucketize.Tensor, aten.bucketize.Tensor_out])
  6023. @out_wrapper()
  6024. def meta_bucketize(self, boundaries, *, out_int32=False, right=False):
  6025. return torch.empty_like(
  6026. self,
  6027. dtype=torch.int32 if out_int32 else torch.int64,
  6028. memory_format=torch.contiguous_format,
  6029. )
  6030. @register_meta([aten.histc])
  6031. @out_wrapper()
  6032. def meta_histc(input, bins=100, min=0, max=0):
  6033. fn_name = "histc()"
  6034. if device_hint(input) == "cpu":
  6035. torch._check(
  6036. input.is_floating_point(),
  6037. lambda: f"\"histogram_cpu\" not implemented for '{input.dtype}'",
  6038. )
  6039. if device_hint(input) == "cuda" and input.is_floating_point():
  6040. utils.alert_not_deterministic("_histc_cuda with floating point input")
  6041. torch._check(
  6042. isinstance(bins, IntLike),
  6043. lambda: f"{fn_name}: argument 'bins' must be int, not {type(bins)}",
  6044. )
  6045. torch._check(bins > 0, lambda: f"{fn_name}: bins must be > 0, but got {bins}")
  6046. torch._check(
  6047. isinstance(min, Number),
  6048. lambda: f"{fn_name}: argument 'min' must be Number, not {type(min)}",
  6049. )
  6050. torch._check(
  6051. isinstance(max, Number),
  6052. lambda: f"{fn_name}: argument 'max' must be Number, not {type(max)}",
  6053. )
  6054. torch._check(max >= min, lambda: "{fn_name}: max must be larger than min")
  6055. return torch.empty(bins, device=input.device, dtype=input.dtype)
  6056. @register_meta(
  6057. [aten._upsample_bilinear2d_aa.default, aten._upsample_bicubic2d_aa.default]
  6058. )
  6059. def meta_upsample_bimode2d_aa(
  6060. input,
  6061. output_size,
  6062. align_corners,
  6063. scales_h=None,
  6064. scales_w=None,
  6065. ):
  6066. full_output_size = upsample_common_check(
  6067. input.size(), output_size, num_spatial_dims=2
  6068. )
  6069. torch._check(
  6070. input.numel() != 0 or all(size > 0 for size in input.size()[1:]),
  6071. lambda: f"Non-empty 4D data tensor expected but got a tensor with sizes {input.size()}",
  6072. )
  6073. return input.new_empty(full_output_size).to(
  6074. memory_format=utils.suggest_memory_format(input)
  6075. )
  6076. @register_meta([aten._upsample_bilinear2d_aa_backward.default])
  6077. def meta_upsample_bimode2d_aa_backward(
  6078. grad_output,
  6079. output_size,
  6080. input_size,
  6081. align_corners,
  6082. scales_h=None,
  6083. scales_w=None,
  6084. ):
  6085. full_output_size = upsample_common_check(
  6086. input_size, output_size, num_spatial_dims=2
  6087. )
  6088. torch._check(
  6089. grad_output.ndim == 4,
  6090. lambda: f"Expected grad_output to be a tensor of dimension 4 but got: dimension {grad_output.ndim}",
  6091. )
  6092. for i in range(4):
  6093. torch._check(
  6094. grad_output.shape[i] == full_output_size[i],
  6095. lambda: f"""
  6096. Expected grad_output to have the same shape as output; output.size({i}) = {full_output_size[i]}
  6097. but got grad_output_size({i}) = {grad_output.size(i)}""",
  6098. )
  6099. return grad_output.new_empty(input_size).to(
  6100. memory_format=utils.suggest_memory_format(grad_output)
  6101. )
  6102. # From aten/src/ATen/native/cuda/AmpKernels.cu
  6103. @register_meta(aten._amp_foreach_non_finite_check_and_unscale_.default)
  6104. def _amp_foreach_non_finite_check_and_unscale_(self, found_inf, inv_scale):
  6105. torch._check(
  6106. found_inf.numel() == 1, lambda: "found_inf must be a 1-element tensor."
  6107. )
  6108. torch._check(
  6109. inv_scale.numel() == 1, lambda: "inv_scale must be a 1-element tensor."
  6110. )
  6111. torch._check(
  6112. found_inf.dtype.is_floating_point,
  6113. lambda: "found_inf must be a float tensor.",
  6114. )
  6115. torch._check(
  6116. inv_scale.dtype.is_floating_point,
  6117. lambda: "inv_scale must be a float tensor.",
  6118. )
  6119. # From aten/src/ATen/native/UnaryOps.cpp
  6120. @register_meta([aten.nan_to_num.default, aten.nan_to_num.out])
  6121. @out_wrapper()
  6122. def nan_to_num(self, nan=None, posinf=None, neginf=None):
  6123. return torch.empty_like(self)
  6124. @register_meta(torch.ops.aten.transpose_)
  6125. def transpose_(self, dim0, dim1):
  6126. assert self.layout not in {
  6127. torch.sparse_csr,
  6128. torch.sparse_csc,
  6129. torch.sparse_bsr,
  6130. torch.sparse_bsc,
  6131. }, (
  6132. f"torch.transpose_: in-place transposition is not supported for {self.layout} layout"
  6133. )
  6134. ndims = self.ndim
  6135. dim0 = maybe_wrap_dim(dim0, ndims)
  6136. dim1 = maybe_wrap_dim(dim1, ndims)
  6137. if dim0 == dim1:
  6138. return self
  6139. size = list(self.size())
  6140. stride = list(self.stride())
  6141. stride[dim0], stride[dim1] = stride[dim1], stride[dim0]
  6142. size[dim0], size[dim1] = size[dim1], size[dim0]
  6143. self.as_strided_(size, stride)
  6144. return self
  6145. @register_meta(torch.ops.aten.t_)
  6146. def t_(self):
  6147. ndims = self.ndim
  6148. if self.is_sparse:
  6149. sparse_dim = self.sparse_dim()
  6150. dense_dim = self.dense_dim()
  6151. assert sparse_dim <= 2 and dense_dim == 0, (
  6152. f"t_ expects a tensor with <= 2 sparse and 0 dense dimensions, "
  6153. f"but got {sparse_dim} sparse and {dense_dim} dense dimensions"
  6154. )
  6155. else:
  6156. assert self.dim() <= 2, (
  6157. f"t_ expects a tensor with <= 2 dimensions, but self is {ndims}D"
  6158. )
  6159. return transpose_(self, 0, 0 if ndims < 2 else 1)
  6160. @register_meta(aten.searchsorted)
  6161. @out_wrapper()
  6162. def meta_searchsorted(
  6163. sorted_sequence,
  6164. self,
  6165. *,
  6166. out_int32=False,
  6167. right=False,
  6168. side=None,
  6169. sorter=None,
  6170. ):
  6171. # If the sorted_sequence is not one-dimensional, its shape must match that of values
  6172. # in all but the last dimension.
  6173. torch._check(
  6174. len(sorted_sequence.shape) <= 1
  6175. or sorted_sequence.shape[:-1] == self.shape[:-1],
  6176. lambda: (
  6177. "torch.searchsorted(): boundaries tensor should be 1 dimension or the "
  6178. "first N-1 dimensions of boundaries tensor and input value tensor must "
  6179. f"match, but we got boundaries tensor {list(sorted_sequence.shape)} and "
  6180. f"input value tensor {list(self.shape)}"
  6181. ),
  6182. )
  6183. # If a sorter array is provided, its dimensions must exactly match sorted_sequence.
  6184. torch._check(
  6185. sorter is None or sorted_sequence.shape == sorter.shape,
  6186. lambda: (
  6187. "torch.searchsorted(): boundary and sorter must have the same size, but "
  6188. f"got boundary tensor {list(sorted_sequence.shape)} and got sorter tensor "
  6189. f"{list(sorter.shape) if sorter is not None else []}"
  6190. ),
  6191. )
  6192. # Per the docs, if side == "left" and right is True, we error.
  6193. torch._check(
  6194. side != "left" or not right,
  6195. "torch.searchsorted(): side and right can't be set to opposites, got side of "
  6196. "left while right was True",
  6197. )
  6198. dtype = torch.int32 if out_int32 else torch.int64
  6199. if isinstance(self, torch.Tensor):
  6200. return torch.empty_like(
  6201. self, dtype=dtype, memory_format=torch.contiguous_format
  6202. )
  6203. else: # Scalar
  6204. return torch.empty((), dtype=dtype, device=sorted_sequence.device)
  6205. def _check_for_unsupported_isin_dtype(dtype):
  6206. torch._check(
  6207. dtype not in (torch.bool, torch.complex128, torch.complex64),
  6208. lambda: f"Unsupported input type encountered for isin(): {dtype}",
  6209. )
  6210. @register_meta(aten.embedding_dense_backward)
  6211. def meta_embedding_dense_backward(
  6212. grad_output,
  6213. indices,
  6214. num_weights,
  6215. padding_idx,
  6216. scale_grad_by_freq,
  6217. ):
  6218. grad_weight = grad_output.new_empty((num_weights, grad_output.size(-1)))
  6219. return grad_weight
  6220. @register_meta(aten._embedding_bag_backward)
  6221. def meta_embedding_bag_backward(
  6222. grad,
  6223. indices,
  6224. offsets,
  6225. offset2bag,
  6226. bag_size,
  6227. maximum_indices,
  6228. num_weights,
  6229. scale_grad_by_freq,
  6230. mode,
  6231. sparse,
  6232. per_sample_weights,
  6233. padding_idx=-1,
  6234. ):
  6235. if sparse:
  6236. return aten._embedding_bag_sparse_backward(
  6237. grad,
  6238. indices,
  6239. offsets,
  6240. offset2bag,
  6241. bag_size,
  6242. num_weights,
  6243. scale_grad_by_freq,
  6244. mode,
  6245. per_sample_weights,
  6246. padding_idx,
  6247. )
  6248. else:
  6249. return meta_embedding_bag_dense_backward(
  6250. grad,
  6251. indices,
  6252. offset2bag,
  6253. bag_size,
  6254. maximum_indices,
  6255. num_weights,
  6256. scale_grad_by_freq,
  6257. mode,
  6258. per_sample_weights,
  6259. padding_idx,
  6260. )
  6261. @register_meta(aten._embedding_bag_dense_backward)
  6262. def meta_embedding_bag_dense_backward(
  6263. grad,
  6264. indices,
  6265. offset2bag,
  6266. bag_size,
  6267. maximum_indices,
  6268. num_weights,
  6269. scale_grad_by_freq,
  6270. mode,
  6271. per_sample_weights,
  6272. padding_idx=-1,
  6273. ):
  6274. torch._check(
  6275. grad.dtype in [torch.float16, torch.bfloat16, torch.float32, torch.float64],
  6276. lambda: f"Unsupported input type encountered: {grad.dtype}",
  6277. )
  6278. if mode == MODE_MAX:
  6279. torch._check(maximum_indices is not None)
  6280. index_grad_weight = grad.new_empty((num_weights, grad.size(1)))
  6281. return index_grad_weight
  6282. @register_meta(aten._embedding_bag_per_sample_weights_backward)
  6283. def meta_embedding_bag_per_sample_weights_backward(
  6284. grad,
  6285. weight,
  6286. indices,
  6287. offsets,
  6288. offset2bag,
  6289. mode,
  6290. padding_idx=-1,
  6291. ):
  6292. embedding_features = grad.size(1)
  6293. torch._check(
  6294. mode == MODE_SUM,
  6295. "embedding_bag_backward: per_sample_weights only supported for mode='sum'",
  6296. )
  6297. torch._check(grad.dim() == 2)
  6298. torch._check(indices.dim() == 1)
  6299. num_samples = indices.size(0)
  6300. torch._check(weight.dim() == 2)
  6301. torch._check(weight.size(1) == embedding_features)
  6302. output = grad.new_empty((num_samples,))
  6303. return output
  6304. @register_meta(aten.isin)
  6305. @out_wrapper()
  6306. def meta_isin(elements, test_elements, *, assume_unique=False, invert=False):
  6307. torch._check(
  6308. isinstance(elements, Tensor) or isinstance(test_elements, Tensor),
  6309. lambda: "At least one of elements and test_elements must be a Tensor.",
  6310. )
  6311. if not isinstance(elements, Tensor):
  6312. elements = torch.tensor(elements, device=test_elements.device)
  6313. if not isinstance(test_elements, Tensor):
  6314. test_elements = torch.tensor(test_elements, device=elements.device)
  6315. _check_for_unsupported_isin_dtype(elements.dtype)
  6316. _check_for_unsupported_isin_dtype(test_elements.dtype)
  6317. return torch.empty_like(elements, dtype=torch.bool)
  6318. @register_meta(aten.polygamma)
  6319. @out_wrapper()
  6320. def meta_polygamma(n: int, self: Tensor) -> Tensor:
  6321. torch._check(n >= 0, lambda: "polygamma(n, x) does not support negative n.")
  6322. _, result_dtype = elementwise_dtypes(
  6323. self,
  6324. type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
  6325. )
  6326. return torch.empty_like(self, dtype=result_dtype)
  6327. @register_meta(aten._local_scalar_dense)
  6328. def meta_local_scalar_dense(self: Tensor):
  6329. raise RuntimeError("Tensor.item() cannot be called on meta tensors")
  6330. @register_meta(aten.silu)
  6331. @out_wrapper(exact_dtype=True)
  6332. def silu(self: Tensor) -> Tensor:
  6333. return torch.empty_like(self)
  6334. @register_meta(aten.sigmoid)
  6335. @out_wrapper()
  6336. def sigmoid(self: Tensor) -> Tensor:
  6337. _, result_dtype = elementwise_dtypes(
  6338. self,
  6339. type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT,
  6340. )
  6341. return torch.empty_like(self, dtype=result_dtype)
  6342. def _create_grouped_mm_output_tensor(mat1, mat2, offs, out_dtype):
  6343. mat1_is_2d = mat1.dim() == 2
  6344. mat2_is_2d = mat2.dim() == 2
  6345. if mat1_is_2d:
  6346. if mat2_is_2d:
  6347. out_size = [offs.size(0), mat1.size(0), mat2.size(1)]
  6348. else:
  6349. torch._check(
  6350. offs.size(0) == mat2.size(0), lambda: "matrix batch sizes have to match"
  6351. )
  6352. out_size = [mat1.size(0), mat2.size(-1)]
  6353. else:
  6354. if mat2_is_2d:
  6355. torch._check(
  6356. offs.size(0) == mat1.size(0), lambda: "matrix batch sizes have to match"
  6357. )
  6358. out_size = [mat1.size(1), mat2.size(1)]
  6359. else:
  6360. # regular bmm
  6361. torch._check(
  6362. mat1.size(0) == mat2.size(0), lambda: "batched dimension has to match"
  6363. )
  6364. out_size = [mat1.size(0), mat1.size(1), mat2.size(-1)]
  6365. out_dtype = out_dtype or mat1.dtype
  6366. if torch.version.cuda:
  6367. alignment = 16 // out_dtype.itemsize
  6368. size_padded = (out_size[-1] + alignment - 1) // alignment * alignment
  6369. if mat1_is_2d == mat2_is_2d:
  6370. out_stride = [out_size[1] * size_padded, size_padded, 1]
  6371. else:
  6372. out_stride = [size_padded, 1]
  6373. out = torch.empty_strided(
  6374. out_size, out_stride, dtype=out_dtype, device=mat1.device
  6375. )
  6376. else:
  6377. out = torch.empty(out_size, dtype=out_dtype, device=mat1.device)
  6378. return out
  6379. def _meta_grouped_mm_common(
  6380. mat_a: Tensor,
  6381. mat_b: Tensor,
  6382. scale_a: Optional[torch.Tensor],
  6383. scale_b: Optional[torch.Tensor],
  6384. offs: Optional[Tensor] = None,
  6385. bias: Optional[Tensor] = None,
  6386. scale_result: Optional[torch.Tensor] = None,
  6387. out_dtype: Optional[torch.dtype] = None,
  6388. use_fast_accum: bool = False,
  6389. ):
  6390. torch._check(
  6391. (scale_a is None) == (scale_b is None),
  6392. lambda: "Either both scale factors are given, or none",
  6393. )
  6394. scaled = scale_a is not None and scale_b is not None
  6395. # Implementing all the checks from
  6396. # _grouped_mm_cuda()/_scaled_grouped_mm_cuda() code in
  6397. # aten/src/ATen/native/cuda/Blas.cpp.
  6398. if scaled:
  6399. fp8_dtype = torch.float8_e4m3fnuz if torch.version.hip else torch.float8_e4m3fn
  6400. torch._check(
  6401. mat_a.dtype == fp8_dtype and mat_b.dtype == fp8_dtype,
  6402. lambda: f"Expected inputs of E4M3 FP8 type but got mat_a.dtype={mat_a.dtype} and mat_b.dtype={mat_b.dtype}.", # noqa: B950
  6403. )
  6404. else:
  6405. torch._check(
  6406. mat_a.dtype == torch.bfloat16 and mat_b.dtype == torch.bfloat16,
  6407. lambda: f"Expected inputs of BF16 type but got mat_a.dtype={mat_a.dtype} and mat_b.dtype={mat_b.dtype}.", # noqa: B950
  6408. )
  6409. torch._check(
  6410. mat_a.dim() in [2, 3] and mat_b.dim() in [2, 3],
  6411. lambda: f"Multiplicands must be 2D or 3D but got mat_a.dim()={mat_a.dim()} and mat_b.dim()={mat_b.dim()}", # noqa: B950
  6412. )
  6413. mat_a_is_2d = mat_a.dim() == 2
  6414. mat_b_is_2d = mat_b.dim() == 2
  6415. if not mat_a_is_2d or not mat_b_is_2d:
  6416. torch._check(
  6417. mat_a.size(-1) == mat_b.size(-2),
  6418. "contraction dimension of mat_a and mat_b must match",
  6419. )
  6420. if scaled:
  6421. def is_row_major(mat):
  6422. mat_stride = mat.stride()
  6423. return mat_stride[-2] > 1 and mat_stride[-1] == 1
  6424. def is_col_major(mat):
  6425. mat_stride = mat.stride()
  6426. return mat_stride[-2] == 1 and mat_stride[-1] > 1
  6427. torch._check(
  6428. is_row_major(mat_a),
  6429. lambda: f"Expected mat_a tensor to be row major in the last two dimensions, got strides {mat_a.stride()[-2:]}", # noqa: B950
  6430. )
  6431. torch._check(
  6432. is_col_major(mat_b),
  6433. lambda: f"Expected mat_b tensor to be column major in the last two dimensions, got strides {mat_b.stride()[-2:]}", # noqa: B950
  6434. )
  6435. def check_valid_strides(mat_name, mat):
  6436. end_dim = mat.dim() - 1
  6437. alignment = 16 // mat.element_size()
  6438. mat_stride = mat.stride()
  6439. if mat_stride[end_dim - 1] == 1 and mat_stride[end_dim] >= max(
  6440. 1, mat.shape[end_dim - 1]
  6441. ):
  6442. torch._check(
  6443. mat_stride[end_dim] % alignment == 0,
  6444. lambda: f"Expected {mat_name} stride along {end_dim} dim to be multiple of 16 bytes, got {mat_stride[end_dim]}.", # noqa: B950
  6445. )
  6446. elif mat_stride[end_dim] == 1 and mat_stride[end_dim - 1] >= max(
  6447. 1, mat.shape[end_dim]
  6448. ):
  6449. torch._check(
  6450. mat_stride[end_dim - 1] % alignment == 0,
  6451. lambda: f"Expected {mat_name} stride along {end_dim - 1} dim to be multiple of 16 bytes, got {mat_stride[end_dim - 1]}.", # noqa: B950
  6452. )
  6453. else:
  6454. torch._check(
  6455. False,
  6456. lambda: f"Invalid strides/sizes, got {mat_stride} for strides and {mat.shape} for sizes.", # noqa: B950
  6457. )
  6458. check_valid_strides("mat_a", mat_a)
  6459. check_valid_strides("mat_b", mat_b)
  6460. if scale_a is not None and scale_b is not None:
  6461. torch._check(
  6462. (scale_a.dtype == torch.float32 and scale_b.dtype == torch.float32)
  6463. or (
  6464. scale_a.dtype == torch.float8_e8m0fnu
  6465. and scale_b.dtype == torch.float8_e8m0fnu
  6466. ),
  6467. lambda: f"For FP8 scales must both be float32, or for MXFP8 both scales must be float8_e8m0fnu. Got scale_a.dtype={scale_a.dtype} and scale_b.dtype={scale_b.dtype}.", # noqa: B950
  6468. )
  6469. is_mxfp8 = (
  6470. scale_a.dtype == torch.float8_e8m0fnu
  6471. and scale_b.dtype == torch.float8_e8m0fnu
  6472. )
  6473. def round_up(x, y):
  6474. """Rounds up x to nearest multiple of y"""
  6475. return ((x + y - 1) // y) * y
  6476. def check_scale(scale_name, scale, mat, scaled_dim, scale_multiplier=1):
  6477. if mat.dim() == 2:
  6478. torch._check(
  6479. scale.is_contiguous(),
  6480. lambda: f"Expected {scale_name} to be contiguous.",
  6481. )
  6482. # For MXFP8, 2d tensors have variable size groups represented as subtensors,
  6483. # that are converted to blocked padded format individually. At compile time we don't know
  6484. # the group sizes yet, so we don't know the expect size of the blocked format scale.
  6485. # This limits what we can check here.
  6486. if is_mxfp8:
  6487. torch._check(
  6488. scale.dim() == mat.dim(),
  6489. lambda: f"For MXFP8, scale must have same number of dimensions as target tensor, but {scale_name} has mat.ndim={mat.ndim} and scale.ndim={scale.ndim}", # noqa: B950
  6490. )
  6491. else:
  6492. torch._check(
  6493. scale.dim() == 1,
  6494. lambda: f"Expected {scale_name} to be 1D tensor, but got {scale.dim()}D tensor.",
  6495. )
  6496. torch._check(
  6497. scale.shape[0] == mat.shape[scaled_dim] * scale_multiplier,
  6498. lambda: f"Expected {scale_name} to have {mat.shape[scaled_dim] * scale_multiplier} elements, got {scale.shape[0]} elements.", # noqa: B950
  6499. )
  6500. else:
  6501. torch._check(
  6502. scale.stride(-1) == 1,
  6503. lambda: f"Expected {scale_name} to be contiguous in the last dimension.",
  6504. )
  6505. torch._check(
  6506. scale.shape[0] == mat.shape[0],
  6507. lambda: f"Expected {scale_name} batch dimension to be {mat.shape[0]}, got {scale.shape[0]}.",
  6508. )
  6509. # For MXFP8, 3d tensors have static 'groups' (stack of 2d tensors) so we can know the expected blocked
  6510. # scale sizes at compile time.
  6511. if is_mxfp8:
  6512. torch._check(
  6513. mat.ndim == scale.ndim,
  6514. lambda: f"For MXFP8, scale should have same number of dimensions as target tensor, but {scale_name} has mat.ndim={mat.ndim} and scale.ndim={scale.ndim}", # noqa: B950
  6515. )
  6516. # TODO: This logic only holds for RHS tensor in 2d-3d case.
  6517. # We'll need to update it to handle LHS 3d tensor in 3d-2d and 3d-3d cases.
  6518. G, K, N = scale.shape
  6519. block_size = 32
  6520. blocked_K = round_up(K / block_size, 4)
  6521. blocked_N = round_up(N, 128)
  6522. torch._check(
  6523. mat.shape[-2] == blocked_K and mat.shape[-1] == blocked_N,
  6524. lambda: f"For MXFP8, expected mat.shape={mat.shape} to have scale shape of ({G},{blocked_K},{blocked_N}), but got {scale.shape}", # noqa: B950
  6525. )
  6526. else:
  6527. torch._check(
  6528. scale.dim() == 2,
  6529. lambda: f"Expected {scale_name} to be 2D tensor, but got {scale.dim()}D tensor.",
  6530. )
  6531. torch._check(
  6532. scale.shape[1] == mat.shape[1 + scaled_dim],
  6533. lambda: f"Expected {scale_name} non-batch dimension to be {mat.shape[1 + scaled_dim]}, got {scale.shape[1]}.", # noqa: B950
  6534. )
  6535. scale_multiplier = (
  6536. offs.shape[0] if offs is not None and mat_a_is_2d and mat_b_is_2d else 1
  6537. )
  6538. check_scale("scale_a", scale_a, mat_a, 0, scale_multiplier)
  6539. check_scale("scale_b", scale_b, mat_b, 1, scale_multiplier)
  6540. torch._check(
  6541. scale_result is None,
  6542. lambda: "Scale result tensor provided, but it is not supported yet.",
  6543. )
  6544. if mat_a_is_2d or mat_b_is_2d:
  6545. torch._check(
  6546. offs is not None,
  6547. lambda: f"Offsets tensor not provided, but is needed for {mat_a.dim()}D/{mat_b.dim()}D multiplicand layouts.",
  6548. )
  6549. if offs is not None: # to silence Mypy
  6550. torch._check(
  6551. offs.dim() == 1,
  6552. lambda: f"Offsets tensor must be 1D, but got offs.dim()={offs.dim()}.",
  6553. )
  6554. torch._check(
  6555. offs.dtype == torch.int32,
  6556. lambda: f"Offsets tensor must be integer (int32) tensor, but got {offs.dtype}.",
  6557. )
  6558. else:
  6559. torch._check(
  6560. offs is None,
  6561. lambda: "Offsets tensor provided, but is not needed for 3D/3D multiplicand layouts.",
  6562. )
  6563. torch._check(
  6564. bias is None,
  6565. lambda: "Bias tensor provided, but it is not supported yet.",
  6566. )
  6567. torch._check(
  6568. out_dtype is None or out_dtype == torch.bfloat16,
  6569. lambda: "If output dtype provided, it must be torch.bfloat16.",
  6570. )
  6571. return _create_grouped_mm_output_tensor(mat_a, mat_b, offs, out_dtype)
  6572. @register_meta(aten._grouped_mm)
  6573. @out_wrapper()
  6574. def meta_grouped_mm(
  6575. mat_a: Tensor,
  6576. mat_b: Tensor,
  6577. offs: Optional[Tensor] = None,
  6578. bias: Optional[Tensor] = None,
  6579. out_dtype: Optional[torch.dtype] = None,
  6580. ) -> Tensor:
  6581. return _meta_grouped_mm_common(
  6582. mat_a,
  6583. mat_b,
  6584. scale_a=None,
  6585. scale_b=None,
  6586. offs=offs,
  6587. bias=bias,
  6588. scale_result=None,
  6589. out_dtype=out_dtype,
  6590. )
  6591. @register_meta([aten._scaled_grouped_mm])
  6592. def meta_scaled_grouped_mm(
  6593. mat_a: torch.Tensor,
  6594. mat_b: torch.Tensor,
  6595. scale_a: torch.Tensor,
  6596. scale_b: torch.Tensor,
  6597. offs: Optional[torch.Tensor] = None,
  6598. bias: Optional[torch.Tensor] = None,
  6599. scale_result: Optional[torch.Tensor] = None,
  6600. out_dtype: Optional[torch.dtype] = None,
  6601. use_fast_accum: bool = False,
  6602. ):
  6603. return _meta_grouped_mm_common(
  6604. mat_a,
  6605. mat_b,
  6606. scale_a=scale_a,
  6607. scale_b=scale_b,
  6608. offs=offs,
  6609. bias=bias,
  6610. scale_result=scale_result,
  6611. out_dtype=out_dtype,
  6612. use_fast_accum=use_fast_accum,
  6613. )
  6614. @register_meta(aten._softmax)
  6615. @out_wrapper()
  6616. def softmax(x: Tensor, dim: int, half_to_float: bool) -> Tensor:
  6617. if half_to_float:
  6618. assert x.dtype == torch.half
  6619. computation_dtype, result_dtype = utils.elementwise_dtypes(
  6620. x, type_promotion_kind=utils.ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
  6621. )
  6622. result_dtype = result_dtype if not half_to_float else computation_dtype
  6623. res = torch.empty_like(x, dtype=result_dtype, memory_format=torch.contiguous_format)
  6624. return res
  6625. @register_meta(aten.constant_pad_nd)
  6626. @out_wrapper()
  6627. def _constant_pad_nd_meta(input, pad, value=0):
  6628. # same checks as decomposition in torch/_refs/__init__.py:constant_pad_nd()
  6629. torch._check(
  6630. len(pad) % 2 == 0,
  6631. lambda: f"Length of pad must be even but instead it equals {len(pad)}",
  6632. )
  6633. input_sizes = input.shape
  6634. l_inp = len(input_sizes)
  6635. l_pad = len(pad) // 2
  6636. l_diff = l_inp - l_pad
  6637. torch._check(
  6638. l_inp >= l_pad,
  6639. lambda: "Length of pad should be no more than twice the number of "
  6640. f"dimensions of the input. Pad length is {len(pad)} while the input has "
  6641. f"{l_inp} dimensions.",
  6642. )
  6643. if all(isinstance(p, utils.IntWithoutSymInt) and p <= 0 for p in pad):
  6644. c_input = input
  6645. for i in range(l_diff, l_inp):
  6646. pad_idx = 2 * (l_inp - i - 1)
  6647. if pad[pad_idx] < 0:
  6648. c_input = c_input.narrow(
  6649. i, -pad[pad_idx], c_input.shape[i] + pad[pad_idx]
  6650. )
  6651. if pad[pad_idx + 1] < 0:
  6652. c_input = c_input.narrow(i, 0, c_input.shape[i] + pad[pad_idx + 1])
  6653. return c_input.clone()
  6654. new_shape = list(input_sizes[:l_diff])
  6655. for i in range(l_pad):
  6656. pad_idx = len(pad) - ((i + 1) * 2)
  6657. new_dim = input_sizes[l_diff + i] + pad[pad_idx] + pad[pad_idx + 1]
  6658. torch._check(
  6659. new_dim >= 0,
  6660. lambda: f"The input size {input_sizes[l_diff + i]}, plus negative padding "
  6661. f"{pad[pad_idx]} and {pad[pad_idx + 1]} resulted in a negative output size, "
  6662. f"which is invalid. Check dimension {l_diff + i} of your input.",
  6663. )
  6664. new_shape.append(new_dim)
  6665. return torch.empty(
  6666. new_shape,
  6667. dtype=input.dtype,
  6668. device=input.device,
  6669. requires_grad=input.requires_grad,
  6670. memory_format=suggest_memory_format(input),
  6671. )
  6672. @register_meta(aten.embedding)
  6673. @out_wrapper()
  6674. def embedding(
  6675. weight: Tensor,
  6676. indices: Tensor,
  6677. padding_idx: int = -1,
  6678. scale_grad_by_freq: bool = False,
  6679. sparse: bool = False,
  6680. ) -> Tensor:
  6681. assert weight.dim() == 2, "'weight' must be 2-D"
  6682. weight_shape = weight.shape
  6683. indices_shape = indices.shape
  6684. if indices.ndim == 0:
  6685. out_shape: tuple[int, ...] = (weight_shape[1],)
  6686. elif indices.ndim == 1:
  6687. out_shape = (indices_shape[0], weight_shape[1])
  6688. else:
  6689. out_shape = (*indices_shape, weight_shape[1])
  6690. out_dtype = weight.dtype
  6691. return weight.new_empty(out_shape, dtype=out_dtype)
  6692. @register_meta(aten._jagged_to_padded_dense_forward.default)
  6693. def meta__jagged_to_padded_dense_forward(
  6694. values: Tensor,
  6695. offsets: list[Tensor],
  6696. max_lengths: list[int],
  6697. padding_value: float = 0.0,
  6698. ):
  6699. # only one jagged dim is supported for now
  6700. assert len(offsets) == 1
  6701. assert len(max_lengths) == 1
  6702. B = offsets[0].shape[0] - 1
  6703. S = max_lengths[0]
  6704. output_shape = (B, S, *values.shape[1:])
  6705. return values.new_empty(output_shape)
  6706. def _create_unary_float_meta_func(func):
  6707. @register_meta(func)
  6708. @out_wrapper()
  6709. def _f(x):
  6710. return elementwise_meta(
  6711. x, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT
  6712. )
  6713. return _f
  6714. def _create_binary_float_meta_func(func):
  6715. @register_meta(func)
  6716. @out_wrapper()
  6717. def _f(x, y):
  6718. return elementwise_meta(
  6719. x, y, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT
  6720. )
  6721. return _f
  6722. _create_unary_float_meta_func(aten.special_airy_ai)
  6723. _create_unary_float_meta_func(aten.special_bessel_y0)
  6724. _create_unary_float_meta_func(aten.special_bessel_y1)
  6725. _create_unary_float_meta_func(aten.special_modified_bessel_i0)
  6726. _create_unary_float_meta_func(aten.special_modified_bessel_i1)
  6727. _create_unary_float_meta_func(aten.special_modified_bessel_k0)
  6728. _create_unary_float_meta_func(aten.special_modified_bessel_k1)
  6729. _create_unary_float_meta_func(aten.special_scaled_modified_bessel_k0)
  6730. _create_unary_float_meta_func(aten.special_scaled_modified_bessel_k1)
  6731. _create_binary_float_meta_func(aten.special_chebyshev_polynomial_t)
  6732. _create_binary_float_meta_func(aten.special_chebyshev_polynomial_u)
  6733. _create_binary_float_meta_func(aten.special_chebyshev_polynomial_v)
  6734. _create_binary_float_meta_func(aten.special_chebyshev_polynomial_w)
  6735. _create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_t)
  6736. _create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_u)
  6737. _create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_v)
  6738. _create_binary_float_meta_func(aten.special_shifted_chebyshev_polynomial_w)
  6739. _create_binary_float_meta_func(aten.special_hermite_polynomial_h)
  6740. _create_binary_float_meta_func(aten.special_hermite_polynomial_he)
  6741. _create_binary_float_meta_func(aten.special_laguerre_polynomial_l)
  6742. _create_binary_float_meta_func(aten.special_legendre_polynomial_p)
  6743. def _register_inplace_meta(fn):
  6744. @wraps(fn)
  6745. def _fn(self, *args, **kwargs):
  6746. out = fn(self, *args, **kwargs)
  6747. check_inplace_broadcast(self.shape, out.shape)
  6748. return self
  6749. inplace_name = f"{fn.__name__}_"
  6750. _fn.__name__ = inplace_name
  6751. _fn = register_meta(getattr(aten, inplace_name))(_fn) # type: ignore[assignment]
  6752. return _fn
  6753. @register_meta(aten.lerp)
  6754. @out_wrapper()
  6755. def lerp(start, end, weight):
  6756. torch._check(
  6757. start.dtype == end.dtype,
  6758. lambda: f"expected dtype {start.dtype} for `end`, but got dtype {end.dtype}",
  6759. )
  6760. args = [start, end]
  6761. if isinstance(weight, TensorLike):
  6762. if weight.ndim != 0:
  6763. torch._check(
  6764. start.dtype == weight.dtype,
  6765. lambda: f"expected dtype {start.dtype} for `weight`, but got dtype {weight.dtype}",
  6766. )
  6767. args.append(weight)
  6768. return elementwise_meta(
  6769. *args, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
  6770. )
  6771. @register_meta(aten.addcmul)
  6772. @out_wrapper()
  6773. def addcmul(input, tensor1, tensor2, *, value=1):
  6774. return elementwise_meta(
  6775. input, tensor1, tensor2, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
  6776. )
  6777. @register_meta(aten.addcdiv)
  6778. @out_wrapper()
  6779. def addcdiv(input, tensor1, tensor2, *, value=1):
  6780. torch._check(
  6781. not (
  6782. utils.is_integer_dtype(tensor1.dtype)
  6783. and utils.is_integer_dtype(tensor2.dtype)
  6784. ),
  6785. lambda: (
  6786. "Integer division with addcdiv is no longer supported, and in a future ",
  6787. "release addcdiv will perform a true division of tensor1 and tensor2. ",
  6788. "The historic addcdiv behavior can be implemented as ",
  6789. "(input + value * torch.trunc(tensor1 / tensor2)).to(input.dtype) ",
  6790. "for integer inputs and as ",
  6791. "(input + value * tensor1 / tensor2) for float inputs. ",
  6792. "The future addcdiv behavior is just the latter implementation: ",
  6793. "(input + value * tensor1 / tensor2), for all dtypes.",
  6794. ),
  6795. )
  6796. return elementwise_meta(
  6797. input, tensor1, tensor2, type_promotion=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT
  6798. )
  6799. lerp_ = _register_inplace_meta(aten.lerp)
  6800. addcmul_ = _register_inplace_meta(aten.addcmul)
  6801. addcdiv_ = _register_inplace_meta(aten.addcdiv)
  6802. # We must also trigger meta registrations from PrimTorch ref
  6803. # decompositions
  6804. import torch._refs
  6805. import torch._refs.nn.functional
  6806. import torch._refs.special
  6807. def activate_meta():
  6808. activate_meta_table = {}
  6809. # For a given op, we pick the most specific decomp function from
  6810. # global_decomp_table in the precedence order of meta > post_autograd > pre_autograd
  6811. for type in ["meta", "post_autograd", "pre_autograd"]:
  6812. registry = global_decomposition_table[type]
  6813. for opo in registry:
  6814. if opo not in activate_meta_table:
  6815. activate_meta_table[opo] = registry[opo]
  6816. for op_overload, fn in activate_meta_table.items():
  6817. # Don't register meta for HigherOrderOp's decomp.
  6818. # We can reconsider this in the future, but in general,
  6819. # the way you do a meta for a HigherOrderOp is different from
  6820. # OpOverload.
  6821. if isinstance(op_overload, torch._ops.HigherOrderOperator):
  6822. continue
  6823. assert isinstance(op_overload, OpOverload)
  6824. op_overload.py_impl(torch._C.DispatchKey.Meta)(fn)
  6825. if torch._C._dispatch_has_kernel_for_dispatch_key(
  6826. op_overload.name(), "CompositeImplicitAutograd"
  6827. ):
  6828. # Internally, we shouldn't be registering meta kernels for any operators that
  6829. # have CompositeImplicitAutograd kernels.
  6830. # Instead, we should be letting those decompositions run, and writing meta kernels
  6831. # only for the base operators.
  6832. if op_overload in global_decomposition_table["meta"]:
  6833. raise RuntimeError(
  6834. f"{op_overload} is a CompositeImplicitAutograd op, we shouldn't "
  6835. "register meta function for it. Instead, we should let the decomposition run and write "
  6836. "meta kernels for the base operators."
  6837. )
  6838. elif op_overload.is_view:
  6839. # Attempting to register a python meta kernel for a view operator.
  6840. # We shouldn't do this, because the output will report as not having aliased storages.
  6841. # All view ops have meta kernels in C++ today, so we should use those instead.
  6842. pass
  6843. elif (
  6844. op_overload.name()
  6845. in {
  6846. "aten::empty_strided", # causing infinite recursion, test_meta.py
  6847. "aten::clone", # causing infinite recursion
  6848. "aten::_to_copy", # causing infinite recursion, test_serialization.py -k test_tensor_subclass_getstate_overwrite # noqa: B950
  6849. "aten::copy_", # Exception not raised, test_torch.py -k test_storage_meta_errors_cpu_int64 # noqa: B950
  6850. "aten::constant_pad_nd", # requires_grad mismatch, test_ops.py -k test_fake_crossref_backward_amp_istft_cuda_float32 # noqa: B950
  6851. "aten::rot90", # requires_grad mismatch! test_ops.py -k test_fake_crossref_backward_amp_rot90_cuda_float32 # noqa: B950
  6852. "aten::as_strided_scatter", # requires_grad mismatch, test_ops.py -k test_fake_crossref_backward_no_amp_as_strided_scatter_cuda_float32 # noqa: B950
  6853. }
  6854. ):
  6855. pass
  6856. else:
  6857. if "mkldnn::" in op_overload.name():
  6858. _meta_lib_dont_use_me_use_register_meta_for_mkldnn.impl(op_overload, fn)
  6859. elif "mkl::" in op_overload.name():
  6860. _meta_lib_dont_use_me_use_register_meta_for_mkl.impl(op_overload, fn)
  6861. elif "onednn::" in op_overload.name():
  6862. _meta_lib_dont_use_me_use_register_meta_for_onednn.impl(op_overload, fn)
  6863. elif "quantized::" in op_overload.name():
  6864. _meta_lib_dont_use_me_use_register_meta_for_quantized.impl(
  6865. op_overload, fn
  6866. )
  6867. else:
  6868. _meta_lib_dont_use_me_use_register_meta.impl(op_overload, fn)
  6869. activate_meta()