utils.py 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241
  1. """
  2. Utility functions and classes used throughout the TorchDynamo system.
  3. This module contains a collection of helper utilities used by various parts of Dynamo for:
  4. - Performance metrics collection and reporting
  5. - Compilation timing and debugging
  6. - Graph manipulation and tensor operations
  7. - Runtime guards and checks
  8. - Common data structure operations
  9. - Testing and development tools
  10. This is an internal module that provides shared functionality used across the Dynamo codebase.
  11. """
  12. from __future__ import annotations
  13. import atexit
  14. import collections
  15. import contextlib
  16. import copy
  17. import dataclasses
  18. import datetime
  19. import dis
  20. import enum
  21. import functools
  22. import gc
  23. import importlib
  24. import inspect
  25. import itertools
  26. import json
  27. import linecache
  28. import logging
  29. import math
  30. import operator
  31. import os
  32. import re
  33. import sys
  34. import textwrap
  35. import threading
  36. import time
  37. import traceback
  38. import types
  39. import typing
  40. import uuid
  41. import warnings
  42. import weakref
  43. from collections import Counter, OrderedDict
  44. from contextlib import AbstractContextManager, contextmanager
  45. from dataclasses import is_dataclass
  46. from functools import lru_cache
  47. from types import CodeType, MethodWrapperType
  48. from typing import (
  49. Any,
  50. cast,
  51. ClassVar,
  52. Generic,
  53. Literal,
  54. NoReturn,
  55. Optional,
  56. overload,
  57. TypeAlias,
  58. TypeGuard,
  59. TypeVar,
  60. Union,
  61. )
  62. from typing_extensions import ParamSpec, TypeIs
  63. import torch
  64. import torch._functorch.config
  65. import torch.fx.experimental.symbolic_shapes
  66. import torch.utils._pytree as pytree
  67. from torch import fx
  68. from torch._C import (
  69. _instruction_counter,
  70. _len_torch_function_stack,
  71. _pop_torch_function_stack,
  72. _push_on_torch_function_stack,
  73. )
  74. from torch._dispatch.python import enable_python_dispatcher
  75. from torch._dynamo.metrics_context import MetricsContext, RuntimeMetricsContext
  76. from torch._guards import CompileId, Source, TracingContext
  77. from torch._subclasses.meta_utils import is_sparse_compressed
  78. from torch._utils_internal import (
  79. justknobs_check,
  80. log_chromium_event_internal,
  81. log_compilation_event,
  82. record_chromium_event_internal,
  83. signpost_event,
  84. )
  85. from torch.fx._utils import _format_graph_code, lazy_format_graph_code
  86. from torch.monitor import _WaitCounter
  87. from torch.nn.modules.lazy import LazyModuleMixin
  88. from torch.utils._ordered_set import OrderedSet
  89. from torch.utils._python_dispatch import is_traceable_wrapper_subclass
  90. from torch.utils._triton import has_triton, has_triton_package
  91. from torch.utils.hooks import RemovableHandle
  92. from .graph_utils import _get_flat_args
  93. if typing.TYPE_CHECKING:
  94. from collections.abc import (
  95. Callable,
  96. Container,
  97. Generator,
  98. ItemsView,
  99. Iterable,
  100. Iterator,
  101. KeysView,
  102. Mapping,
  103. Sequence,
  104. ValuesView,
  105. )
  106. from torch._dynamo.bytecode_transformation import Instruction
  107. from torch._dynamo.replay_record import ExecutionRecord
  108. from torch._dynamo.symbolic_convert import (
  109. InstructionTranslator,
  110. InstructionTranslatorBase,
  111. )
  112. from torch._dynamo.variables.base import VariableTracker
  113. from torch._prims_common import DeviceLikeType
  114. from torch._subclasses import FakeTensorMode
  115. try:
  116. import numpy as np
  117. except ModuleNotFoundError:
  118. np = None # type: ignore[assignment]
  119. try:
  120. import torch._logging
  121. import torch._numpy as tnp
  122. from torch._guards import detect_fake_mode # noqa: F401
  123. from torch._logging import LazyString
  124. from . import config
  125. # NOTE: Make sure `NP_SUPPORTED_MODULES` and `NP_TO_TNP_MODULE` are in sync.
  126. if np:
  127. NP_SUPPORTED_MODULES: tuple[types.ModuleType, ...] = (
  128. np,
  129. np.fft,
  130. np.linalg,
  131. np.random,
  132. )
  133. NP_TO_TNP_MODULE = {
  134. np: tnp,
  135. np.fft: tnp.fft,
  136. np.linalg: tnp.linalg,
  137. np.random: tnp.random,
  138. }
  139. else:
  140. NP_SUPPORTED_MODULES = ()
  141. # pyrefly: ignore [implicit-any]
  142. NP_TO_TNP_MODULE = {}
  143. from torch._subclasses.fake_tensor import FakeTensor, is_fake, maybe_get_fake_mode
  144. except ImportError:
  145. pass
  146. T = TypeVar("T")
  147. R = TypeVar("R")
  148. _P = ParamSpec("_P")
  149. unpatched_nn_module_getattr = torch.nn.Module.__getattr__
  150. unpatched_nn_module_call = torch.nn.Module.__call__
  151. unpatched_nn_module_call_impl = torch.nn.Module._call_impl
  152. counters: collections.defaultdict[str, Counter[str]] = collections.defaultdict(
  153. collections.Counter
  154. )
  155. optimus_scuba_log: dict[str, Any] = {}
  156. troubleshooting_url = "https://docs.pytorch.org/docs/main/user_guide/torch_compiler/compile/programming_model.recompilation.html"
  157. nnmodule_doc_url = "https://docs.pytorch.org/docs/main/user_guide/torch_compiler/torch.compiler_nn_module.html"
  158. nnmodule_doc_url_msg = f"See {nnmodule_doc_url} for more information and limitations."
  159. log = logging.getLogger(__name__)
  160. # profiling compilation time by function
  161. compilation_time_metrics: dict[str, list[float]] = {}
  162. # This supports calculate_time_spent(), which reports cumulative times
  163. # across the process for any "phase" populated by dynamo_timed. Reset if
  164. # reset_frame_count() is called.
  165. cumulative_time_spent_ns: dict[str, float] = collections.defaultdict(float)
  166. timer_counter = itertools.count()
  167. # Abstraction on top of counters.
  168. class ReInplaceTrigger(enum.Enum):
  169. AUTO_FUNC_V1 = 1
  170. AUTO_FUNC_V2 = 2
  171. TRITON_OPS = 3
  172. class ReinplaceCounters:
  173. _values: collections.defaultdict[str, int] = collections.defaultdict(int)
  174. # Track sizes of known not re-inplaced tensors (exclude dynamic shapes).
  175. @classmethod
  176. def add_missed_bytes(cls, trigger: ReInplaceTrigger, bytes: int) -> None:
  177. if bytes != 0:
  178. cls._values[f"missed_bytes_{trigger.name}"] += bytes
  179. # Track number of not re-inplaced tensors.
  180. @classmethod
  181. def add_missed_opportunities(cls, trigger: ReInplaceTrigger, count: int) -> None:
  182. if count != 0:
  183. cls._values[f"missed_tensors_{trigger.name}"] += count
  184. @classmethod
  185. def clear(cls) -> None:
  186. cls._values.clear()
  187. @classmethod
  188. def get_total_missed(cls) -> int:
  189. sum = 0
  190. for trigger in ReInplaceTrigger:
  191. sum += cls._values.get(f"missed_tensors_{trigger.name}", 0)
  192. return sum
  193. @classmethod
  194. def get_total_missed_bytes(cls) -> int:
  195. sum = 0
  196. for trigger in ReInplaceTrigger:
  197. sum += cls._values.get(f"missed_bytes_{trigger.name}", 0)
  198. return sum
  199. @classmethod
  200. def log(cls) -> None:
  201. # if not empty log.
  202. if cls._values:
  203. signpost_event("inductor", "reinplace_counters", cls._values)
  204. def tabulate(
  205. rows: Union[list[tuple[str, Any]], list[list[Any]]],
  206. headers: Union[tuple[str, ...], list[str]],
  207. ) -> str:
  208. try:
  209. import tabulate
  210. return tabulate.tabulate(rows, headers=headers)
  211. except ImportError:
  212. return "\n".join(
  213. ", ".join(map(str, row)) for row in itertools.chain([headers], rows)
  214. )
  215. curr_frame = 0
  216. # Note: Called for you by dynamo - you almost never ever want to invoke this yourself.
  217. def increment_frame() -> None:
  218. global curr_frame
  219. curr_frame = curr_frame + 1
  220. # Note: Called for you by dynamo - you almost never ever want to invoke this yourself.
  221. def reset_frame_count() -> None:
  222. global curr_frame
  223. cumulative_time_spent_ns.clear()
  224. compilation_time_metrics.clear()
  225. curr_frame = 0
  226. _recompile_user_contexts: Optional[list[Callable[[], str]]] = None
  227. def register_hook_for_recompile_user_context(hook: Callable[[], str]) -> None:
  228. """
  229. Register a hook to be called when a recompile is triggered. The hook
  230. should return a string describing user contexts that are not available
  231. to the compiler, such as the current training epoch. This is useful for
  232. debugging and data analysis for recompile. For data retention purposes,
  233. the user context string is capped at 256 characters.
  234. """
  235. global _recompile_user_contexts
  236. if _recompile_user_contexts is None:
  237. _recompile_user_contexts = []
  238. _recompile_user_contexts.append(hook)
  239. def get_hook_for_recompile_user_context() -> Optional[list[Callable[[], str]]]:
  240. return _recompile_user_contexts
  241. def reset_recompile_user_contexts() -> None:
  242. """Clear any registered recompile user-context hooks (test helper)."""
  243. global _recompile_user_contexts
  244. _recompile_user_contexts = None
  245. op_count = 0
  246. def increment_op_count(cnt: int) -> None:
  247. global op_count
  248. op_count += cnt
  249. # Get the total time in seconds for each "phase"
  250. # For example, {'entire_frame_compile':8.574629999999999, 'backend_compile':5.26806}
  251. def calculate_time_spent() -> dict[str, float]:
  252. total_by_key = {}
  253. for phase, timing in cumulative_time_spent_ns.items():
  254. # pyrefly: ignore [unsupported-operation]
  255. total_by_key[phase] = timing / 1e9
  256. total_by_key["total_wall_time"] = total_by_key.get(
  257. "entire_frame_compile", 0
  258. ) + total_by_key.get("entire_backward_compile", 0)
  259. # pyrefly: ignore [bad-return]
  260. return total_by_key
  261. # Print a report of time spent so far
  262. # Ex:
  263. # TIMING:
  264. # entire_frame_compile:8.574629999999999
  265. # backend_compile:5.26806
  266. def print_time_report() -> None:
  267. total_by_key = calculate_time_spent()
  268. out = "TIMING:"
  269. for key, value in total_by_key.items():
  270. out = f"{out} {key}:{round(value, 5)}"
  271. print(out)
  272. # Use the following singleton to capture and log CompilationMetrics. Entering the context
  273. # manager allocates a new record to be logged when it exits. (You should not need to use
  274. # this directly unless you introduce a new code path where compilation metrics would be
  275. # gathered). While compiling, use the setters or timer in MetricsContext to update fields
  276. # in the current context. For example:
  277. #
  278. # To set a single field once (use overwrite=True to overwrite):
  279. # get_metrics_context().set("metric_name", value)
  280. #
  281. # To set multiple fields at once (use overwrite=True to overwrite):
  282. # get_metrics_context().update({"name1": val1, "name2": val2})
  283. #
  284. # To increment an integer field:
  285. # get_metrics_context().increment("metric_name", value)
  286. #
  287. # To record execution time, MetricsContext works with dynamo_timed:
  288. # def foo(...):
  289. # # Updates the "metric_us" field.
  290. # with dynamo_timed("metric", dynamo_compile_column_us="metric_us")
  291. # ...
  292. #
  293. _metrics_context_tls = threading.local()
  294. def get_metrics_context() -> MetricsContext:
  295. if not hasattr(_metrics_context_tls, "metrics_context"):
  296. _metrics_context_tls.metrics_context = MetricsContext(
  297. on_exit=record_compilation_metrics
  298. )
  299. return _metrics_context_tls.metrics_context
  300. def get_runtime_metrics_context() -> RuntimeMetricsContext:
  301. if not hasattr(_metrics_context_tls, "runtime_metrics_context"):
  302. _metrics_context_tls.runtime_metrics_context = RuntimeMetricsContext(
  303. on_exit=record_compilation_metrics
  304. )
  305. return _metrics_context_tls.runtime_metrics_context
  306. class CompileEventLogLevel(enum.Enum):
  307. """
  308. Enum that loosely corresponds with a "log level" of a given event.
  309. CHROMIUM_EVENT: Logs only to tlparse.
  310. COMPILE_EVENT: Logs to tlparse + PT2 Compile Events
  311. COMPILATION_METRIC: Logs to tlparse, PT2 Compile Events, and dynamo_compile
  312. """
  313. CHROMIUM = 1
  314. PT2_COMPILE = 2
  315. COMPILATION_METRIC = 3
  316. class CompileEventLogger:
  317. """
  318. Helper class for representing adding metadata(i.e. columns) to various compile events.
  319. Use CompileEventLogger to add event data to:
  320. - Chromium events
  321. - PT2 Compile Events
  322. - CompilationMetrics
  323. This should be used in conjunction with dynamo_timed() and metrics contexts, which create
  324. timed spans and events. CompileEventLogger uses three log levels (described in CompileEventLogLevel),
  325. where each log level logs to all sources below it in the hierarchy.
  326. Example usages:
  327. - I want to log to an existing chromium event within dynamo timed:
  328. with dynamo_timed("my_event"):
  329. CompileEventLogger.chromium("my_event", foo=bar)
  330. - I want to log my event to both chromium + pt2_compile_events:
  331. with dynamo_timed("my_event", log_pt2_compile_event=True):
  332. CompileEventLogger.pt2_compile("my_event", foo=bar)
  333. - I want to add information to dynamo events and dynamo_compile
  334. CompileEventLogger.compilation_metric(foo=bar)
  335. """
  336. @staticmethod
  337. def log_instant_event(
  338. event_name: str,
  339. metadata: dict[str, Any],
  340. time_ns: Optional[int] = None,
  341. log_level: CompileEventLogLevel = CompileEventLogLevel.CHROMIUM,
  342. ) -> None:
  343. if time_ns is None:
  344. time_ns = time.time_ns()
  345. chromium_log = get_chromium_event_logger()
  346. if log_level == CompileEventLogLevel.CHROMIUM:
  347. log_pt2_compile_event = False
  348. elif log_level == CompileEventLogLevel.PT2_COMPILE:
  349. log_pt2_compile_event = True
  350. else:
  351. raise RuntimeError(
  352. "Cannot log instant event at COMPILATION_METRIC level. Please choose one of CHROMIUM_EVENT or COMPILE_EVENT"
  353. )
  354. chromium_log.log_instant_event(
  355. event_name, time_ns, metadata, log_pt2_compile_event
  356. )
  357. @staticmethod
  358. def add_data(
  359. event_name: str,
  360. log_level: CompileEventLogLevel,
  361. overwrite: bool = False,
  362. **metadata: object,
  363. ) -> None:
  364. """
  365. Centralized API for adding data to various events
  366. Log an event to a toplevel "dynamo" event or metrics context
  367. depending on log level.
  368. """
  369. chromium_log = get_chromium_event_logger()
  370. pt2_compile_substack = chromium_log.get_pt2_compile_substack()
  371. if log_level == CompileEventLogLevel.CHROMIUM:
  372. chromium_log.add_event_data(event_name, **metadata)
  373. elif log_level == CompileEventLogLevel.PT2_COMPILE:
  374. pt2_compile_substack = chromium_log.get_pt2_compile_substack()
  375. if event_name not in pt2_compile_substack:
  376. raise RuntimeError(
  377. "Error: specified log level PT2_COMPILE, but the event %s"
  378. " is not logged to pt2_compile_events. Make sure the event is active and you passed "
  379. "log_pt2_compile_event=True to dynamo_timed",
  380. event_name,
  381. )
  382. chromium_log.add_event_data(event_name, **metadata)
  383. else:
  384. assert log_level == CompileEventLogLevel.COMPILATION_METRIC
  385. top_event = chromium_log.get_outermost_event()
  386. if event_name != top_event:
  387. raise RuntimeError(
  388. "Log level is COMPILATION_METRIC, but event_name isn't the toplevel event. "
  389. "CompilationMetrics must be logged to the toplevel event. Consider using `log_toplevel_event_data` directly."
  390. )
  391. metrics_context = get_metrics_context()
  392. if not metrics_context.in_progress():
  393. raise RuntimeError(
  394. "No metrics context is in progress. Please only call this function within a metrics context."
  395. )
  396. # TODO: should we assert that the keys of metadata are in CompilationMetrics?
  397. metrics_context.update(metadata, overwrite)
  398. chromium_log.add_event_data(event_name, **metadata)
  399. @staticmethod
  400. def add_toplevel(
  401. log_level: CompileEventLogLevel, overwrite: bool = False, **metadata: object
  402. ) -> None:
  403. """
  404. Syntactic sugar for logging to the toplevel event
  405. """
  406. top_event = get_chromium_event_logger().get_outermost_event()
  407. if top_event is None:
  408. raise RuntimeError(
  409. "No toplevel event active. Please only call this function within a dynamo_timed context."
  410. )
  411. CompileEventLogger.add_data(top_event, log_level, overwrite, **metadata)
  412. @staticmethod
  413. def increment(
  414. event_name: str, log_level: CompileEventLogLevel, key: str, value: int
  415. ) -> None:
  416. """
  417. Increments an existing field, or adds it
  418. """
  419. chromium_log = get_chromium_event_logger()
  420. if (
  421. log_level == CompileEventLogLevel.CHROMIUM
  422. or log_level == CompileEventLogLevel.PT2_COMPILE
  423. ):
  424. chromium_log.increment(event_name, key, value)
  425. else:
  426. assert log_level == CompileEventLogLevel.COMPILATION_METRIC
  427. top_event = chromium_log.get_outermost_event()
  428. if event_name != top_event:
  429. raise RuntimeError(
  430. "Log level is COMPILATION_METRIC, but event_name isn't the toplevel event. "
  431. "CompilationMetrics must be logged to the toplevel event. Consider using `increment_toplevel` directly."
  432. )
  433. metrics_context = get_metrics_context()
  434. if not metrics_context.in_progress():
  435. raise RuntimeError(
  436. "No metrics context is in progress. Please only call this function within a metrics context/dynamo_timed."
  437. )
  438. metrics_context.increment(key, value)
  439. chromium_log.increment(event_name, key, value)
  440. @staticmethod
  441. def increment_toplevel(
  442. key: str,
  443. value: int = 1,
  444. log_level: CompileEventLogLevel = CompileEventLogLevel.COMPILATION_METRIC,
  445. ) -> None:
  446. """
  447. Increments a value on the toplevel metric. By default, logs to metric.
  448. """
  449. chromium_log = get_chromium_event_logger()
  450. top_event = chromium_log.get_outermost_event()
  451. if top_event is None:
  452. raise RuntimeError(
  453. "No toplevel event active. Please only call this function within a metrics context/dynamo_timed."
  454. )
  455. CompileEventLogger.increment(top_event, log_level, key, value)
  456. @staticmethod
  457. def add_to_set(
  458. event_name: str, log_level: CompileEventLogLevel, key: str, value: Any
  459. ) -> None:
  460. """
  461. Add metadata <value> to a set of values with key <key>. Creates a set if it doesn't exist.
  462. """
  463. chromium_log = get_chromium_event_logger()
  464. if (
  465. log_level == CompileEventLogLevel.CHROMIUM
  466. or log_level == CompileEventLogLevel.PT2_COMPILE
  467. ):
  468. chromium_log.add_to_set(event_name, key, value)
  469. else:
  470. assert log_level == CompileEventLogLevel.COMPILATION_METRIC
  471. top_event = chromium_log.get_outermost_event()
  472. if event_name != top_event:
  473. raise RuntimeError(
  474. "Log level is COMPILATION_METRIC, but event_name isn't the toplevel event. "
  475. "CompilationMetrics must be logged to the toplevel event. Consider using `add_to_set_metric` directly."
  476. )
  477. metrics_context = get_metrics_context()
  478. if not metrics_context.in_progress():
  479. raise RuntimeError(
  480. "No metrics context is in progress. Please only call this function within a metrics context/dynamo_timed."
  481. )
  482. metrics_context.add_to_set(key, value)
  483. chromium_log.add_to_set(event_name, key, value)
  484. @staticmethod
  485. def add_to_set_toplevel(
  486. key: str,
  487. value: Any,
  488. log_level: CompileEventLogLevel = CompileEventLogLevel.COMPILATION_METRIC,
  489. ) -> None:
  490. """
  491. Same as add to set, just does it automatically to the toplevel event instead of having to explicitly name it.
  492. Defaults to COMPILATION_METRIC log level.
  493. """
  494. chromium_log = get_chromium_event_logger()
  495. top_event = chromium_log.get_outermost_event()
  496. if top_event is None:
  497. raise RuntimeError(
  498. "No toplevel event active. Please only call this function within a metrics context/dynamo_timed."
  499. )
  500. CompileEventLogger.add_to_set(top_event, log_level, key, value)
  501. # Helper functions that are syntactic sugar
  502. @staticmethod
  503. def chromium(event_name: str, **metadata: object) -> None:
  504. """
  505. Add <metadata> to <event_name> in chromium. Each key/value of metadata will appear in the chromium trace.
  506. <event_name> should be the name of a timed event span passed to `dynamo_timed`.
  507. """
  508. CompileEventLogger.add_data(
  509. event_name, CompileEventLogLevel.CHROMIUM, overwrite=False, **metadata
  510. )
  511. @staticmethod
  512. def pt2_compile(event_name: str, **metadata: object) -> None:
  513. """
  514. Add <metadata> to <event_name> in chromium and PT2 Compile Events.
  515. Each key/value of metadata will appear in the chromium trace. Each kwarg name becomes
  516. a column in PT2 Compile Events, with the corresponding kwarg value.
  517. <event_name> should be the name of a timed event span passed to `dynamo_timed`,
  518. with log_to_pt2_compile_events=True.
  519. """
  520. CompileEventLogger.add_data(
  521. event_name, CompileEventLogLevel.PT2_COMPILE, overwrite=False, **metadata
  522. )
  523. @staticmethod
  524. def add_record_function_data(event_name: str, **metadata: object) -> None:
  525. """
  526. Add record function data to the profiler event.
  527. This emits profiler event data so compilation events show up in stack profilers
  528. like the PyTorch profiler.
  529. Args:
  530. event_name: Name of the event to record
  531. **metadata: Additional metadata to attach to the record function
  532. """
  533. if torch.autograd.profiler._is_profiler_enabled and metadata:
  534. metadata_str = ", ".join(f"{k}={v}" for k, v in metadata.items())
  535. with torch.autograd.profiler.record_function(
  536. f"{event_name}_data: {metadata_str}"
  537. ):
  538. pass
  539. @staticmethod
  540. def compilation_metric(overwrite: bool = False, **metadata: object) -> None:
  541. """
  542. Add <metadata> to the CompilationMetrics context. Also logs to PT2 Compile Events
  543. and chromium.
  544. Each key/value of metadata will appear in the chromium trace. Each kwarg name becomes
  545. a column in PT2 Compile Events and Dynamo Compile, with the corresponding kwarg value.
  546. """
  547. CompileEventLogger.add_toplevel(
  548. CompileEventLogLevel.COMPILATION_METRIC, overwrite, **metadata
  549. )
  550. @staticmethod
  551. def instant(
  552. event_name: str, metadata: dict[str, Any], time_ns: Optional[int] = None
  553. ) -> None:
  554. """
  555. Log an instant event to chromium logs with name <event_name> at time <time_ns>. The `args` field in
  556. Perfetto will point to metadata. <time_ns> should be a value obtained from time.time_ns().
  557. """
  558. CompileEventLogger.log_instant_event(
  559. event_name, metadata, time_ns, CompileEventLogLevel.CHROMIUM
  560. )
  561. @staticmethod
  562. def try_add_pt2_compile(event_name: str, **metadata: object) -> None:
  563. """
  564. Adds to an existing pt2_compile event, but silently returns if the event doesn't exist
  565. or ChromiumEventLogger is not initialized.
  566. This function is syntactic sugar for chromium_event_logger().try_add_event_data.
  567. """
  568. if not chromium_event_log_active():
  569. return
  570. chromium_log = get_chromium_event_logger()
  571. chromium_log.try_add_event_data(event_name, **metadata)
  572. @staticmethod
  573. def try_(method_fn: Callable[_P, Any], *args: _P.args, **kwargs: _P.kwargs) -> None:
  574. """
  575. Special function that quietly runs a given method, returning if CHROMIUM_EVENT_LOG is None or metrics context is not set
  576. """
  577. if not chromium_event_log_active():
  578. return
  579. metrics_context = get_metrics_context()
  580. if not metrics_context.in_progress():
  581. return
  582. method_fn(*args, **kwargs)
  583. _dynamo_timed_tls = threading.local()
  584. @contextmanager
  585. def compile_time_record_function(name: str) -> Generator[Any, None, None]:
  586. """
  587. A context manager for compile-time profiling that uses _RecordFunctionFast
  588. for lower overhead than torch.profiler.record_function.
  589. This is intended for use during compilation (dynamo, inductor, etc.) where
  590. we want profiling support but with minimal overhead. Moreover, we do not
  591. want the record_function call inside torch.compile to be dispatched.
  592. Args:
  593. name: The name of the record function event that will appear in profiles.
  594. """
  595. if torch.autograd.profiler._is_profiler_enabled:
  596. rf = torch._C._profiler._RecordFunctionFast(name)
  597. rf.__enter__()
  598. try:
  599. yield
  600. finally:
  601. rf.__exit__(None, None, None)
  602. else:
  603. yield
  604. @contextmanager
  605. def dynamo_timed(
  606. key: str,
  607. # TODO(masneral): Deprecate this param.
  608. phase_name: Optional[str] = None,
  609. log_pt2_compile_event: bool = False,
  610. metadata: Optional[dict[str, object]] = None,
  611. dynamo_compile_column_us: Optional[str] = None,
  612. compile_id: Optional[CompileId] = None,
  613. is_backward: Optional[bool] = None,
  614. log_waitcounter: bool = False,
  615. waitcounter_name_override: Optional[str] = None,
  616. ) -> Generator[Any, None, None]:
  617. """
  618. dynamo_timed is a context manager
  619. By wrapping a function in dynamo_timed, we can get a few things:
  620. 1) Optionally log timings to pt2_compile_events.
  621. 2) Optionally log timings to CompilationMetrics (dynamo_compile).
  622. 3) Optionally log chromium events.
  623. 4) Optionally increment a WaitCounter.
  624. 5) Store a record in compilation_time_metrics
  625. For example:
  626. def _foo(...):
  627. with dynamo_timed("_foo"):
  628. ...
  629. Would show up as an entry in our timing dict:
  630. OrderedDict([('_foo', [0.083690, 0.23949, 3.1425e-05])])
  631. This is extremely useful for granular debugging.
  632. Although it is tempting to use dynamo_timed as a decorator, please do not.
  633. In its decorator form it makes cProfile traces less useful as dynamo_timed
  634. suddenly becomes a bottleneck for lots of function calls (as only one parent
  635. pointer is recorded).
  636. Params:
  637. - key: key into compile_time_metrics. If phase_name is not provided, this is
  638. also the event name used for pt2_compile_events logs and chromium events.
  639. - phase_name: Optional override for the event name.
  640. - log_pt2_compile_event: Whether to log a pt2 compile event internally.
  641. - metadata: Extra metadata to put in pt2_compile_events.
  642. - dynamo_compile_column_us: If provided, updates the specified CompilationMetrics
  643. field to be logged to dyname_compile column. We expect all columns to be _us;
  644. therefore, the field name must end with "_us".
  645. - compile_id: In the typical case, this parameter should not be needed. Use to
  646. supply the compile_id for those cases where we want to log a compile_id where
  647. it's not naturally available, e.g., for runtime autotuning.
  648. - is_backward: Specify forward/backward directly when not available in a
  649. CompileContext, e.g., during runtime autotuning.
  650. that support it.
  651. - log_waitcounter: If set, we'll log a waitcounter of the form "pytorch.dynamo_timed.{key}"
  652. """
  653. if phase_name:
  654. event_name = phase_name
  655. fn_name = key
  656. else:
  657. event_name = key
  658. fn_name = None
  659. if key not in compilation_time_metrics:
  660. compilation_time_metrics[key] = []
  661. metrics = compilation_time_metrics[key]
  662. event_metadata = {}
  663. if metadata:
  664. event_metadata.update(metadata)
  665. if fn_name:
  666. event_metadata.update({"fn_name": fn_name})
  667. if is_backward is not None:
  668. event_metadata.update({"is_backward": is_backward})
  669. chromium_log: ChromiumEventLogger = get_chromium_event_logger()
  670. start_ns = time.time_ns()
  671. chromium_log.log_event_start(
  672. event_name, start_ns, event_metadata, log_pt2_compile_event, compile_id
  673. )
  674. cx_mgrs: list[typing.Any] = [compile_time_record_function(f"{key} (dynamo_timed)")]
  675. if log_waitcounter:
  676. wc_name = waitcounter_name_override if waitcounter_name_override else key
  677. cx_mgrs.append(_WaitCounter(f"pytorch.wait_counter.{wc_name}").guard())
  678. is_compile_time = torch._guards.CompileContext.current_compile_id() is not None
  679. if dynamo_compile_column_us:
  680. # We're standardizing on microseconds for dynamo_compile timings.
  681. assert dynamo_compile_column_us.endswith("_us")
  682. # Track nested dynamo_timed calls that update CompilationMetrics so we can
  683. # bump a total duration only for the outermost metric.
  684. if not hasattr(_dynamo_timed_tls, "depth"):
  685. _dynamo_timed_tls.depth = 0
  686. _dynamo_timed_tls.depth += 1
  687. # The corresponding WaitCounters that we bump for all overheads
  688. if _dynamo_timed_tls.depth == 1:
  689. cx_mgrs.append(_WaitCounter("pytorch.wait_counter.dynamo_compile").guard())
  690. if not is_compile_time:
  691. runtime_wc = "pytorch.wait_counter.compile_runtime_overheads"
  692. cx_mgrs.append(_WaitCounter(runtime_wc).guard())
  693. try:
  694. with contextlib.ExitStack() as stack:
  695. for cx in cx_mgrs:
  696. stack.enter_context(cx)
  697. yield
  698. finally:
  699. end_ns = time.time_ns()
  700. time_spent_ns = end_ns - start_ns
  701. metrics.append(time_spent_ns / 1e9)
  702. chromium_log.log_event_end(
  703. event_name, end_ns, {}, start_ns, log_pt2_compile_event, compile_id
  704. )
  705. if dynamo_compile_column_us:
  706. # TODO: the events that we capture in calculate_time_spent() seem a little
  707. # arbitrary. Currently, it's only those fields that are present in
  708. # CompilationMetrics (but note that we accumulate by the associated event
  709. # name, not the field name in CompilationMetrics). Do we want to keep it
  710. # this way?
  711. cumulative_time_spent_ns[event_name] += time_spent_ns
  712. # Bump the total duration for every outer event.
  713. _dynamo_timed_tls.depth -= 1
  714. is_outer_event = _dynamo_timed_tls.depth == 0
  715. duration_us = time_spent_ns // 1000
  716. if is_compile_time:
  717. metrics_context = get_metrics_context()
  718. if metrics_context.in_progress():
  719. metrics_context.increment(dynamo_compile_column_us, duration_us)
  720. if is_outer_event:
  721. metrics_context.increment("duration_us", duration_us)
  722. else:
  723. runtime_context = get_runtime_metrics_context()
  724. runtime_context.increment(dynamo_compile_column_us, duration_us)
  725. if is_outer_event:
  726. extra = {
  727. "compile_id": compile_id,
  728. "is_runtime": True,
  729. "is_forward": not is_backward,
  730. }
  731. runtime_context.increment("duration_us", duration_us, extra)
  732. @overload
  733. def compile_times(repr: Literal["str"], aggregate: bool = False) -> str: ...
  734. @overload
  735. # pyrefly: ignore [inconsistent-overload]
  736. def compile_times(
  737. repr: Literal["csv"], aggregate: bool = False
  738. ) -> tuple[list[str], list[object]]: ...
  739. def compile_times( # type: ignore[misc]
  740. repr: str = "str", aggregate: bool = False
  741. ) -> Union[str, None, tuple[list[str], list[str]]]:
  742. """
  743. Get metrics about torchdynamo frontend/backend compilation times.
  744. Accumulates information from functions tagged with `dynamo_timed`.
  745. repr='str' returns a printable string for user interaction, and 'csv'
  746. returns headers, rows which can be logged for output
  747. aggregate causes values from multiple compilations (e.g. split graphs)
  748. to be accumulated into one value. If false, expect more than one value
  749. per metric.
  750. """
  751. def fmt_fn(values: list[float], item_fn: Callable[[float], str] = str) -> str:
  752. if aggregate:
  753. return item_fn(sum(values))
  754. return ", ".join(map(item_fn, values))
  755. if repr == "str":
  756. rows = [
  757. (k, fmt_fn(compilation_time_metrics[k], item_fn=lambda x: f"{x:.4f}"))
  758. for k in compilation_time_metrics
  759. ]
  760. out = "TorchDynamo compilation metrics:\n"
  761. out += tabulate(rows, headers=("Function", "Runtimes (s)"))
  762. return out
  763. elif repr == "csv":
  764. values = [
  765. fmt_fn(v, item_fn=lambda x: f"{x:.6f}")
  766. for v in compilation_time_metrics.values()
  767. ]
  768. headers = list(compilation_time_metrics.keys())
  769. return headers, values
  770. return None
  771. @atexit.register
  772. def dump_compile_times() -> None:
  773. log.info(compile_times(repr="str", aggregate=True))
  774. tensortype_to_dtype = {
  775. torch.FloatTensor: (torch.float32, torch.float),
  776. torch.DoubleTensor: (torch.float64, torch.double),
  777. torch.HalfTensor: (torch.float16, torch.half),
  778. torch.BFloat16Tensor: (torch.bfloat16,),
  779. torch.ByteTensor: (torch.uint8,),
  780. torch.CharTensor: (torch.int8,),
  781. torch.LongTensor: (torch.int64, torch.long),
  782. torch.IntTensor: (torch.int32, torch.int),
  783. torch.ShortTensor: (torch.int16, torch.short),
  784. torch.BoolTensor: (torch.bool,),
  785. }
  786. class DuplicateWarningChecker:
  787. def __init__(self, maxsize: int = 4096) -> None:
  788. self.maxsize = maxsize
  789. self.reset()
  790. def reset(self) -> None:
  791. self.set: OrderedDict[Any, Any] = OrderedDict()
  792. def add(self, key: Union[str, tuple[object, object]]) -> bool:
  793. if key in self.set:
  794. self.set.move_to_end(key, last=True)
  795. if not config.verbose:
  796. return False
  797. else:
  798. self.set[key] = None
  799. while len(self.set) > self.maxsize:
  800. self.set.popitem(last=False)
  801. return True
  802. graph_break_dup_warning_checker = DuplicateWarningChecker()
  803. def setup_compile_debug() -> contextlib.ExitStack:
  804. compile_debug = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1"
  805. if compile_debug:
  806. return add_file_handler()
  807. return contextlib.ExitStack()
  808. def reset_graph_break_dup_checker() -> None:
  809. graph_break_dup_warning_checker.reset()
  810. # Matches ANSI escape sequences (CSI)
  811. ANSI_ESCAPE_PATTERN = re.compile(
  812. r"""
  813. \x1B # ESC
  814. \[ # [
  815. [0-?]* # Parameter bytes
  816. [ -/]* # Intermediate bytes
  817. [@-~] # Final byte
  818. """,
  819. re.VERBOSE,
  820. )
  821. class StripAnsiFormatter(logging.Formatter):
  822. """Logging formatter that strips ANSI escape codes."""
  823. def format(self, record: logging.LogRecord) -> str:
  824. msg = super().format(record)
  825. return ANSI_ESCAPE_PATTERN.sub("", msg)
  826. def add_file_handler() -> contextlib.ExitStack:
  827. log_path = os.path.join(get_debug_dir(), "torchdynamo")
  828. os.makedirs(log_path, exist_ok=True)
  829. log_file_handler = logging.FileHandler(os.path.join(log_path, "debug.log"))
  830. log_file_handler.setFormatter(StripAnsiFormatter("%(message)s"))
  831. logger = logging.getLogger("torch._dynamo")
  832. logger.addHandler(log_file_handler)
  833. exitstack = contextlib.ExitStack()
  834. exitstack.callback(lambda: logger.removeHandler(log_file_handler))
  835. return exitstack
  836. def setup_log_file() -> contextlib.ExitStack:
  837. exitstack = contextlib.ExitStack()
  838. if config.log_file_name is not None:
  839. log_file_handler = logging.FileHandler(config.log_file_name)
  840. for logger in torch._logging._internal.get_loggers():
  841. logger.addHandler(log_file_handler)
  842. exitstack.callback(lambda: logger.removeHandler(log_file_handler))
  843. return exitstack
  844. return exitstack
  845. def gen_record_file_name(exc: Exception, code: CodeType) -> str:
  846. return f"{get_debug_dir()}/error_recordings/\
  847. {code.co_name}_{type(exc).__name__}_{code.co_firstlineno}.rec"
  848. def write_record_to_file(filename: str, exec_record: ExecutionRecord) -> None:
  849. try:
  850. if os.path.exists(filename):
  851. log.warning(
  852. "Unable to write execution record %s; file already exists.", filename
  853. )
  854. else:
  855. os.makedirs(os.path.dirname(filename), exist_ok=True)
  856. with open(filename, "wb") as f:
  857. exec_record.dump(f)
  858. except Exception:
  859. log.exception("Unable to write execution record %s", filename)
  860. def count_calls(g: fx.Graph) -> int:
  861. c = 0
  862. for n in g.nodes:
  863. if "call" in n.op:
  864. c += 1
  865. return c
  866. def identity(x: T) -> T:
  867. return x
  868. def hashable(x: Any) -> bool:
  869. try:
  870. hash(x)
  871. return True
  872. except TypeError:
  873. return False
  874. # cannot hash writable memoryview object
  875. except ValueError:
  876. return False
  877. def nothing(*args: Any, **kwargs: Any) -> None:
  878. pass
  879. class ExactWeakKeyDictionary:
  880. """Similar to weakref.WeakKeyDictionary, but use `is`/`id` rather than `==` to compare equality"""
  881. def __init__(self) -> None:
  882. self.values: dict[int, Any] = {}
  883. self.refs: dict[int, weakref.ReferenceType[Any]] = {}
  884. def __getitem__(self, key: Any) -> Any:
  885. return self.values[id(key)]
  886. def get(self, key: Any, default: Any = None) -> Any:
  887. return self.values.get(id(key), default)
  888. def __contains__(self, key: Any) -> bool:
  889. return id(key) in self.values
  890. def __setitem__(self, key: Any, value: Any) -> None:
  891. idx = id(key)
  892. if idx not in self.refs:
  893. self.refs[idx] = weakref.ref(key, lambda ref: self._remove_id(idx))
  894. self.values[idx] = value
  895. def _remove_id(self, idx: int) -> None:
  896. if idx in self.values:
  897. del self.values[idx]
  898. if idx in self.refs:
  899. del self.refs[idx]
  900. def clear(self) -> None:
  901. self.refs.clear()
  902. self.values.clear()
  903. @overload
  904. def istype(obj: object, allowed_types: type[T]) -> TypeIs[T]: ...
  905. @overload
  906. def istype(
  907. obj: object, allowed_types: tuple[type[list[T]], type[tuple[T, ...]]]
  908. ) -> TypeIs[T]: ...
  909. @overload
  910. def istype(obj: object, allowed_types: Iterable[type]) -> bool: ...
  911. def istype(obj: object, allowed_types: Any) -> bool:
  912. """isinstance() without subclasses"""
  913. if isinstance(allowed_types, (tuple, list, set)):
  914. return type(obj) in allowed_types
  915. return type(obj) is allowed_types
  916. _builtin_final_typing_classes: tuple[Any, ...] = tuple()
  917. if sys.version_info >= (3, 12):
  918. # Some typing classes moved to C in 3.12,
  919. # which no longer have the _Final mixin.
  920. # Check for consistency e.g. here:
  921. # https://github.com/python/cpython/blob/f2b82b3b3b1f8c7a81e84df35ee921e44517cf32/Lib/typing.py#L32
  922. _builtin_final_typing_classes = (
  923. typing.ParamSpecArgs,
  924. typing.ParamSpecKwargs,
  925. typing.ParamSpec,
  926. typing.TypeVar,
  927. typing.TypeVarTuple,
  928. typing.TypeAliasType,
  929. )
  930. def get_inputs_devices(
  931. inputs: collections.abc.Sequence[object],
  932. model: torch.fx.GraphModule,
  933. ) -> list[Optional[torch.device]]:
  934. all_inputs = pytree.tree_flatten(inputs)[0] + [
  935. node.meta["val"] for node in list(model.graph.nodes) if "val" in node.meta
  936. ]
  937. devices: list[Optional[torch.device]] = list(
  938. OrderedSet([i.device for i in all_inputs if hasattr(i, "device")])
  939. )
  940. return [
  941. i for i in devices if (isinstance(i, torch.device) and i.type != "meta")
  942. ] + [None]
  943. if sys.version_info >= (3, 14):
  944. _builtin_final_typing_classes += (typing.Union,)
  945. def is_typing(value: Any) -> bool:
  946. # _Final catches most of typing classes:
  947. # - Any
  948. # - Callable
  949. # - Union (Python < 3.14)
  950. # ...
  951. #
  952. # NB: we intentionally ignore classes that inherit from Generic, since they
  953. # can be used as both TypingVariable as well as UserDefinedClassVariable.
  954. if sys.version_info >= (3, 12) and isinstance(value, _builtin_final_typing_classes):
  955. return True
  956. return (
  957. isinstance(value, (types.UnionType, typing._Final)) # type: ignore[attr-defined]
  958. or value is typing.Generic
  959. or value is typing.Union
  960. )
  961. def is_numpy_int_type(value: Any) -> bool:
  962. if not np:
  963. return False
  964. return istype(
  965. value,
  966. (
  967. np.int8,
  968. np.int16,
  969. np.int32,
  970. np.int64,
  971. np.uint8,
  972. np.uint16,
  973. np.uint32,
  974. np.uint64,
  975. ),
  976. )
  977. def is_numpy_float_type(value: Any) -> bool:
  978. if not np:
  979. return False
  980. return istype(
  981. value,
  982. (
  983. np.float16,
  984. np.float32,
  985. np.float64,
  986. ),
  987. )
  988. @overload
  989. def is_lru_cache_wrapped_function(
  990. value: Callable[..., T],
  991. ) -> TypeGuard[functools._lru_cache_wrapper[T]]: ...
  992. @overload
  993. def is_lru_cache_wrapped_function(
  994. value: Any,
  995. ) -> TypeGuard[functools._lru_cache_wrapper[Any]]: ...
  996. def is_lru_cache_wrapped_function(
  997. value: Any,
  998. ) -> bool:
  999. return isinstance(value, functools._lru_cache_wrapper) and is_function(
  1000. inspect.getattr_static(value, "__wrapped__")
  1001. )
  1002. _FuncTypes: TypeAlias = Union[
  1003. types.FunctionType,
  1004. types.BuiltinFunctionType,
  1005. types.MethodDescriptorType,
  1006. types.WrapperDescriptorType,
  1007. ]
  1008. def is_function_or_wrapper(
  1009. value: Any,
  1010. ) -> TypeIs[Union[_FuncTypes, torch._ops.OpOverloadPacket, torch._ops.OpOverload]]:
  1011. return is_function(value) or isinstance(
  1012. value, (torch._ops.OpOverloadPacket, torch._ops.OpOverload)
  1013. )
  1014. def is_function(
  1015. value: Any,
  1016. ) -> TypeIs[_FuncTypes]:
  1017. return isinstance(
  1018. value,
  1019. (
  1020. types.FunctionType,
  1021. types.BuiltinFunctionType,
  1022. types.MethodDescriptorType,
  1023. types.WrapperDescriptorType,
  1024. ),
  1025. )
  1026. cmp_name_to_op_mapping = {
  1027. "__eq__": operator.eq,
  1028. "__ne__": operator.ne,
  1029. "__lt__": operator.lt,
  1030. "__le__": operator.le,
  1031. "__gt__": operator.gt,
  1032. "__ge__": operator.ge,
  1033. }
  1034. cmp_name_to_op_str_mapping = {
  1035. "__eq__": "==",
  1036. "__ne__": "!=",
  1037. "__lt__": "<",
  1038. "__le__": "<=",
  1039. "__gt__": ">",
  1040. "__ge__": ">=",
  1041. }
  1042. def is_wrapper_or_member_descriptor(
  1043. value: Any,
  1044. ) -> TypeIs[
  1045. Union[
  1046. types.GetSetDescriptorType,
  1047. types.MethodDescriptorType,
  1048. types.WrapperDescriptorType,
  1049. types.MemberDescriptorType,
  1050. types.MethodWrapperType,
  1051. ]
  1052. ]:
  1053. return isinstance(
  1054. value,
  1055. (
  1056. # set up by PyGetSetDef
  1057. types.GetSetDescriptorType,
  1058. # set by PyMethodDef, e.g. list.append
  1059. types.MethodDescriptorType,
  1060. # slots - list.__add__
  1061. types.WrapperDescriptorType,
  1062. # set up by PyMemberDef
  1063. types.MemberDescriptorType,
  1064. # wrapper over C functions
  1065. types.MethodWrapperType,
  1066. ),
  1067. )
  1068. def unwrap_if_wrapper(fn: Any) -> Any:
  1069. return unwrap_with_attr_name_if_wrapper(fn)[0]
  1070. def unwrap_with_attr_name_if_wrapper(fn: Any) -> tuple[Any, Optional[str]]:
  1071. # TODO(anijain2305) - Investigate if we can get rid of this function
  1072. # unpack @torch._dynamo.optimize()(fn) wrapped function
  1073. if is_function(fn) and inspect.getattr_static(fn, "_torchdynamo_inline", False):
  1074. fn = inspect.getattr_static(fn, "_torchdynamo_inline", fn)
  1075. attr_name = "_torchdynamo_inline"
  1076. else:
  1077. attr_name = None
  1078. return fn, attr_name
  1079. def is_numpy_ndarray(value: Any) -> TypeGuard[np.ndarray]: # type: ignore[type-arg]
  1080. if not np:
  1081. return False
  1082. return istype(value, np.ndarray)
  1083. def istensor(obj: Any) -> bool:
  1084. """Check of obj is a tensor"""
  1085. tensor_list: tuple[type, ...] = (
  1086. torch.Tensor,
  1087. torch.nn.Parameter,
  1088. *config.traceable_tensor_subclasses,
  1089. )
  1090. tensor_list = tensor_list + (torch._subclasses.FakeTensor,)
  1091. return istype(obj, tensor_list)
  1092. def is_lazy_module(mod: Any) -> bool:
  1093. return isinstance(mod, LazyModuleMixin)
  1094. @functools.lru_cache(4096)
  1095. def print_once(*args: Any) -> None:
  1096. print(*args)
  1097. def make_cell(val: Any = None) -> types.CellType:
  1098. """Some black magic to create a cell object that usually only exists in a closure"""
  1099. x = val
  1100. def f() -> Any:
  1101. return x
  1102. assert f.__closure__ is not None and len(f.__closure__) == 1
  1103. return f.__closure__[0]
  1104. def proxy_args_kwargs(args: Any, kwargs: Any) -> tuple[tuple[Any, ...], dict[str, Any]]:
  1105. try:
  1106. proxy_args = tuple(arg.as_proxy() for arg in args)
  1107. proxy_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()}
  1108. return proxy_args, proxy_kwargs
  1109. except NotImplementedError as e:
  1110. from .exc import unimplemented
  1111. from .variables.base import typestr
  1112. unimplemented(
  1113. gb_type="Failed to convert args/kwargs to proxy",
  1114. context=f"call_function args: {typestr(*args)} {typestr(*list(kwargs.values()))}",
  1115. explanation="Missing `as_proxy()` implementation for some arg/kwarg.",
  1116. hints=[],
  1117. from_exc=e,
  1118. )
  1119. def to_int_ms(v: Optional[float]) -> Optional[int]:
  1120. return None if v is None else int(v * 1000)
  1121. # float64 timestamp has a quarter microsecond precision in 2024, so while
  1122. # this is suboptimal we shouldn't meaningfully lose precision
  1123. def to_int_us(v: Optional[float]) -> Optional[int]:
  1124. return None if v is None else int(v * 1_000_000)
  1125. # Version field added to every log. Increment to make it easier to distinguish new
  1126. # vs. old entries when you make a substantive change to how the logs are populated.
  1127. LOG_FORMAT_VERSION = 3
  1128. @dataclasses.dataclass
  1129. class CompilationMetrics:
  1130. compile_id: Optional[str] = None
  1131. frame_key: Optional[str] = None
  1132. co_name: Optional[str] = None
  1133. co_filename: Optional[str] = None
  1134. co_firstlineno: Optional[int] = None
  1135. cache_size: Optional[int] = None
  1136. accumulated_cache_size: Optional[int] = None
  1137. guard_count: Optional[int] = None
  1138. shape_env_guard_count: Optional[int] = None
  1139. graph_op_count: Optional[int] = None
  1140. graph_node_count: Optional[int] = None
  1141. graph_input_count: Optional[int] = None
  1142. start_time: Optional[float] = None
  1143. entire_frame_compile_time_s: Optional[float] = None
  1144. backend_compile_time_s: Optional[float] = None
  1145. inductor_compile_time_s: Optional[float] = None
  1146. code_gen_time_s: Optional[float] = None
  1147. fail_type: Optional[str] = None
  1148. fail_reason: Optional[str] = None
  1149. fail_user_frame_filename: Optional[str] = None
  1150. fail_user_frame_lineno: Optional[int] = None
  1151. non_compliant_ops: Optional[set[str]] = None
  1152. compliant_custom_ops: Optional[set[str]] = None
  1153. restart_reasons: Optional[set[str]] = None
  1154. dynamo_time_before_restart_s: Optional[float] = None
  1155. stack_trace: Optional[list[str]] = None
  1156. exception_stack_trace: Optional[list[str]] = None
  1157. graph_node_shapes: Optional[str] = None
  1158. # Sometimes, we will finish analyzing a frame but conclude we don't want
  1159. # to install any guarded code. True means we actually decided to install
  1160. # a compiled frame
  1161. has_guarded_code: Optional[bool] = None
  1162. remote_cache_time_saved_s: Optional[float] = None
  1163. structured_logging_overhead_s: Optional[float] = None
  1164. config_suppress_errors: Optional[bool] = None
  1165. config_inline_inbuilt_nn_modules: Optional[bool] = None
  1166. specialize_float: Optional[bool] = None
  1167. dynamo_config: Optional[str] = None
  1168. compiler_config: Optional[str] = None
  1169. is_forward: Optional[bool] = None
  1170. num_triton_bundles: Optional[int] = None
  1171. remote_fx_graph_cache_get_time_ms: Optional[int] = None
  1172. remote_fx_graph_cache_put_time_ms: Optional[int] = None
  1173. start_time_us: Optional[int] = None
  1174. duration_us: Optional[int] = None
  1175. dynamo_cumulative_compile_time_us: Optional[int] = None
  1176. aot_autograd_cumulative_compile_time_us: Optional[int] = None
  1177. inductor_cumulative_compile_time_us: Optional[int] = None
  1178. inductor_code_gen_cumulative_compile_time_us: Optional[int] = None
  1179. triton_compile_time_us: Optional[int] = None
  1180. runtime_cudagraphify_time_us: Optional[int] = None
  1181. runtime_triton_autotune_time_us: Optional[int] = None
  1182. dynamo_compile_time_before_restart_us: Optional[int] = None
  1183. distributed_ephemeral_timeout_us: Optional[int] = None
  1184. structured_logging_overhead_us: Optional[int] = None
  1185. remote_fx_graph_cache_get_time_us: Optional[int] = None
  1186. remote_fx_graph_cache_put_time_us: Optional[int] = None
  1187. backward_cumulative_compile_time_us: Optional[int] = None
  1188. end_time_us: Optional[int] = None
  1189. pre_grad_pass_time_us: Optional[int] = None
  1190. post_grad_pass_time_us: Optional[int] = None
  1191. joint_graph_pass_time_us: Optional[int] = None
  1192. log_format_version: int = LOG_FORMAT_VERSION
  1193. inductor_config: Optional[str] = None
  1194. remote_cache_version: Optional[int] = None
  1195. inductor_fx_remote_cache_hit_count: Optional[int] = 0
  1196. inductor_fx_remote_cache_miss_count: Optional[int] = 0
  1197. inductor_fx_remote_cache_backend_type: Optional[str] = None
  1198. inductor_fx_remote_cache_hit_keys: Optional[str] = None
  1199. inductor_fx_remote_cache_miss_keys: Optional[str] = None
  1200. inductor_fx_local_cache_hit_count: Optional[int] = 0
  1201. inductor_fx_local_cache_miss_count: Optional[int] = 0
  1202. aotautograd_remote_cache_hit_count: Optional[int] = 0
  1203. aotautograd_remote_cache_miss_count: Optional[int] = 0
  1204. aotautograd_local_cache_hit_count: Optional[int] = 0
  1205. aotautograd_local_cache_miss_count: Optional[int] = 0
  1206. cuda_version: Optional[str] = None
  1207. triton_version: Optional[str] = None
  1208. feature_usage: Optional[dict[str, bool]] = None
  1209. compile_time_autotune_time_us: Optional[int] = None
  1210. is_runtime: Optional[bool] = False
  1211. gc_time_us: Optional[int] = None
  1212. tensorify_float_attempt: Optional[bool] = None
  1213. tensorify_float_success: Optional[bool] = None
  1214. tensorify_float_failure: Optional[set[str]] = None
  1215. guard_latency_us: Optional[float] = None
  1216. recompile_reason: Optional[str] = None
  1217. num_graph_breaks: Optional[int] = None
  1218. triton_kernel_compile_times_us: Optional[str] = None
  1219. ir_count: Optional[int] = None
  1220. cudagraph_skip_reason: Optional[str] = None
  1221. python_version: Optional[str] = None
  1222. pgo_put_remote_code_state_time_us: Optional[int] = None
  1223. pgo_get_remote_code_state_time_us: Optional[int] = None
  1224. # The number of elements within parameters. This is classically what people
  1225. # think of when they think of parameters in a ML model.
  1226. param_numel: Optional[int] = None
  1227. # The number of elements counted by bytes - i.e. a float32 is 4 bytes
  1228. # per element.
  1229. param_bytes: Optional[int] = None
  1230. # The number of parameters counted by fields. This is mostly a proxy for
  1231. # the number of distinct type of params.
  1232. param_count: Optional[int] = None
  1233. recompile_user_contexts: Optional[set[str]] = None
  1234. inline_inbuilt_nn_modules_candidate: Optional[bool] = False
  1235. pytorch_version: Optional[str] = None
  1236. inductor_provenance: Optional[set[str]] = None
  1237. @classmethod
  1238. def create(cls, metrics: dict[str, Any]) -> CompilationMetrics:
  1239. """
  1240. Factory method to create a CompilationMetrics from a dict of fields.
  1241. Includes the logic to add legacy fields and any pre-processing, e.g.,
  1242. we transform some fields to comma-separated strings for scuba logging.
  1243. """
  1244. def us_to_s(metric: Optional[int]) -> Optional[float]:
  1245. return metric / 1e6 if metric is not None else None
  1246. def us_to_ms(metric: Optional[int]) -> Optional[int]:
  1247. return metric // 1000 if metric is not None else None
  1248. def collection_to_str(metric: Optional[Any]) -> Optional[str]:
  1249. def safe_str(item: Any) -> str:
  1250. try:
  1251. return str(item)
  1252. except Exception:
  1253. return "<unknown>"
  1254. if metric is None:
  1255. return None
  1256. if not isinstance(metric, (set, list)):
  1257. return "<unknown>"
  1258. return ",".join(safe_str(item) for item in sorted(metric))
  1259. def collection_to_json_str(metric: Optional[Any]) -> Optional[str]:
  1260. if metric is None:
  1261. return None
  1262. try:
  1263. return json.dumps(list(metric))
  1264. except Exception:
  1265. return "<unknown>"
  1266. # TODO: The following are legacy fields, populated from the fields that replace
  1267. # them. Remove these when we decide we can really deprecate them.
  1268. legacy_metrics = {
  1269. "start_time": us_to_s(metrics.get("start_time_us")),
  1270. "entire_frame_compile_time_s": us_to_s(
  1271. metrics.get("dynamo_cumulative_compile_time_us")
  1272. ),
  1273. "backend_compile_time_s": us_to_s(
  1274. metrics.get("aot_autograd_cumulative_compile_time_us")
  1275. ),
  1276. "inductor_compile_time_s": us_to_s(
  1277. metrics.get("inductor_cumulative_compile_time_us")
  1278. ),
  1279. "code_gen_time_s": us_to_s(
  1280. metrics.get("inductor_code_gen_cumulative_compile_time_us")
  1281. ),
  1282. "remote_cache_time_saved_s": us_to_s(
  1283. metrics.get("distributed_ephemeral_timeout_us")
  1284. ),
  1285. "remote_fx_graph_cache_get_time_ms": us_to_ms(
  1286. metrics.get("remote_fx_graph_cache_get_time_us")
  1287. ),
  1288. "remote_fx_graph_cache_put_time_ms": us_to_ms(
  1289. metrics.get("remote_fx_graph_cache_put_time_us")
  1290. ),
  1291. "structured_logging_overhead_s": us_to_s(
  1292. metrics.get("structured_logging_overhead_us")
  1293. ),
  1294. }
  1295. all_metrics = {**legacy_metrics, **metrics}
  1296. # Processing before logging:
  1297. all_metrics["inductor_fx_remote_cache_hit_keys"] = collection_to_str(
  1298. all_metrics.get("inductor_fx_remote_cache_hit_keys")
  1299. )
  1300. all_metrics["inductor_fx_remote_cache_miss_keys"] = collection_to_str(
  1301. all_metrics.get("inductor_fx_remote_cache_miss_keys")
  1302. )
  1303. all_metrics["triton_kernel_compile_times_us"] = collection_to_json_str(
  1304. all_metrics.get("triton_kernel_compile_times_us")
  1305. )
  1306. compile_id = all_metrics.get("compile_id")
  1307. all_metrics["compile_id"] = str(compile_id) if compile_id else None
  1308. # pyrefly: ignore [bad-argument-type]
  1309. return cls(**all_metrics)
  1310. DEFAULT_COMPILATION_METRICS_LIMIT = 64
  1311. _compilation_metrics: collections.deque[CompilationMetrics] = collections.deque(
  1312. maxlen=DEFAULT_COMPILATION_METRICS_LIMIT
  1313. )
  1314. def add_compilation_metrics_to_chromium(c: CompilationMetrics) -> None:
  1315. """
  1316. These are the common fields in CompilationMetrics that existed before
  1317. metrics_context, and aren't set by MetricsContext.set(). We add the subset
  1318. of them that make sense in `dynamo`/toplevel events in PT2 Compile Events
  1319. directly.
  1320. If you're tempted to add to this list, consider using CompileEventLogger.compilation_metric()
  1321. instead, which will automatically also add it to tlparse and PT2 Compile Events.
  1322. TODO: Get rid of this function and replace it with CompileEventLogger directly instead.
  1323. """
  1324. event_logger = get_chromium_event_logger()
  1325. event_name = event_logger.get_outermost_event()
  1326. if not event_name:
  1327. return
  1328. event_logger.add_event_data(
  1329. event_name=event_name,
  1330. frame_key=c.frame_key,
  1331. co_name=c.co_name,
  1332. co_filename=c.co_filename,
  1333. co_firstlineno=c.co_firstlineno,
  1334. cache_size=c.cache_size,
  1335. accumulated_cache_size=c.accumulated_cache_size,
  1336. guard_count=c.guard_count,
  1337. shape_env_guard_count=c.shape_env_guard_count,
  1338. graph_op_count=c.graph_op_count,
  1339. graph_node_count=c.graph_node_count,
  1340. graph_input_count=c.graph_input_count,
  1341. fail_type=c.fail_type,
  1342. fail_reason=c.fail_reason,
  1343. fail_user_frame_filename=c.fail_user_frame_filename,
  1344. fail_user_frame_lineno=c.fail_user_frame_lineno,
  1345. # Sets aren't JSON serializable
  1346. non_compliant_ops=(
  1347. list(c.non_compliant_ops) if c.non_compliant_ops is not None else None
  1348. ),
  1349. compliant_custom_ops=(
  1350. list(c.compliant_custom_ops) if c.compliant_custom_ops is not None else None
  1351. ),
  1352. restart_reasons=(
  1353. list(c.restart_reasons) if c.restart_reasons is not None else None
  1354. ),
  1355. dynamo_time_before_restart_s=c.dynamo_time_before_restart_s,
  1356. has_guarded_code=c.has_guarded_code,
  1357. dynamo_config=c.dynamo_config,
  1358. )
  1359. def _get_dynamo_config_for_logging() -> Optional[str]:
  1360. def clean_for_json(d: dict[str, Any]) -> dict[str, Any]:
  1361. blocklist = {
  1362. "TYPE_CHECKING",
  1363. "log_file_name",
  1364. "verbose",
  1365. "repro_after",
  1366. "repro_level",
  1367. "repro_forward_only",
  1368. "repro_tolerance",
  1369. "repro_ignore_non_fp",
  1370. "same_two_models_use_fp64",
  1371. "base_dir",
  1372. "debug_dir_root",
  1373. "_save_config_ignore",
  1374. "log_compilation_metrics",
  1375. "inject_BUILD_SET_unimplemented_TESTING_ONLY",
  1376. "_autograd_backward_strict_mode_banned_ops",
  1377. "reorderable_logging_functions",
  1378. "ignore_logger_methods",
  1379. "traceable_tensor_subclasses",
  1380. "nontraceable_tensor_subclasses",
  1381. "_custom_ops_profile",
  1382. }
  1383. return {
  1384. key: sorted(value) if isinstance(value, set) else value
  1385. for key, value in d.items()
  1386. if key not in blocklist
  1387. }
  1388. config_dict = clean_for_json(config.get_config_copy())
  1389. return json.dumps(config_dict, sort_keys=True)
  1390. def _compiler_config_for_logging() -> Optional[str]:
  1391. def clean_for_json(d: dict[str, Any]) -> dict[str, Any]:
  1392. blocklist = {
  1393. "TYPE_CHECKING",
  1394. }
  1395. return {
  1396. key: sorted(value) if isinstance(value, set) else value
  1397. for key, value in d.items()
  1398. if key not in blocklist
  1399. }
  1400. if not torch.compiler.config:
  1401. return None
  1402. try:
  1403. compiler_config_copy = torch.compiler.config.get_config_copy() # type: ignore[attr-defined]
  1404. except (TypeError, AttributeError):
  1405. return "Compiler Config cannot be pickled"
  1406. config_dict = clean_for_json(compiler_config_copy)
  1407. return json.dumps(config_dict, sort_keys=True)
  1408. def _scrubbed_inductor_config_for_logging() -> Optional[str]:
  1409. """
  1410. Method to parse and scrub uninteresting configs from inductor config
  1411. """
  1412. # TypeSafeSerializer for json.dumps()
  1413. # Skips complex types as values in config dict
  1414. class TypeSafeSerializer(json.JSONEncoder):
  1415. def default(self, o: Any) -> Any:
  1416. try:
  1417. return super().default(o)
  1418. except Exception:
  1419. return "Value is not JSON serializable"
  1420. keys_to_scrub: set[Any] = set()
  1421. inductor_conf_str = None
  1422. inductor_config_copy = None
  1423. if torch._inductor.config:
  1424. try:
  1425. inductor_config_copy = torch._inductor.config.get_config_copy()
  1426. except (TypeError, AttributeError, RuntimeError, AssertionError):
  1427. inductor_conf_str = "Inductor Config cannot be pickled"
  1428. if inductor_config_copy is not None:
  1429. try:
  1430. for key, val in inductor_config_copy.items():
  1431. if not isinstance(key, str):
  1432. keys_to_scrub.add(key)
  1433. # Convert set() to list for json.dumps()
  1434. if isinstance(val, set):
  1435. inductor_config_copy[key] = list(val)
  1436. # Evict unwanted keys
  1437. for key in keys_to_scrub:
  1438. del inductor_config_copy[key]
  1439. # Stringify Inductor config
  1440. inductor_conf_str = json.dumps(
  1441. inductor_config_copy,
  1442. cls=TypeSafeSerializer,
  1443. skipkeys=True,
  1444. sort_keys=True,
  1445. )
  1446. except Exception:
  1447. # Don't crash because of runtime logging errors
  1448. inductor_conf_str = "Inductor Config is not JSON serializable"
  1449. return inductor_conf_str
  1450. def record_compilation_metrics(
  1451. start_time_ns: int,
  1452. end_time_ns: int,
  1453. metrics: dict[str, Any],
  1454. exc_type: Optional[type[BaseException]],
  1455. exc_value: Optional[BaseException],
  1456. ) -> None:
  1457. if torch._inductor.utils.should_use_remote_fx_graph_cache():
  1458. try:
  1459. from torch._inductor.fb.remote_cache import REMOTE_CACHE_VERSION
  1460. remote_cache_version = REMOTE_CACHE_VERSION
  1461. inductor_fx_remote_cache_backend_type = "_ManifoldCache"
  1462. except ModuleNotFoundError:
  1463. remote_cache_version = None
  1464. inductor_fx_remote_cache_backend_type = None
  1465. else:
  1466. inductor_fx_remote_cache_backend_type = None
  1467. remote_cache_version = None
  1468. # Populate the compile_id from the metrics context if it's set. Otherwise,
  1469. # look for it in the current compile context.
  1470. compile_id = metrics.get("compile_id")
  1471. if not compile_id:
  1472. compile_id = torch._guards.CompileContext.current_compile_id()
  1473. common_metrics = {
  1474. "compile_id": compile_id,
  1475. "start_time_us": start_time_ns // 1000,
  1476. "end_time_us": end_time_ns // 1000,
  1477. "fail_type": exc_type.__qualname__ if exc_type else None,
  1478. "fail_reason": str(exc_value) if exc_value else None,
  1479. "structured_logging_overhead_us": to_int_us(
  1480. torch._logging.get_structured_logging_overhead()
  1481. ),
  1482. "dynamo_config": _get_dynamo_config_for_logging(),
  1483. "config_suppress_errors": config.suppress_errors,
  1484. "config_inline_inbuilt_nn_modules": config.inline_inbuilt_nn_modules,
  1485. "inductor_config": _scrubbed_inductor_config_for_logging(),
  1486. "compiler_config": _compiler_config_for_logging(),
  1487. "cuda_version": torch.version.cuda,
  1488. "triton_version": triton.__version__ if has_triton() else "",
  1489. "remote_cache_version": remote_cache_version,
  1490. "inductor_fx_remote_cache_backend_type": inductor_fx_remote_cache_backend_type,
  1491. "python_version": sys.version,
  1492. "pytorch_version": torch.__version__,
  1493. }
  1494. compilation_metrics = CompilationMetrics.create({**common_metrics, **metrics})
  1495. _compilation_metrics.append(compilation_metrics)
  1496. name = "compilation_metrics"
  1497. if compilation_metrics.is_forward is False:
  1498. name = "bwd_" + name
  1499. if compilation_metrics.is_runtime is True:
  1500. name = name + "_runtime"
  1501. torch._logging.trace_structured(
  1502. name,
  1503. lambda: {
  1504. k: list(v) if isinstance(v, set) else v
  1505. for k, v in dataclasses.asdict(compilation_metrics).items()
  1506. },
  1507. # NB: Because compilation metrics *includes* the logging overhead time,
  1508. # we can't both *measure* the logging overhead of compilation metrics
  1509. # without making it inconsistent with compilation metrics itself, so
  1510. # we ignore the (hopefully small) time spent logging compilation metrics
  1511. record_logging_overhead=False,
  1512. # These may be runtime logs, e.g., runtime autotunning, so we provide
  1513. # the CompileId from the compilation metrics in case it's not available
  1514. # in the current trace.
  1515. compile_id=compile_id,
  1516. )
  1517. # If there's a chromium event in flight, add the CompilationMetrics to it.
  1518. add_compilation_metrics_to_chromium(compilation_metrics)
  1519. # Finally log the compilation metrics.
  1520. if config.log_compilation_metrics:
  1521. log_compilation_event(compilation_metrics)
  1522. def set_compilation_metrics_limit(new_size: int) -> None:
  1523. global _compilation_metrics
  1524. while len(_compilation_metrics) > new_size:
  1525. _compilation_metrics.popleft()
  1526. new_deque = collections.deque(_compilation_metrics, maxlen=new_size)
  1527. _compilation_metrics = new_deque
  1528. def clear_compilation_metrics() -> None:
  1529. global _compilation_metrics
  1530. _compilation_metrics.clear()
  1531. def get_compilation_metrics() -> list[CompilationMetrics]:
  1532. return list(_compilation_metrics)
  1533. class ChromiumEventLogger:
  1534. """Logs chromium events to structured logs. tlparse will concatenate these into a perfetto UI link.
  1535. Also emits RecordFunction calls to torch.profiler when enabled.
  1536. See https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview#heading=h.yr4qxyxotyw for
  1537. a specification of the Chromium Event JSON format.
  1538. """
  1539. def get_stack(self) -> list[str]:
  1540. """
  1541. The main event stack, with every chromium event.
  1542. Logged to tlparse.
  1543. """
  1544. if hasattr(self.tls, "stack"):
  1545. return self.tls.stack
  1546. else:
  1547. self.tls.stack = []
  1548. return self.tls.stack
  1549. def get_outermost_event(self) -> Optional[str]:
  1550. """
  1551. Get the outermost event name (i.e. the longest running event)
  1552. or None if the stack is empty.
  1553. """
  1554. stack = self.get_stack()
  1555. return stack[0] if stack else None
  1556. def get_pt2_compile_substack(self) -> list[str]:
  1557. """
  1558. A smaller subset of the main stack that gets used to log
  1559. PT2 Compile Events internally.
  1560. """
  1561. if hasattr(self.tls, "pt2_compile_substack"):
  1562. return self.tls.pt2_compile_substack
  1563. else:
  1564. self.tls.pt2_compile_substack = []
  1565. return self.tls.pt2_compile_substack
  1566. def get_event_data(self) -> dict[str, Any]:
  1567. if not hasattr(self.tls, "event_data"):
  1568. self.tls.event_data = {}
  1569. return self.tls.event_data
  1570. def get_record_functions(self) -> dict[str, AbstractContextManager[None]]:
  1571. if not hasattr(self.tls, "record_functions"):
  1572. self.tls.record_functions = {}
  1573. return self.tls.record_functions
  1574. def __init__(self) -> None:
  1575. self.tls = threading.local()
  1576. from . import config
  1577. # Generate a unique id for this logger, which we can use in scuba to filter down
  1578. # to a single python run.
  1579. if config.pt2_compile_id_prefix:
  1580. self.id_ = f"{config.pt2_compile_id_prefix}-{uuid.uuid4()}"
  1581. else:
  1582. self.id_ = str(uuid.uuid4())
  1583. # TODO: log to init/id tlparse after I add support for it
  1584. log.info("ChromiumEventLogger initialized with id %s", self.id_)
  1585. def try_add_event_data(self, event_name: str, **kwargs: Any) -> None:
  1586. """
  1587. Same as add_event_data, but will silently not log if the event isn't in the stack.
  1588. """
  1589. if event_name not in self.get_stack():
  1590. return
  1591. self.add_event_data(event_name, **kwargs)
  1592. def add_event_data(
  1593. self,
  1594. event_name: str,
  1595. **kwargs: Any,
  1596. ) -> None:
  1597. """
  1598. Adds additional metadata info to an in-progress event
  1599. This metadata is recorded in the END event
  1600. """
  1601. if event_name not in self.get_stack():
  1602. raise RuntimeError(
  1603. f"Event {repr(event_name)} not in {self.get_stack()}. "
  1604. "Cannot add metadata to events that aren't in progress. "
  1605. "Please make sure the event has started and hasn't ended."
  1606. )
  1607. event_data = self.get_event_data()
  1608. if event_name not in event_data:
  1609. event_data[event_name] = {}
  1610. event_data[event_name].update(kwargs)
  1611. def increment(self, event_name: str, key: str, value: int) -> None:
  1612. """
  1613. Increment an integer event data field by the given amount
  1614. """
  1615. if event_name not in self.get_stack():
  1616. raise RuntimeError(
  1617. f"Event {repr(event_name)} not in {self.get_stack()}. "
  1618. "Cannot add metadata to events that aren't in progress. "
  1619. "Please make sure the event has started and hasn't ended."
  1620. )
  1621. event_data = self.get_event_data()
  1622. if event_name not in event_data:
  1623. event_data[event_name] = {}
  1624. if key not in event_data[event_name]:
  1625. event_data[event_name][key] = 0
  1626. event_data[event_name][key] += value
  1627. def add_to_set(
  1628. self,
  1629. event_name: str,
  1630. key: str,
  1631. value: Any,
  1632. ) -> None:
  1633. """
  1634. Add a value to a set within a event_name's metadata if it exists
  1635. """
  1636. if event_name not in self.get_stack():
  1637. raise RuntimeError(
  1638. f"Event {repr(event_name)} not in {self.get_stack()}. "
  1639. "Cannot add metadata to events that aren't in progress. "
  1640. "Please make sure the event has started and hasn't ended."
  1641. )
  1642. event_data = self.get_event_data()
  1643. if event_name not in event_data:
  1644. event_data[event_name] = {}
  1645. if key not in event_data[event_name]:
  1646. event_data[event_name][key] = set()
  1647. event_data[event_name][key].add(value)
  1648. def log_event_start(
  1649. self,
  1650. event_name: str,
  1651. time_ns: int,
  1652. metadata: dict[str, Any],
  1653. log_pt2_compile_event: bool = False,
  1654. compile_id: Optional[CompileId] = None,
  1655. ) -> None:
  1656. """
  1657. Logs the start of a single event.
  1658. :param str event_name Name of event to appear in trace
  1659. :param time_ns Timestamp in nanoseconds
  1660. :param metadata: Any extra metadata associated with this event
  1661. :param log_pt2_compile_event: If True, log to pt2_compile_events
  1662. :param compile_id: Explicit compile_id (rather than using the current context)
  1663. """
  1664. compile_id = compile_id or torch._guards.CompileContext.current_compile_id()
  1665. metadata["compile_id"] = str(compile_id)
  1666. self._log_timed_event(
  1667. event_name,
  1668. time_ns,
  1669. "B",
  1670. metadata,
  1671. )
  1672. self.get_stack().append(event_name)
  1673. # Add metadata from start event
  1674. self.add_event_data(event_name, **metadata)
  1675. if log_pt2_compile_event:
  1676. self.get_pt2_compile_substack().append(event_name)
  1677. # Emit profiler event so compilation events show up in stock PyTorch profiler
  1678. if torch.autograd.profiler._is_profiler_enabled:
  1679. rf = torch._C._profiler._RecordFunctionFast(event_name)
  1680. rf.__enter__()
  1681. self.get_record_functions()[event_name] = rf
  1682. # Add metadata to the profiler event if present
  1683. if metadata:
  1684. CompileEventLogger.add_record_function_data(event_name, **metadata)
  1685. def reset(self) -> None:
  1686. # We this on every compile in case a compile crashes or restarts and we haven't
  1687. # cleared the stack.
  1688. stack = self.get_stack()
  1689. substack = self.get_pt2_compile_substack()
  1690. stack.clear()
  1691. substack.clear()
  1692. event_data = self.get_event_data()
  1693. event_data.clear()
  1694. # Clean up any lingering record functions (shouldn't happen in normal operation)
  1695. record_functions = self.get_record_functions()
  1696. if record_functions:
  1697. for rf in record_functions.values():
  1698. rf.__exit__(None, None, None)
  1699. record_functions.clear()
  1700. def log_event_end(
  1701. self,
  1702. event_name: str,
  1703. time_ns: int,
  1704. metadata: dict[str, Any],
  1705. start_time_ns: int,
  1706. log_pt2_compile_event: bool,
  1707. compile_id: Optional[CompileId] = None,
  1708. ) -> None:
  1709. """
  1710. Logs the end of a single event. This function should only be
  1711. called after log_event_start with the same event_name.
  1712. :param event_name: Name of event to appear in trace
  1713. :param time_ns: Timestamp in nanoseconds
  1714. :param metadata: Any extra metadata associated with this event
  1715. :param start_time_ns: The start time timestamp in nanoseconds
  1716. :param log_pt_compile_event: If True, log to pt2_compile_events
  1717. :param compile_id: Explicit compile_id (rather than using the current context)
  1718. """
  1719. compile_id = compile_id or torch._guards.CompileContext.current_compile_id()
  1720. metadata["compile_id"] = str(compile_id)
  1721. # Grab metadata collected during event span
  1722. all_event_data = self.get_event_data()
  1723. if event_name in all_event_data:
  1724. event_metadata = all_event_data[event_name]
  1725. del all_event_data[event_name]
  1726. else:
  1727. # pyrefly: ignore [implicit-any]
  1728. event_metadata = {}
  1729. # Add the passed in metadata
  1730. event_metadata.update(metadata)
  1731. event = self._log_timed_event(
  1732. event_name,
  1733. time_ns,
  1734. "E",
  1735. event_metadata,
  1736. )
  1737. def pop_stack(stack: list[str]) -> None:
  1738. while event_name != stack[-1]:
  1739. # If the event isn't the most recent one to end, pop
  1740. # off the stack until it is.
  1741. # Since event_name in self.stack, this pop is always safe
  1742. log.warning(
  1743. "ChromiumEventLogger: Detected overlapping events, fixing stack"
  1744. )
  1745. stack.pop()
  1746. event_stack = self.get_stack()
  1747. # These stack health checks currently never happen,
  1748. # but they're written this way to future proof any weird event
  1749. # overlaps in the future.
  1750. if event_name not in event_stack:
  1751. # Something went wrong, we never called start on this event,
  1752. # or it was skipped due to overlapping events below
  1753. log.warning("ChromiumEventLogger: Start event not in stack, ignoring")
  1754. return
  1755. pop_stack(event_stack)
  1756. if log_pt2_compile_event:
  1757. pt2_compile_substack = self.get_pt2_compile_substack()
  1758. pop_stack(pt2_compile_substack)
  1759. log_chromium_event_internal(
  1760. event, pt2_compile_substack, self.id_, start_time_ns
  1761. )
  1762. # Pop actual event off of stack
  1763. pt2_compile_substack.pop()
  1764. # Finally pop the actual event off the stack
  1765. event_stack.pop()
  1766. # End profiler event so compilation events show up in stock PyTorch profiler
  1767. record_functions = self.get_record_functions()
  1768. if event_name in record_functions:
  1769. rf = record_functions.pop(event_name)
  1770. rf.__exit__(None, None, None)
  1771. def _log_timed_event(
  1772. self,
  1773. event_name: str,
  1774. time_ns: int,
  1775. phase: str,
  1776. metadata: Optional[dict[str, Any]] = None,
  1777. ) -> dict[str, Any]:
  1778. """
  1779. Logs a timed event in chromium format. See log_event_start, log_event_end, etc.
  1780. """
  1781. event = {
  1782. "name": event_name,
  1783. "ts": time_ns / 1000, # Chromium events are in micro seconds
  1784. "args": metadata,
  1785. "ph": phase,
  1786. # These categories are needed in all chromium traces
  1787. "cat": "dynamo_timed",
  1788. "tid": 0,
  1789. "pid": 0, # pid should be specified on all logs, we don't personally care about the actual process id
  1790. }
  1791. torch._logging.trace_structured(
  1792. "chromium_event",
  1793. payload_fn=lambda: event,
  1794. suppress_context=False,
  1795. expect_trace_id=False, # Not every chromium event will have a trace_id
  1796. )
  1797. record_chromium_event_internal(event)
  1798. return event
  1799. def log_instant_event(
  1800. self,
  1801. event_name: str,
  1802. time_ns: int,
  1803. metadata: Optional[dict[str, Any]] = None,
  1804. # By default, an instant event isn't logged internally, only to structured logging.
  1805. log_pt2_compile_event: bool = False,
  1806. ) -> None:
  1807. """
  1808. Log an instant event with no associated duration.
  1809. :param str event_name: Name of event to appear in trace
  1810. :param int time_ns Timestamp in nanoseconds
  1811. :param Optional[Dict[str, Any]] metadata: Any extra metadata associated with this event
  1812. :param str cname optional color for the arrow in the trace
  1813. """
  1814. if metadata is None:
  1815. metadata = {}
  1816. compile_id = str(torch._guards.CompileContext.current_compile_id())
  1817. metadata["compile_id"] = compile_id
  1818. event = {
  1819. "name": event_name,
  1820. "ts": time_ns / 1000,
  1821. "args": metadata,
  1822. "ph": "i",
  1823. # These categories are needed in all chromium traces
  1824. "cat": "dynamo_timed",
  1825. "tid": 0,
  1826. "pid": 0,
  1827. "s": "p", # We use "process" level instant events so they all appear on the same row in the trace.
  1828. }
  1829. torch._logging.trace_structured(
  1830. "chromium_event",
  1831. payload_fn=lambda: event,
  1832. suppress_context=False,
  1833. expect_trace_id=True,
  1834. )
  1835. if log_pt2_compile_event:
  1836. # Log an instant event with the same start and end time
  1837. log_chromium_event_internal(
  1838. event, self.get_pt2_compile_substack(), self.id_, time_ns
  1839. )
  1840. CHROMIUM_EVENT_LOG: Optional[ChromiumEventLogger] = None
  1841. def get_chromium_event_logger() -> ChromiumEventLogger:
  1842. global CHROMIUM_EVENT_LOG
  1843. if CHROMIUM_EVENT_LOG is None:
  1844. CHROMIUM_EVENT_LOG = ChromiumEventLogger()
  1845. return CHROMIUM_EVENT_LOG
  1846. def chromium_event_log_active() -> bool:
  1847. global CHROMIUM_EVENT_LOG
  1848. return CHROMIUM_EVENT_LOG is not None
  1849. @contextmanager
  1850. def chromium_event_timed(
  1851. event_name: str,
  1852. reset_event_log_on_exit: bool = False,
  1853. log_pt2_compile_event: bool = False,
  1854. ) -> Generator[Any, None, None]:
  1855. """
  1856. Context manager that creates a chromium start and end event. Chromium event
  1857. logging is integrated with dynamo_timed, so you probably want to use that
  1858. instead. Use this context manager only if you want to avoid dynamo_timed.
  1859. """
  1860. chromium_event_log = get_chromium_event_logger()
  1861. chromium_start_time = time.time_ns()
  1862. chromium_event_log.log_event_start(
  1863. event_name,
  1864. chromium_start_time,
  1865. {},
  1866. log_pt2_compile_event,
  1867. )
  1868. try:
  1869. yield
  1870. finally:
  1871. chromium_event_log.log_event_end(
  1872. event_name,
  1873. time.time_ns(),
  1874. {},
  1875. chromium_start_time,
  1876. log_pt2_compile_event,
  1877. )
  1878. if reset_event_log_on_exit:
  1879. chromium_event_log.reset()
  1880. @dataclasses.dataclass
  1881. class CleanupHook:
  1882. """Remove a global variable when hook is called"""
  1883. scope: dict[str, Any]
  1884. name: str
  1885. def __call__(self, *args: Any) -> None:
  1886. # Make sure we're not shutting down
  1887. if CleanupManager is not None:
  1888. CleanupManager.count -= 1
  1889. del self.scope[self.name]
  1890. @staticmethod
  1891. def create(scope: dict[str, Any], name: str, val: Any) -> CleanupHook:
  1892. assert name not in scope
  1893. CleanupManager.count += 1
  1894. scope[name] = val
  1895. return CleanupHook(scope, name)
  1896. class CleanupManager(ExactWeakKeyDictionary):
  1897. count = 0
  1898. instance: ClassVar[CleanupManager]
  1899. def _remove_id(self, idx: int) -> None:
  1900. for hook in self.values[idx]:
  1901. hook()
  1902. super()._remove_id(idx)
  1903. CleanupManager.instance = CleanupManager()
  1904. def clone_tensor(x: torch.Tensor) -> torch.Tensor:
  1905. """Clone the tensor and its gradient"""
  1906. y = x.clone().requires_grad_(x.requires_grad)
  1907. if x.is_leaf and x.grad is not None:
  1908. y.grad = x.grad.clone()
  1909. return y
  1910. def _copy_dynamo_attr(src: torch.Tensor, dst: torch.Tensor, attr: str) -> None:
  1911. """Copy a single dynamo attribute from src to dst, or remove it from dst if src doesn't have it."""
  1912. if hasattr(src, attr):
  1913. setattr(dst, attr, getattr(src, attr).copy())
  1914. elif hasattr(dst, attr):
  1915. delattr(dst, attr)
  1916. def copy_dynamo_tensor_attributes(src: torch.Tensor, dst: torch.Tensor) -> None:
  1917. """
  1918. Copy dynamo-specific tensor attributes from src to dst.
  1919. These attributes are used for dynamic shape marking and must be preserved
  1920. when cloning or casting tensors. If src doesn't have an attribute but dst does,
  1921. the attribute is removed from dst.
  1922. """
  1923. _copy_dynamo_attr(src, dst, "_dynamo_dynamic_indices")
  1924. _copy_dynamo_attr(src, dst, "_dynamo_unbacked_indices")
  1925. _copy_dynamo_attr(src, dst, "_dynamo_hint_overrides")
  1926. _copy_dynamo_attr(src, dst, "_dynamo_shape_ids")
  1927. _copy_dynamo_attr(src, dst, "_dynamo_strict_unbacked_indices")
  1928. _copy_dynamo_attr(src, dst, "_dynamo_weak_dynamic_indices")
  1929. def clone_input(
  1930. x: torch.Tensor, *, dtype: Optional[torch.dtype] = None
  1931. ) -> torch.Tensor:
  1932. """copy while preserving strides"""
  1933. # TODO: this is questionable
  1934. if is_fake(x):
  1935. # this func fails on fake tensors in __torch_dispatch__
  1936. return x
  1937. def torch_clone(x: torch.Tensor) -> torch.Tensor:
  1938. y = torch.clone(x)
  1939. if x.is_leaf:
  1940. y.requires_grad_(x.requires_grad)
  1941. if x.is_leaf and x.grad is not None:
  1942. y.grad = clone_input(x.grad, dtype=dtype)
  1943. copy_dynamo_tensor_attributes(x, y)
  1944. return y
  1945. with torch.no_grad():
  1946. if x.device.type == "xla":
  1947. # Access data_ptr() for a xla tensor will cause crash
  1948. return torch_clone(x)
  1949. # Handle sparse storage (no stride).
  1950. if x.layout is torch.sparse_coo:
  1951. return torch.sparse_coo_tensor(
  1952. torch_clone(x._indices()),
  1953. torch_clone(x._values()),
  1954. x.shape,
  1955. is_coalesced=x.is_coalesced(),
  1956. )
  1957. elif is_sparse_compressed(x):
  1958. if x.layout in {torch.sparse_csr, torch.sparse_bsr}:
  1959. compressed_indices = x.crow_indices()
  1960. plain_indices = x.col_indices()
  1961. else:
  1962. compressed_indices = x.ccol_indices()
  1963. plain_indices = x.row_indices()
  1964. return torch.sparse_compressed_tensor(
  1965. torch_clone(compressed_indices),
  1966. torch_clone(plain_indices),
  1967. torch_clone(x.values()),
  1968. x.shape,
  1969. layout=x.layout,
  1970. )
  1971. elif is_traceable_wrapper_subclass(x):
  1972. # Questionable - but this is required to not fail executorch related
  1973. # torchao tests.
  1974. return torch_clone(x)
  1975. needed_size = sum(
  1976. (shape - 1) * stride for shape, stride in zip(x.size(), x.stride())
  1977. )
  1978. if x.is_quantized:
  1979. result = torch.empty_quantized((needed_size + 32,), x)
  1980. else:
  1981. result = torch.empty(
  1982. needed_size + 32, dtype=dtype or x.dtype, device=x.device
  1983. )
  1984. cache_line_offset = (
  1985. (x.data_ptr() - result.data_ptr()) % 32
  1986. ) // x.element_size()
  1987. result.as_strided_(x.size(), x.stride(), cache_line_offset)
  1988. try:
  1989. result.copy_(x.clone())
  1990. if x.is_leaf:
  1991. result.requires_grad_(x.requires_grad)
  1992. if x.is_leaf and x.grad is not None:
  1993. result.grad = clone_input(x.grad, dtype=dtype)
  1994. except RuntimeError:
  1995. # RuntimeError: unsupported operation: more than one element of the written-to
  1996. # tensor refers to a single memory location. Please clone() the tensor before
  1997. # performing the operation.
  1998. return torch_clone(x)
  1999. copy_dynamo_tensor_attributes(x, result)
  2000. return result
  2001. @overload
  2002. def clone_inputs(
  2003. example_inputs: dict[str, Union[T, tuple[T, ...]]],
  2004. ) -> dict[str, list[T]]: ...
  2005. @overload
  2006. def clone_inputs(example_inputs: Sequence[T]) -> list[T]: ...
  2007. def clone_inputs(example_inputs: Any) -> Any:
  2008. res: Union[dict[str, Any], list[Any]]
  2009. if type(example_inputs) is dict:
  2010. res = dict(example_inputs)
  2011. for key, value in res.items():
  2012. if isinstance(value, tuple):
  2013. res[key] = clone_inputs(value)
  2014. else:
  2015. assert isinstance(value, torch.Tensor), type(value)
  2016. res[key] = clone_input(value)
  2017. return res
  2018. res = list(example_inputs)
  2019. for i in range(len(res)):
  2020. if isinstance(res[i], torch.Tensor):
  2021. res[i] = clone_input(res[i])
  2022. return res
  2023. def skip_frame_if_in_functorch_mode(val: torch.Tensor) -> None:
  2024. try:
  2025. val.data_ptr() # will throw for functorch tensors
  2026. except RuntimeError as e:
  2027. from .exc import unimplemented
  2028. # This will be GradTrackingTensor/BatchedTensor/etc
  2029. functorch_subclass_name = re.sub(r"\(.*", "", repr(val))
  2030. unimplemented(
  2031. gb_type="skip frame due to being in functorh mode",
  2032. context="",
  2033. explanation=f"torch.compile cannot be run in context: {functorch_subclass_name}. Skipping frame.",
  2034. hints=[],
  2035. from_exc=e,
  2036. skip_frame=True,
  2037. )
  2038. @contextmanager
  2039. def preserve_rng_state() -> Generator[None, None, None]:
  2040. disable_functorch = torch._C._DisableFuncTorch
  2041. disable_current_modes = torch.utils._python_dispatch._disable_current_modes
  2042. with disable_current_modes(), disable_functorch():
  2043. rng_state = torch.clone(torch.random.get_rng_state())
  2044. skip_frame_if_in_functorch_mode(rng_state)
  2045. if torch.cuda.is_available():
  2046. cuda_rng_state = torch.clone(torch.cuda.get_rng_state())
  2047. if torch.xpu.is_available():
  2048. xpu_rng_state = torch.clone(torch.xpu.get_rng_state())
  2049. try:
  2050. yield
  2051. finally:
  2052. with torch.utils._python_dispatch._disable_current_modes():
  2053. torch.random.set_rng_state(rng_state)
  2054. if torch.cuda.is_available():
  2055. torch.cuda.set_rng_state(cuda_rng_state) # type: ignore[possibly-undefined]
  2056. if torch.xpu.is_available():
  2057. torch.xpu.set_rng_state(xpu_rng_state) # type: ignore[possibly-undefined]
  2058. def is_jit_model(
  2059. model0: Any,
  2060. ) -> TypeIs[
  2061. Union[
  2062. torch.jit._trace.TopLevelTracedModule,
  2063. torch.jit._script.RecursiveScriptModule,
  2064. # pyrefly: ignore [invalid-param-spec]
  2065. torch.jit.ScriptFunction[Any, Any],
  2066. torch.jit.ScriptModule,
  2067. ]
  2068. ]:
  2069. return isinstance(
  2070. model0,
  2071. (
  2072. torch.jit._trace.TopLevelTracedModule,
  2073. torch.jit._script.RecursiveScriptModule,
  2074. torch.jit.ScriptFunction,
  2075. torch.jit.ScriptModule,
  2076. ),
  2077. )
  2078. def torchscript(model: Any, example_inputs: Any, verbose: bool = False) -> Any:
  2079. if is_jit_model(model):
  2080. # already done?
  2081. return model
  2082. try:
  2083. return torch.jit.trace(model, example_inputs)
  2084. except Exception:
  2085. try:
  2086. return torch.jit.script(model)
  2087. except Exception:
  2088. if verbose:
  2089. log.exception("jit error")
  2090. else:
  2091. log.error("Both torch.jit.trace and torch.jit.script failed")
  2092. return None
  2093. def getfile(obj: Any) -> Optional[str]:
  2094. try:
  2095. return inspect.getfile(obj)
  2096. except (TypeError, OSError):
  2097. return None
  2098. def is_namedtuple(obj: Any) -> bool:
  2099. """Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple"""
  2100. return is_namedtuple_cls(type(obj))
  2101. def is_namedtuple_cls(cls: Any) -> bool:
  2102. """Test if an object is a namedtuple or a (torch.return_types|torch.autograd.forward_ad).* quasi-namedtuple"""
  2103. try:
  2104. if issubclass(cls, tuple):
  2105. module = getattr(cls, "__module__", None)
  2106. if module in ("torch.return_types", "torch.autograd.forward_ad"):
  2107. return True
  2108. if isinstance(getattr(cls, "_fields", None), tuple) and callable(
  2109. getattr(cls, "_make", None)
  2110. ):
  2111. # The subclassing style namedtuple can have an extra base `typing.Generic`
  2112. bases = tuple(t for t in cls.__bases__ if t is not Generic)
  2113. if bases == (tuple,):
  2114. # This is a namedtuple type directly created by `collections.namedtuple(...)`
  2115. return True
  2116. if bases and any(
  2117. (
  2118. # Subclass of namedtuple
  2119. is_namedtuple_cls(t)
  2120. # For subclasses of namedtuple, the __new__ method should not be customized
  2121. and cls.__new__ is t.__new__
  2122. )
  2123. for t in bases
  2124. ):
  2125. return True
  2126. except TypeError:
  2127. pass
  2128. return False
  2129. @functools.lru_cache(1)
  2130. def namedtuple_fields(cls: type) -> tuple[str, ...]:
  2131. """Get the fields of a namedtuple or a torch.return_types.* quasi-namedtuple"""
  2132. if cls is slice:
  2133. return ("start", "stop", "step")
  2134. assert issubclass(cls, tuple)
  2135. if hasattr(cls, "_fields"):
  2136. # normal namedtuples
  2137. return cls._fields
  2138. @dataclasses.dataclass
  2139. class Marker:
  2140. index: int
  2141. # frustrating ones e.g. torch.return_types.max
  2142. assert cls.__module__ == "torch.return_types"
  2143. obj = cls(map(Marker, range(cls.n_fields))) # type: ignore[attr-defined]
  2144. fields: dict[str, int] = {}
  2145. for name in dir(obj):
  2146. if name[0] != "_" and isinstance(getattr(obj, name), Marker):
  2147. fields[name] = getattr(obj, name).index
  2148. assert len(fields) == cls.n_fields # type: ignore[attr-defined]
  2149. return tuple(sorted(fields, key=fields.get)) # type: ignore[arg-type]
  2150. def checkpoint_params(gm: torch.fx.GraphModule) -> Callable[[], None]:
  2151. with torch.no_grad():
  2152. rng_state = torch.clone(torch.random.get_rng_state())
  2153. if torch.cuda.is_available():
  2154. cuda_rng_state = torch.clone(torch.cuda.get_rng_state())
  2155. saved_state = [
  2156. (param, param._version, torch.clone(param))
  2157. # pyrefly: ignore [bad-argument-type]
  2158. for param in itertools.chain(gm.parameters(), gm.buffers())
  2159. ]
  2160. def restore() -> None:
  2161. with torch.no_grad():
  2162. torch.random.set_rng_state(rng_state)
  2163. if torch.cuda.is_available():
  2164. torch.cuda.set_rng_state(cuda_rng_state)
  2165. for param, version, original_value in saved_state:
  2166. if param._version != version:
  2167. param.copy_(original_value)
  2168. return restore
  2169. def timed(
  2170. model: Any, example_inputs: Iterable[Any], times: int = 1
  2171. ) -> tuple[Any, float]:
  2172. if torch.cuda.is_available():
  2173. synchronize = torch.cuda.synchronize
  2174. else:
  2175. synchronize = nothing
  2176. synchronize()
  2177. gc.collect()
  2178. torch.manual_seed(1337)
  2179. t0 = time.perf_counter()
  2180. for _ in range(times):
  2181. result = model(*example_inputs)
  2182. synchronize()
  2183. t1 = time.perf_counter()
  2184. return result, t1 - t0 # type: ignore[possibly-undefined]
  2185. def check_is_cuda(gm: torch.fx.GraphModule, example_inputs: Iterable[Any]) -> bool:
  2186. return all(x.is_cuda for x in itertools.chain(example_inputs, gm.parameters(True)))
  2187. @lru_cache(32)
  2188. def rot_n_helper(n: int) -> Callable[..., Any]:
  2189. assert n > 1
  2190. vars = [f"v{i}" for i in range(n)]
  2191. rotated = reversed(vars[-1:] + vars[:-1])
  2192. fn = eval(f"lambda {','.join(vars)}: ({','.join(rotated)})")
  2193. fn.__name__ = f"rot_{n}_helper"
  2194. return fn
  2195. common_constant_types: set[type] = {
  2196. int,
  2197. float,
  2198. complex,
  2199. bool,
  2200. str,
  2201. bytes,
  2202. type(None),
  2203. Ellipsis.__class__,
  2204. NotImplemented.__class__,
  2205. types.CodeType,
  2206. # Commonly used immutable types from torch.
  2207. torch.device,
  2208. torch.dtype,
  2209. torch.memory_format,
  2210. torch.layout,
  2211. torch.finfo,
  2212. torch.iinfo,
  2213. torch.nn.attention.SDPBackend,
  2214. torch.cuda._CudaDeviceProperties,
  2215. }
  2216. if has_triton_package():
  2217. import triton
  2218. common_constant_types.add(triton.language.dtype)
  2219. """
  2220. Difference between is_safe_constant and common_constant_types.
  2221. * common_constant_types: Constants would be wrapped by VariableBuilder.wrap_literal
  2222. as ConstantVariable.
  2223. * is_safe_constant: Constants can be loaded by LOAD_CONST bytecode.
  2224. """
  2225. def is_safe_constant(v: Any) -> bool:
  2226. if istype(v, (tuple, frozenset)):
  2227. return all(map(is_safe_constant, v))
  2228. return isinstance(
  2229. v,
  2230. (
  2231. enum.Enum,
  2232. type,
  2233. torch.Size,
  2234. typing._GenericAlias, # type: ignore[attr-defined]
  2235. types.GenericAlias,
  2236. ),
  2237. ) or istype(
  2238. v,
  2239. common_constant_types | {slice},
  2240. )
  2241. @functools.cache
  2242. def common_constants() -> set[int]:
  2243. return {
  2244. # We zero-one specialize shapes, so specialize these constants
  2245. # too
  2246. 0,
  2247. 1,
  2248. }
  2249. def is_torch_sym(value: Any) -> TypeGuard[Union[torch.SymBool, torch.SymInt]]:
  2250. return isinstance(value, (torch.SymBool, torch.SymInt)) and not isinstance(
  2251. value.node, torch.nested._internal.nested_int.NestedIntNode
  2252. )
  2253. def is_int_specialization_case(value: Any, source: Any) -> bool:
  2254. from .source import is_from_defaults
  2255. return not TracingContext.get().force_unspec_int_unbacked_size_like and (
  2256. # Assume integers from global variables want to be specialized
  2257. not source.guard_source.is_local()
  2258. # Assume that integers that came from NN modules want to be
  2259. # specialized (as we don't expect users to be changing the
  2260. # NN modules on the fly), unless explicitly disabled
  2261. or (
  2262. source.guard_source.is_specialized_nn_module()
  2263. and not config.allow_unspec_int_on_nn_module
  2264. )
  2265. or (
  2266. source.guard_source.is_unspecialized_builtin_nn_module()
  2267. and not config.allow_unspec_int_on_nn_module
  2268. )
  2269. or (
  2270. source.guard_source.is_unspecialized_nn_module()
  2271. and not config.allow_unspec_int_on_nn_module
  2272. )
  2273. or is_from_defaults(source)
  2274. # TODO: Delete this condition when rollout is done. NB: this
  2275. # condition never evaluates True in open source
  2276. or (
  2277. not justknobs_check("pytorch/dynamo:enable_unspecialize_zero_one_plain_int")
  2278. and value in common_constants()
  2279. )
  2280. )
  2281. def specialize_symnode(arg: Any) -> Any:
  2282. from .variables import ConstantVariable, LazyVariableTracker, SymNodeVariable
  2283. # Guard and specialize
  2284. if isinstance(arg, LazyVariableTracker) and not arg.is_realized():
  2285. # Find if the arg would be realized as SymNodeVariable later on. If yes,
  2286. # realize it and specialize. Else return the arg.
  2287. source = arg.original_source()
  2288. value = arg.original_value()
  2289. is_symnode_vt = is_torch_sym(value) or (
  2290. not config.specialize_int
  2291. and type(value) is int
  2292. and not is_int_specialization_case(value, source)
  2293. )
  2294. if not is_symnode_vt:
  2295. return arg
  2296. if isinstance(arg, SymNodeVariable):
  2297. return ConstantVariable.create(arg.evaluate_expr())
  2298. return arg
  2299. def guard_if_dyn(arg: Any) -> Any:
  2300. from .variables import VariableTracker
  2301. arg = specialize_symnode(arg)
  2302. if isinstance(arg, VariableTracker) and arg.is_python_constant():
  2303. return arg.as_python_constant()
  2304. return arg
  2305. def check_constant_args(args: Iterable[Any], kwargs: Mapping[Any, Any]) -> bool:
  2306. return all(x.is_python_constant() for x in itertools.chain(args, kwargs.values()))
  2307. def check_unspec_python_args(args: Iterable[Any], kwargs: Mapping[Any, Any]) -> bool:
  2308. from .variables import VariableTracker
  2309. from .variables.tensor import UnspecializedPythonVariable
  2310. unspec_count = 0
  2311. for x in itertools.chain(args, kwargs.values()):
  2312. if isinstance(x, UnspecializedPythonVariable):
  2313. unspec_count += 1
  2314. elif not (isinstance(x, VariableTracker) and x.is_python_constant()):
  2315. return False
  2316. return unspec_count > 0
  2317. def check_unspec_or_constant_args(
  2318. args: Iterable[Any], kwargs: Mapping[Any, Any]
  2319. ) -> bool:
  2320. # A fused version of:
  2321. # return check_constant_args(args, kwargs) or check_unspec_python_args(args, kwargs)
  2322. from .variables.tensor import UnspecializedPythonVariable
  2323. for x in itertools.chain(args, kwargs.values()):
  2324. if not (x.is_python_constant() or isinstance(x, UnspecializedPythonVariable)):
  2325. return False
  2326. return True
  2327. def check_numpy_ndarray_args(args: Iterable[Any], kwargs: Mapping[Any, Any]) -> bool:
  2328. from .variables.tensor import NumpyNdarrayVariable
  2329. return any(
  2330. isinstance(x, NumpyNdarrayVariable)
  2331. for x in itertools.chain(args, kwargs.values())
  2332. )
  2333. dict_keys: type[KeysView[Any]] = type({}.keys())
  2334. dict_values: type[ValuesView[Any]] = type({}.values())
  2335. dict_items: type[ItemsView[Any, Any]] = type({}.items())
  2336. odict_values: type[ValuesView[Any]] = type(OrderedDict().values())
  2337. # pyrefly: ignore [bad-assignment]
  2338. tuple_iterator: type[Iterator[Any]] = type(iter(()))
  2339. # pyrefly: ignore [bad-assignment]
  2340. range_iterator: type[Iterator[Any]] = type(iter(range(0)))
  2341. tuple_iterator_len = tuple_iterator.__length_hint__ # type: ignore[attr-defined]
  2342. object_new = object.__new__
  2343. dict_new = dict.__new__
  2344. dict_methods = {
  2345. method
  2346. for method in itertools.chain(dict.__dict__.values(), OrderedDict.__dict__.values())
  2347. if callable(method)
  2348. }
  2349. set_methods = {method for method in set.__dict__.values() if callable(method)}
  2350. frozenset_methods = {
  2351. method for method in frozenset.__dict__.values() if callable(method)
  2352. }
  2353. tuple_new = tuple.__new__
  2354. tuple_methods = {method for method in tuple.__dict__.values() if callable(method)}
  2355. list_methods = {method for method in list.__dict__.values() if callable(method)}
  2356. list_getitem = list.__getitem__
  2357. str_methods = {method for method in str.__dict__.values() if callable(method)}
  2358. # EnumType is the metaclass for Enum classes
  2359. enum_type_methods = {
  2360. method for method in type(enum.Enum).__dict__.values() if callable(method)
  2361. }
  2362. K = TypeVar("K")
  2363. V = TypeVar("V")
  2364. def builtin_dict_keys(d: dict[K, V]) -> KeysView[K]:
  2365. # Avoids overridden keys method of the dictionary
  2366. assert isinstance(d, dict)
  2367. return dict.keys(d)
  2368. def get_items_from_dict(obj: dict[K, V]) -> Iterable[tuple[K, Union[V, Any]]]:
  2369. # Get items without calling the user defined __getitem__ or keys method.
  2370. assert isinstance(obj, dict)
  2371. if istype(obj, (dict, OrderedDict)):
  2372. return obj.items()
  2373. elif isinstance(obj, OrderedDict):
  2374. # pyrefly: ignore [bad-argument-type]
  2375. return [(k, OrderedDict.__getitem__(obj, k)) for k in OrderedDict.keys(obj)]
  2376. else:
  2377. # pyrefly: ignore [bad-argument-type]
  2378. return [(k, dict.__getitem__(obj, k)) for k in dict.keys(obj)]
  2379. def nn_module_new(cls: Any) -> Any:
  2380. obj = object_new(cls)
  2381. # pyrefly: ignore [bad-argument-type]
  2382. torch.nn.Module.__init__(obj)
  2383. return obj
  2384. def product(it: Iterable[T]) -> int:
  2385. return functools.reduce(operator.mul, it, 1)
  2386. def tuple_iterator_getitem(it: Any, index: int) -> Any:
  2387. _, (obj,), start = it.__reduce__()
  2388. return obj[start + index]
  2389. def dataclass_fields(cls: Any) -> Any:
  2390. return torch._dynamo.disable(dataclasses.fields)(cls)
  2391. iter_next = next
  2392. def normalize_range_iter(range_iter: Any) -> tuple[int, int, int]:
  2393. _, (range_obj,), maybe_idx = range_iter.__reduce__()
  2394. # In 3.12+, `maybe_idx` could be None, and `range_obj.start` would've been
  2395. # already incremented by the current index.
  2396. # The index (maybe_idx) is the number of steps taken so far. To get the
  2397. # correct start value, one must add (maybe_idx * step) to the original
  2398. # start. See:
  2399. # https://github.com/python/cpython/blob/ea77feecbba389916af8f90b2fc77f07910a2963/Objects/rangeobject.c#L885-L899
  2400. start = range_obj.start + (maybe_idx or 0) * range_obj.step
  2401. stop = range_obj.stop
  2402. step = range_obj.step
  2403. return (start, stop, step)
  2404. def to_subclass(t: Any, cls: type) -> Any:
  2405. return t.as_subclass(cls)
  2406. dict_getitem = dict.__getitem__
  2407. @torch.fx.wrap
  2408. def dict_keys_getitem(d: dict[Any, Any], n: int) -> Any:
  2409. # Call dict(d) to prevent calling overridden __iter__/keys
  2410. dict_class = dict
  2411. if isinstance(d, OrderedDict):
  2412. dict_class = OrderedDict
  2413. # pyrefly: ignore [bad-argument-type]
  2414. return next(itertools.islice(dict_class.keys(d), n, n + 1))
  2415. def set_getitem(s: set[T], n: int) -> T:
  2416. # Set ordering might not be stable
  2417. return list(s)[n]
  2418. def enum_repr(value: Any, local: bool) -> str:
  2419. # enum class can override __str__ method. Use __class__ and name attribute
  2420. # to extract the class name and key name.
  2421. name = value.__class__.__name__
  2422. val = value.name
  2423. scope = "L" if local else "G"
  2424. local_name = f'{scope}["{name}"].{val}'
  2425. return local_name
  2426. def set_example_value(node: torch.fx.Node, example_value: Any) -> None:
  2427. # NB: example_value is a bit of a misnomer, because this is always a fake
  2428. # tensor of some sort. Furthermore, these example values serve as the
  2429. # runtime state of Dynamo tracing, which means if metadata mutation
  2430. # occurs, the example_value gets directly updated (so you can't rely on
  2431. # this to accurately reflect what the state of the value was at the time
  2432. # the program was traced).
  2433. node.meta["example_value"] = example_value
  2434. fake_mode = TracingContext.get().fake_mode
  2435. assert fake_mode is not None
  2436. shape_env = fake_mode.shape_env
  2437. if (
  2438. symbol_to_path
  2439. := torch.fx.experimental.symbolic_shapes.compute_unbacked_bindings(
  2440. shape_env, example_value
  2441. )
  2442. ):
  2443. node.meta["unbacked_bindings"] = symbol_to_path
  2444. def _get_fake_tensor(vt: VariableTracker) -> Any:
  2445. fake_tensor = vt.as_proxy().node.meta.get("example_value")
  2446. if not is_fake(fake_tensor):
  2447. from . import graph_break_hints
  2448. from .exc import unimplemented
  2449. unimplemented(
  2450. gb_type="Cannot check Tensor object identity without its fake value",
  2451. context=str(fake_tensor),
  2452. explanation="TensorVariable is missing a fake example_value.",
  2453. hints=[*graph_break_hints.DYNAMO_BUG],
  2454. )
  2455. return fake_tensor
  2456. def slice_length(s: slice, seq_len: int) -> int:
  2457. start, stop, step = s.indices(seq_len)
  2458. return max(0, (stop - start + (step - (1 if step > 0 else -1))) // step)
  2459. def raise_args_mismatch(
  2460. tx: InstructionTranslatorBase,
  2461. name: str,
  2462. expect: str = "",
  2463. actual: str = "",
  2464. ) -> None:
  2465. from torch._dynamo.exc import raise_observed_exception
  2466. from torch._dynamo.variables import ConstantVariable
  2467. msg_str = (
  2468. f"wrong number of arguments or keyword arguments for {name}() call.\n"
  2469. f" Expect: {expect}\n"
  2470. f" Actual: {actual}"
  2471. )
  2472. raise_observed_exception(
  2473. TypeError,
  2474. tx,
  2475. args=[ConstantVariable(msg_str)],
  2476. )
  2477. def iter_contains(
  2478. items: Iterable[Any],
  2479. search: Any,
  2480. tx: InstructionTranslator,
  2481. check_tensor_identity: bool = False,
  2482. ) -> Any:
  2483. from .variables import ConstantVariable
  2484. if search.is_python_constant():
  2485. found_const = any(
  2486. x.is_python_constant()
  2487. and x.as_python_constant() == search.as_python_constant()
  2488. for x in items
  2489. )
  2490. return ConstantVariable.create(found_const)
  2491. must_check_tensor_id = False
  2492. if check_tensor_identity and search.is_tensor():
  2493. must_check_tensor_id = True
  2494. # Match of Tensor means match of FakeTensor
  2495. search = _get_fake_tensor(search)
  2496. found: Optional[VariableTracker] = None
  2497. for x in items:
  2498. if must_check_tensor_id:
  2499. if x.is_tensor():
  2500. if search is _get_fake_tensor(x): # Object equivalence
  2501. return ConstantVariable.create(True)
  2502. else:
  2503. from torch._dynamo.variables.builder import SourcelessBuilder
  2504. check = SourcelessBuilder.create(tx, operator.eq).call_function(
  2505. tx, [x, search], {}
  2506. )
  2507. if found is None:
  2508. found = check
  2509. else:
  2510. found = SourcelessBuilder.create(tx, operator.or_).call_function(
  2511. tx, [check, found], {}
  2512. )
  2513. if found is None:
  2514. found = ConstantVariable.create(False)
  2515. return found
  2516. def key_is_id(
  2517. k: Any,
  2518. ) -> TypeIs[Union[torch.Tensor, torch.nn.Module, MethodWrapperType]]:
  2519. """Returns whether it indexes dictionaries using its id"""
  2520. return isinstance(k, (torch.Tensor, torch.nn.Module, MethodWrapperType))
  2521. def key_to_id(value: Any) -> list[Any]:
  2522. return [id(k) if key_is_id(k) else k for k in value]
  2523. def const_repr(x: Any, *, local: Any) -> str:
  2524. from .trace_rules import is_builtin_callable
  2525. if isinstance(x, (list, tuple)):
  2526. elems_repr = ",".join(const_repr(s, local=local) for s in x)
  2527. if isinstance(x, list):
  2528. return f"[{elems_repr}]"
  2529. else:
  2530. assert isinstance(x, tuple)
  2531. if len(x) == 1:
  2532. return f"({elems_repr},)"
  2533. else:
  2534. return f"({elems_repr})"
  2535. elif isinstance(x, enum.Enum):
  2536. # To workaround repr(Enum) returning invalid global reference before python 3.11
  2537. # by calling enum_repr and removing quotes to render enum in guard code.
  2538. return enum_repr(x, local=local).replace("'", "")
  2539. elif is_builtin_callable(x):
  2540. return x.__name__
  2541. elif isinstance(x, type):
  2542. def fullname(o: Any) -> str:
  2543. klass = o.__class__
  2544. module = klass.__module__
  2545. if module == "builtins":
  2546. return klass.__qualname__ # avoid outputs like 'builtins.str'
  2547. return module + "." + klass.__qualname__
  2548. return fullname(x)
  2549. else:
  2550. return f"{x!r}"
  2551. def dict_keys_repr(const_keys: Any, *, local: Any) -> str:
  2552. keys_str = ",".join(const_repr(s, local=local) for s in const_keys)
  2553. return "[" + keys_str + "]"
  2554. GLOBAL_KEY_PREFIX = "__dict_key"
  2555. from torch._subclasses import UnsupportedFakeTensorException # noqa: F401
  2556. def get_safe_global_name(tx: InstructionTranslatorBase, root: str, obj: Any) -> str:
  2557. # The global_mangled_class_name should be different for different
  2558. # invocations of torch.compile. Otherwise, we can run into a situation
  2559. # where multiple torch.compile invocations reuse the same global name,
  2560. # but the global's lifetime is tied to the first invocation (and
  2561. # may be deleted when the first torch.compile invocation is deleted)
  2562. # We mangle it based off of the output_graph's id.
  2563. return f"{root}_{id(obj)}_c{tx.output.compile_id}"
  2564. def is_in(item: T, *containers: Container[T]) -> bool:
  2565. for container in containers:
  2566. if item in container:
  2567. return True
  2568. return False
  2569. def get_unique_name_wrt(
  2570. prefix: str, *containers: Any, requires_suffix: bool = False
  2571. ) -> str:
  2572. """
  2573. Return a name that starts with `prefix` and is not in any of the
  2574. `containers` (e.g., map, set).
  2575. """
  2576. if not requires_suffix and not is_in(prefix, *containers):
  2577. return prefix
  2578. for i in itertools.count():
  2579. candidate = f"{prefix}_{i}"
  2580. if not is_in(candidate, *containers):
  2581. return candidate
  2582. raise AssertionError("unreachable")
  2583. def wrap_fake_exception(fn: Callable[[], Any]) -> Any:
  2584. try:
  2585. return fn()
  2586. except UnsupportedFakeTensorException as e:
  2587. from .exc import unimplemented
  2588. msg = f"Encountered exception ({e.reason}) during fake tensor propagation."
  2589. log.warning(msg)
  2590. unimplemented(
  2591. gb_type="Fake tensor propagation exception",
  2592. context=str(e.reason),
  2593. explanation=msg,
  2594. hints=[],
  2595. from_exc=e,
  2596. )
  2597. def deepcopy_to_fake_tensor(
  2598. obj: Any, fake_mode: torch._subclasses.fake_tensor.FakeTensorMode
  2599. ) -> Any:
  2600. with torch._subclasses.fake_tensor.FakeCopyMode(fake_mode):
  2601. return wrap_fake_exception(lambda: copy.deepcopy(obj))
  2602. def rmse(ref: torch.Tensor, res: torch.Tensor) -> torch.Tensor:
  2603. """
  2604. Calculate root mean squared error
  2605. """
  2606. return torch.sqrt(torch.mean(torch.square(ref - res)))
  2607. def bitwise_same(ref: Any, res: Any, equal_nan: bool = False) -> bool:
  2608. return same(
  2609. ref,
  2610. res,
  2611. tol=0.0,
  2612. equal_nan=equal_nan,
  2613. )
  2614. def same(
  2615. ref: Any,
  2616. res: Any,
  2617. fp64_ref: Any = None,
  2618. cos_similarity: bool = False,
  2619. tol: float = 1e-4,
  2620. equal_nan: bool = False,
  2621. exact_dtype: bool = True,
  2622. relax_numpy_equality: bool = False,
  2623. ignore_non_fp: bool = False,
  2624. log_error: Callable[..., None] = log.error,
  2625. use_larger_multiplier_for_smaller_tensor: bool = False,
  2626. force_max_multiplier: bool = False,
  2627. use_iou_for_bool: bool = False,
  2628. iou_threshold: float = 0.99,
  2629. ) -> bool:
  2630. """Check correctness to see if ref and res match"""
  2631. if fp64_ref is None:
  2632. fp64_ref = ref
  2633. if isinstance(
  2634. ref, (list, tuple, collections.deque, torch.nn.ParameterList, torch.Size)
  2635. ):
  2636. assert isinstance(res, (list, tuple, collections.deque)), (
  2637. f"type mismatch {type(ref)} {type(res)}"
  2638. )
  2639. if len(ref) != len(res):
  2640. log_error("Length mismatch")
  2641. return False
  2642. return len(ref) == len(res) and all(
  2643. same(
  2644. ai,
  2645. bi,
  2646. fp64_refi,
  2647. cos_similarity,
  2648. tol,
  2649. equal_nan,
  2650. exact_dtype,
  2651. relax_numpy_equality,
  2652. ignore_non_fp,
  2653. log_error=log_error,
  2654. use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor,
  2655. force_max_multiplier=force_max_multiplier,
  2656. use_iou_for_bool=use_iou_for_bool,
  2657. iou_threshold=iou_threshold,
  2658. )
  2659. for ai, bi, fp64_refi in zip(ref, res, fp64_ref)
  2660. )
  2661. elif type(ref).__name__ == "QuestionAnsweringModelOutput":
  2662. # This skips checking accuracy for start_logits/end_logits.
  2663. # Tentatively, start_logits/end_logits appear to be very prone to
  2664. # inaccuracies and is somewhat subsumed by checking the loss.
  2665. return same(
  2666. ref.loss,
  2667. res.loss,
  2668. fp64_ref.loss,
  2669. cos_similarity,
  2670. tol,
  2671. equal_nan,
  2672. exact_dtype,
  2673. relax_numpy_equality,
  2674. ignore_non_fp,
  2675. log_error=log_error,
  2676. use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor,
  2677. force_max_multiplier=force_max_multiplier,
  2678. use_iou_for_bool=use_iou_for_bool,
  2679. iou_threshold=iou_threshold,
  2680. )
  2681. elif isinstance(ref, dict):
  2682. assert isinstance(res, dict)
  2683. assert set(ref.keys()) == set(res.keys()), (
  2684. f"keys mismatch {set(ref.keys())} == {set(res.keys())}"
  2685. )
  2686. for k in sorted(ref.keys()):
  2687. if not (
  2688. same(
  2689. ref[k],
  2690. res[k],
  2691. fp64_ref[k],
  2692. cos_similarity=cos_similarity,
  2693. tol=tol,
  2694. equal_nan=equal_nan,
  2695. exact_dtype=exact_dtype,
  2696. relax_numpy_equality=relax_numpy_equality,
  2697. ignore_non_fp=ignore_non_fp,
  2698. log_error=log_error,
  2699. use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor,
  2700. force_max_multiplier=force_max_multiplier,
  2701. use_iou_for_bool=use_iou_for_bool,
  2702. iou_threshold=iou_threshold,
  2703. )
  2704. ):
  2705. log_error("Accuracy failed for key name %s", k)
  2706. return False
  2707. return True
  2708. elif isinstance(ref, set):
  2709. assert isinstance(res, set)
  2710. assert set(ref) == set(res), f"elements mismatch {set(ref)} == {set(res)}"
  2711. return True
  2712. elif isinstance(ref, (torch.Tensor, float)):
  2713. assert not isinstance(ref, torch._subclasses.FakeTensor)
  2714. assert not isinstance(res, torch._subclasses.FakeTensor)
  2715. def to_tensor(t: Any) -> torch.Tensor:
  2716. return t if isinstance(t, torch.Tensor) else torch.tensor(t)
  2717. ref, res, fp64_ref = (to_tensor(val) for val in (ref, res, fp64_ref))
  2718. if ref.is_sparse:
  2719. assert res.is_sparse
  2720. ref = ref.to_dense()
  2721. res = res.to_dense()
  2722. assert isinstance(res, torch.Tensor), f"type mismatch {type(ref)} {type(res)}"
  2723. if exact_dtype:
  2724. if ref.dtype != res.dtype:
  2725. log_error("dtype mismatch %s, %s", ref.dtype, res.dtype)
  2726. return False
  2727. if ref.dtype == torch.bool:
  2728. if ignore_non_fp:
  2729. return True
  2730. if use_iou_for_bool:
  2731. # Use IoU (Intersection over Union) metric for boolean mask comparison.
  2732. # This is useful for segmentation models where small floating-point
  2733. # differences get thresholded into boolean masks.
  2734. intersection = (ref & res).sum().float()
  2735. union = (ref | res).sum().float()
  2736. if union == 0:
  2737. # Both masks are empty
  2738. return bool(intersection == 0)
  2739. iou = (intersection / union).item()
  2740. if iou < iou_threshold:
  2741. log_error(
  2742. "IoU accuracy failed: %.4f < %.2f (intersection=%d, union=%d, ref_sum=%d, res_sum=%d, shape=%s)",
  2743. iou,
  2744. iou_threshold,
  2745. int(intersection.item()),
  2746. int(union.item()),
  2747. int(ref.sum().item()),
  2748. int(res.sum().item()),
  2749. list(ref.shape),
  2750. )
  2751. return False
  2752. return True
  2753. # triton stores bool as int8, so add this for more accurate checking
  2754. r = torch.allclose(
  2755. ref.to(dtype=torch.uint8),
  2756. res.to(dtype=torch.uint8),
  2757. atol=tol,
  2758. rtol=tol,
  2759. equal_nan=equal_nan,
  2760. )
  2761. if not r:
  2762. log_error("Accuracy failed: uint8 tensor did not match")
  2763. return r
  2764. if cos_similarity:
  2765. ref = ref.flatten().to(torch.float32)
  2766. res = res.flatten().to(torch.float32)
  2767. if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=True):
  2768. # early exit that handles zero/nan better
  2769. # cosine_similarity(zeros(10), zeros(10), dim=0) is 0
  2770. return True
  2771. score = torch.nn.functional.cosine_similarity(ref, res, dim=0, eps=1e-6)
  2772. if score < 0.99:
  2773. log.warning("Similarity score=%s", score.detach().cpu().item())
  2774. return bool(score >= 0.99)
  2775. else:
  2776. if not exact_dtype:
  2777. ref = ref.to(res.dtype)
  2778. # First try usual allclose
  2779. if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=equal_nan):
  2780. return True
  2781. # Check error from fp64 version
  2782. if fp64_ref.dtype == torch.float64:
  2783. # Fix a corner case that res and fp64_ref does not contains NaN and match (with loose tolerance)
  2784. # while the ref contains NaN. In this case, RMSE should not match any ways.
  2785. # But res is 'BETTER' than ref so we count it pass.
  2786. #
  2787. # This happens for Super_SloMo when loop ordering after fusion is enabled:
  2788. # https://gist.github.com/shunting314/11f235c70f7db0d52718d26f4a701cab
  2789. loose_tol = 1e-2 * 4
  2790. if (
  2791. not fp64_ref.isnan().any()
  2792. and not res.isnan().any()
  2793. and ref.isnan().any()
  2794. and torch.allclose(
  2795. fp64_ref.to(dtype=res.dtype),
  2796. res,
  2797. atol=loose_tol,
  2798. rtol=loose_tol,
  2799. equal_nan=equal_nan,
  2800. )
  2801. ):
  2802. return True
  2803. ref_error = rmse(fp64_ref, ref).item()
  2804. # ref unable to produce this with stable numerics in this precision, ignore
  2805. if math.isnan(ref_error):
  2806. log.warning(
  2807. "Found nan in reference. Consider running in higher precision."
  2808. )
  2809. res_error = rmse(fp64_ref, res).item()
  2810. def get_multiplier() -> float:
  2811. # In some particular cases, we expect high difference in results.
  2812. # At the moment one of this cases is inductor freezing bfloat16 convolution const folding.
  2813. # In case of it the res_error is at least one order of magnitude higher.
  2814. if force_max_multiplier:
  2815. return 10.0
  2816. # In the case of using AMP (Automatic Mixed Precision), certain models have
  2817. # failed the benchmark's correctness check. However, the end-to-end model's
  2818. # accuracy when comparing AMP with FP32 is within a difference of less than 0.1%.
  2819. # Thus, it's possible that the correctness check failures for these models are
  2820. # false alarms. We use multiplier of 3 instead of 2 to avoid these false alarms.
  2821. multiplier = (
  2822. 3.0 if res.dtype in (torch.float16, torch.bfloat16) else 2.0
  2823. )
  2824. if use_larger_multiplier_for_smaller_tensor and (
  2825. fp64_ref.numel() <= 10
  2826. ):
  2827. multiplier = 10.0
  2828. elif use_larger_multiplier_for_smaller_tensor and (
  2829. fp64_ref.numel() <= 500
  2830. ):
  2831. multiplier = 8.0
  2832. elif (
  2833. fp64_ref.numel() < 1000
  2834. or (ref.ndim == 4 and ref.shape[-1] == ref.shape[-2] == 1)
  2835. # large tol means a benchmark has been specified as REQUIRE_HIGHER_TOLERANCE
  2836. or tol >= 2 * 1e-2
  2837. ):
  2838. # In the presence of noise, noise might dominate our error
  2839. # metric for smaller tensors.
  2840. # Similarly, for 1x1 kernels, there seems to be high noise with amp.
  2841. multiplier = 3.0
  2842. return multiplier
  2843. multiplier = get_multiplier()
  2844. passes_test = res_error <= (multiplier * ref_error + tol / 10.0)
  2845. if (
  2846. not passes_test
  2847. and equal_nan
  2848. and math.isnan(ref_error)
  2849. and math.isnan(res_error)
  2850. # Some unit test for the accuracy minifier relies on
  2851. # returning false in this case.
  2852. and not torch._inductor.config.cpp.inject_relu_bug_TESTING_ONLY
  2853. ):
  2854. passes_test = True
  2855. if not passes_test:
  2856. log_error(
  2857. "RMSE (res-fp64): %.5f, (ref-fp64): %.5f and shape=%s. res.dtype: %s, multiplier: %f, tol: %f"
  2858. ", use_larger_multiplier_for_smaller_tensor: %d",
  2859. res_error,
  2860. ref_error,
  2861. res.size(),
  2862. res.dtype,
  2863. multiplier,
  2864. tol,
  2865. use_larger_multiplier_for_smaller_tensor,
  2866. )
  2867. return passes_test
  2868. if ignore_non_fp:
  2869. return True
  2870. log_error("Accuracy failed: allclose not within tol=%s", tol)
  2871. return False
  2872. elif isinstance(ref, (str, int, type(None), bool, torch.device)):
  2873. if ignore_non_fp:
  2874. return True
  2875. r = ref == res
  2876. if not r:
  2877. log_error("Accuracy failed (%s): %s != %s", type(ref), ref, res)
  2878. return r
  2879. elif is_numpy_int_type(ref) or is_numpy_float_type(ref):
  2880. if relax_numpy_equality and not (
  2881. is_numpy_int_type(res) or is_numpy_float_type(res)
  2882. ):
  2883. ref = ref.item()
  2884. r = (type(ref) is type(res)) and (ref == res)
  2885. if not r:
  2886. log_error("Accuracy failed (numpy): %s != %s", ref, res)
  2887. return r
  2888. elif is_numpy_ndarray(ref):
  2889. return (type(ref) is type(res)) and same(
  2890. torch.as_tensor(ref),
  2891. torch.as_tensor(res),
  2892. fp64_ref,
  2893. cos_similarity=cos_similarity,
  2894. tol=tol,
  2895. equal_nan=equal_nan,
  2896. exact_dtype=exact_dtype,
  2897. relax_numpy_equality=relax_numpy_equality,
  2898. ignore_non_fp=ignore_non_fp,
  2899. log_error=log_error,
  2900. use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor,
  2901. )
  2902. elif type(ref).__name__ in (
  2903. "MaskedLMOutput",
  2904. "Seq2SeqLMOutput",
  2905. "CausalLMOutputWithCrossAttentions",
  2906. "LongformerMaskedLMOutput",
  2907. "Instances",
  2908. "SquashedNormal",
  2909. "Boxes",
  2910. "Normal",
  2911. "TanhTransform",
  2912. "Foo",
  2913. "Variable",
  2914. ):
  2915. assert type(ref) is type(res)
  2916. return all(
  2917. same(
  2918. getattr(ref, key),
  2919. getattr(res, key),
  2920. getattr(fp64_ref, key),
  2921. cos_similarity=cos_similarity,
  2922. tol=tol,
  2923. equal_nan=equal_nan,
  2924. exact_dtype=exact_dtype,
  2925. relax_numpy_equality=relax_numpy_equality,
  2926. ignore_non_fp=ignore_non_fp,
  2927. log_error=log_error,
  2928. use_larger_multiplier_for_smaller_tensor=use_larger_multiplier_for_smaller_tensor,
  2929. )
  2930. for key in ref.__dict__
  2931. )
  2932. else:
  2933. raise RuntimeError(f"unsupported type: {type(ref).__name__}")
  2934. def format_func_info(code: CodeType) -> str:
  2935. short_filename = code.co_filename.split("/")[-1]
  2936. return f"'{code.co_name}' ({short_filename}:{code.co_firstlineno})"
  2937. @contextlib.contextmanager
  2938. def disable_cache_limit() -> Generator[None, None, None]:
  2939. prior = config.recompile_limit
  2940. # pyrefly: ignore [bad-assignment]
  2941. config.recompile_limit = sys.maxsize
  2942. prior_acc_limit = config.accumulated_recompile_limit
  2943. # pyrefly: ignore [bad-assignment]
  2944. config.accumulated_recompile_limit = sys.maxsize
  2945. try:
  2946. yield
  2947. finally:
  2948. config.recompile_limit = prior
  2949. config.accumulated_recompile_limit = prior_acc_limit
  2950. # map from transformed code back to original user code
  2951. orig_code_map = ExactWeakKeyDictionary()
  2952. # keep a record of code_obj -> list of guard failure reasons for logging
  2953. guard_failures: collections.defaultdict[Any, list[Any]] = collections.defaultdict(list)
  2954. # Keep a record of graph break reasons for logging
  2955. graph_break_reasons: list[torch._dynamo.output_graph.GraphCompileReason] = []
  2956. # keep record of compiled code, if we are in "error if recompile"
  2957. # to track code that dynamo has compiled previously
  2958. seen_code_map = ExactWeakKeyDictionary()
  2959. # return same dir unless user changes config between calls
  2960. @functools.cache
  2961. def _get_debug_dir(root_dir: str) -> str:
  2962. dir_name = (
  2963. "run_"
  2964. + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f")
  2965. # use pid to avoid conflicts among ranks
  2966. + "-pid_"
  2967. + str(os.getpid())
  2968. )
  2969. return os.path.join(root_dir, dir_name)
  2970. def get_debug_dir() -> str:
  2971. debug_root = config.debug_dir_root
  2972. return _get_debug_dir(debug_root)
  2973. def extract_fake_example_value(node: torch.fx.Node, required: bool = True) -> Any:
  2974. if "example_value" in node.meta and is_fake(node.meta["example_value"]):
  2975. return node.meta["example_value"]
  2976. elif required:
  2977. from torch._dynamo.exc import unimplemented
  2978. from . import graph_break_hints
  2979. unimplemented(
  2980. gb_type="Missing FakeTensor example value",
  2981. context=str(node),
  2982. explanation=f"`FakeTensor` example value was required for {node} but not available.",
  2983. hints=[*graph_break_hints.DYNAMO_BUG],
  2984. )
  2985. else:
  2986. return None
  2987. def ensure_graph_fake(e: Any, tx: InstructionTranslatorBase) -> Any:
  2988. assert maybe_get_fake_mode(e) is tx.fake_mode
  2989. return e
  2990. def get_fake_values_from_nodes(
  2991. tx: InstructionTranslatorBase, nodes: Any, allow_non_graph_fake: bool
  2992. ) -> Any:
  2993. def visit(n: torch.fx.Node) -> Any:
  2994. if n.op == "call_function" and "example_value" not in n.meta:
  2995. # fake tensor validity is checked inside get_fake_value using
  2996. # ensure_graph_fake
  2997. return get_fake_value(n, tx, allow_non_graph_fake)
  2998. elif n.op == "get_attr" and "example_value" not in n.meta:
  2999. assert n.target in tx.output.nn_modules
  3000. gm = tx.output.nn_modules[n.target] # type: ignore[index]
  3001. assert isinstance(gm, torch.fx.GraphModule)
  3002. return gm
  3003. out = n.meta["example_value"]
  3004. if not allow_non_graph_fake and isinstance(out, torch.Tensor):
  3005. return ensure_graph_fake(out, tx)
  3006. return out
  3007. return torch.fx.node.map_arg(nodes, visit)
  3008. def get_concrete_sizes_from_symints(
  3009. msg: str, fake_mode: Optional[FakeTensorMode]
  3010. ) -> str:
  3011. """
  3012. Replace symbolic size expressions (like 's0', 's94') in error messages
  3013. with their concrete runtime values for better readability.
  3014. Example: "size (s94)" -> "size (s94: hint= 10)" if s94's value is 10.
  3015. """
  3016. import re
  3017. from sympy.core.numbers import Integer
  3018. if fake_mode is None:
  3019. return msg
  3020. pattern = r"\(s(\d+)\)"
  3021. assert fake_mode.shape_env is not None
  3022. shape_env = fake_mode.shape_env
  3023. backed_var_to_val = shape_env.backed_var_to_val
  3024. def replace_sym(match: Any) -> str:
  3025. sym_name = f"s{match.group(1)}"
  3026. val = next(
  3027. (v for k, v in backed_var_to_val.items() if k.name == sym_name),
  3028. None,
  3029. )
  3030. if isinstance(val, (int, Integer)):
  3031. return f"({sym_name}: hint = {str(val)})"
  3032. return match.group(0)
  3033. msg = re.sub(pattern, replace_sym, msg)
  3034. return msg
  3035. def _wrap_graph_break_with_torch_runtime_err(gb_fn: Callable[[], NoReturn]) -> NoReturn:
  3036. from .exc import TorchRuntimeError, Unsupported
  3037. try:
  3038. gb_fn()
  3039. except Unsupported as e:
  3040. exc = TorchRuntimeError(str(e), getattr(e, "real_stack", None))
  3041. raise exc.with_traceback(e.__traceback__) from None
  3042. raise AssertionError("should be unreachable")
  3043. def get_fake_value(
  3044. node: torch.fx.Node,
  3045. tx: InstructionTranslatorBase,
  3046. allow_non_graph_fake: bool = False,
  3047. ) -> Any:
  3048. _t0 = time.time_ns()
  3049. try:
  3050. return _get_fake_value_impl(node, tx, allow_non_graph_fake)
  3051. finally:
  3052. tx.output.bytecode_tracing_timings.get_fake_value_ns += time.time_ns() - _t0
  3053. def _get_fake_value_impl(
  3054. node: torch.fx.Node,
  3055. tx: InstructionTranslatorBase,
  3056. allow_non_graph_fake: bool = False,
  3057. ) -> Any:
  3058. """
  3059. Run the computation represented by `node` using fake tensors and return the result.
  3060. allow_non_graph_fake: whether to allow the return result to be:
  3061. 1. non-fake or 2. fake that is not created by this instance of Dynamo.
  3062. If `True`, you must be prepared to deal with such return values, ideally
  3063. by further wrapping them as this graph's fakes.
  3064. """
  3065. from torch.utils._sympy.value_ranges import ValueRangeError
  3066. from . import graph_break_hints
  3067. from .exc import unimplemented, Unsupported, UserError, UserErrorType
  3068. op = node.op
  3069. # FX Node should always return the same fake value
  3070. if "example_value" in node.meta and is_fake(node.meta["example_value"]):
  3071. return node.meta["example_value"]
  3072. args, kwargs = get_fake_values_from_nodes(
  3073. tx, (node.args, node.kwargs), allow_non_graph_fake
  3074. )
  3075. if (
  3076. torch._dynamo.config.use_graph_deduplication
  3077. or torch._dynamo.config.track_nodes_for_deduplication
  3078. ):
  3079. flat_args_kwargs = get_fake_values_from_nodes(
  3080. tx, _get_flat_args(node, {}), allow_non_graph_fake
  3081. )
  3082. id_to_initial_version = {
  3083. id(arg): arg._version for arg in flat_args_kwargs if is_fake(arg)
  3084. }
  3085. else:
  3086. # pyrefly: ignore [implicit-any]
  3087. flat_args_kwargs = []
  3088. # pyrefly: ignore [implicit-any]
  3089. id_to_initial_version = {}
  3090. nnmodule = None
  3091. fake_mode = tx.fake_mode
  3092. assert fake_mode is not None
  3093. if op == "call_method" and len(args) > 0 and isinstance(args[0], torch.nn.Module):
  3094. # If the first argument is nn.Module, should copy to fake mode.
  3095. args = (deepcopy_to_fake_tensor(args[0], fake_mode),) + tuple(args[1:])
  3096. if op == "call_module":
  3097. nnmodule = tx.output.nn_modules[node.target] # type: ignore[index]
  3098. if is_lazy_module(nnmodule) and hasattr(nnmodule, "_initialize_hook"):
  3099. # In the case of a lazy module, we want to run
  3100. # the pre-hooks which initialize it.
  3101. # Afterwards, lazy module deletes its pre-hooks
  3102. # to avoid treating it as lazy on subsequent recompile.
  3103. nnmodule._infer_parameters(nnmodule, args)
  3104. # no matter it's lazy module or not, we should copy to fake mode.
  3105. nnmodule = deepcopy_to_fake_tensor(nnmodule, fake_mode)
  3106. if node.name in ["interpolate", "is_integer", "wrapped_gradient"] or any(
  3107. isinstance(a, complex) for a in args
  3108. ):
  3109. # We need to specialize symfloats for now. Eventually we should do a tensorify pass in dynamo.
  3110. args = tuple(
  3111. (
  3112. float(arg)
  3113. if isinstance(arg, torch.SymFloat) and arg.node.hint is not None
  3114. else arg
  3115. )
  3116. for arg in args
  3117. )
  3118. try:
  3119. with fake_mode, enable_python_dispatcher():
  3120. ret_val = wrap_fake_exception(
  3121. lambda: run_node(tx.output, node, args, kwargs, nnmodule)
  3122. )
  3123. except Unsupported:
  3124. raise
  3125. except RuntimeError as e:
  3126. cause: BaseException = e
  3127. if e.__cause__ is not None:
  3128. cause = e.__cause__
  3129. if isinstance(
  3130. cause, torch._subclasses.fake_tensor.DataDependentOutputException
  3131. ):
  3132. # capture_scalar_outputs only works for these ops right now
  3133. # see torch/_subclasses/fake_impls.py
  3134. if cause.func in (
  3135. torch.ops.aten.item.default,
  3136. torch.ops.aten._local_scalar_dense.default,
  3137. ):
  3138. # does this actually get triggered?
  3139. hints = [
  3140. "Enable tracing of data-dependent output operators with "
  3141. "`torch._dynamo.config.capture_scalar_outputs = True`",
  3142. ]
  3143. else:
  3144. hints = [
  3145. "Consider wrapping the operator into a PyTorch-understood custom operator "
  3146. "(see https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html)",
  3147. ]
  3148. unimplemented(
  3149. gb_type="Data dependent operator",
  3150. context=str(cause.func),
  3151. explanation=f"Operator `{cause.func}` has a non-Tensor output "
  3152. "whose value is dependent on the data of Tensor inputs.",
  3153. hints=hints,
  3154. from_exc=cause,
  3155. )
  3156. elif isinstance(
  3157. cause, torch._subclasses.fake_tensor.DynamicOutputShapeException
  3158. ):
  3159. if not torch._dynamo.config.capture_dynamic_output_shape_ops:
  3160. unimplemented(
  3161. gb_type="Dynamic shape operator",
  3162. context=str(cause.func),
  3163. explanation=f"Operator `{cause.func}`'s output shape depends on input Tensor data.",
  3164. hints=[
  3165. "Enable tracing of dynamic shape operators with "
  3166. "`torch._dynamo.config.capture_dynamic_output_shape_ops = True`",
  3167. ],
  3168. from_exc=cause,
  3169. )
  3170. else:
  3171. unimplemented(
  3172. gb_type="Dynamic shape operator (no meta kernel)",
  3173. context=str(cause.func),
  3174. explanation=f"Operator `{cause.func}` does not have a meta kernel that supports dynamic output shapes",
  3175. hints=[
  3176. "Please report an issue to PyTorch",
  3177. ],
  3178. from_exc=cause,
  3179. )
  3180. elif isinstance(
  3181. cause, torch._subclasses.fake_tensor.UnsupportedOperatorException
  3182. ):
  3183. op = cause.func # type: ignore[assignment]
  3184. import_suggestion = ""
  3185. if isinstance(op, torch._ops.OpOverload):
  3186. maybe_pystub = torch._C._dispatch_pystub(
  3187. op._schema.name, op._schema.overload_name
  3188. )
  3189. if maybe_pystub is not None:
  3190. module, ctx = maybe_pystub
  3191. import_suggestion = (
  3192. f"It's possible that the support was implemented in "
  3193. f"module `{module}` and you may need to `import {module}`"
  3194. f"({ctx}), otherwise "
  3195. )
  3196. unimplemented(
  3197. gb_type="Operator does not support running with fake tensors",
  3198. context=f"unsupported operator: {cause.func}",
  3199. explanation="",
  3200. hints=[
  3201. f"{import_suggestion}see "
  3202. "https://docs.google.com/document/d/1GgvOe7C8_NVOMLOCwDaYV1mXXyHMXY7ExoewHqooxrs/edit#heading=h.64r4npvq0w0"
  3203. " for how to fix",
  3204. ],
  3205. from_exc=cause,
  3206. )
  3207. elif isinstance(
  3208. cause, torch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode
  3209. ):
  3210. raise UserError( # noqa: B904
  3211. UserErrorType.CONSTRAINT_VIOLATION,
  3212. str(cause),
  3213. case_name="constrain_as_size_example",
  3214. )
  3215. elif isinstance(cause, ValueRangeError):
  3216. raise UserError(UserErrorType.CONSTRAINT_VIOLATION, e.args[0]) from e
  3217. elif isinstance(cause, TypeError) and "argument" in str(cause):
  3218. unimplemented(
  3219. gb_type="TypeError when making fake tensor call",
  3220. context=f"TypeError {node.target}: {cause}",
  3221. explanation="",
  3222. hints=[*graph_break_hints.USER_ERROR],
  3223. from_exc=cause,
  3224. )
  3225. msg = get_concrete_sizes_from_symints(str(e), fake_mode)
  3226. _wrap_graph_break_with_torch_runtime_err(
  3227. lambda: unimplemented(
  3228. gb_type="RuntimeError when making fake tensor call",
  3229. context="",
  3230. explanation=msg,
  3231. hints=[*graph_break_hints.USER_ERROR],
  3232. from_exc=cause,
  3233. )
  3234. )
  3235. raise AssertionError("should not reachable") from None
  3236. if not allow_non_graph_fake:
  3237. _ = pytree.tree_map_only(
  3238. torch.Tensor, functools.partial(ensure_graph_fake, tx=tx), ret_val
  3239. )
  3240. if (
  3241. torch._dynamo.config.use_graph_deduplication
  3242. or torch._dynamo.config.track_nodes_for_deduplication
  3243. ):
  3244. tx.output.region_tracker.track_node_mutations(
  3245. node,
  3246. flat_args_kwargs,
  3247. id_to_initial_version,
  3248. )
  3249. return ret_val
  3250. _current_node = threading.local()
  3251. def get_current_node() -> Optional[torch.fx.Node]:
  3252. return getattr(_current_node, "value", None)
  3253. @contextmanager
  3254. def set_current_node(node: torch.fx.Node) -> Generator[None, None, None]:
  3255. old = get_current_node()
  3256. _current_node.value = node
  3257. try:
  3258. yield
  3259. finally:
  3260. _current_node.value = old
  3261. def run_node(
  3262. tracer: Any, node: torch.fx.Node, args: Any, kwargs: Any, nnmodule: Any
  3263. ) -> Any:
  3264. """
  3265. Runs a given node, with the given args and kwargs.
  3266. Behavior is dictated by a node's op.
  3267. run_node is useful for extracting real values out of nodes.
  3268. See get_real_value for more info on common usage.
  3269. Note: The tracer arg is only used for 'get_attr' ops
  3270. Note: The nnmodule arg is only used for 'call_module' ops
  3271. Nodes that are not call_function, call_method, call_module, or get_attr will
  3272. raise an AssertionError.
  3273. """
  3274. op = node.op
  3275. with set_current_node(node):
  3276. def make_error_message(e: Any) -> str:
  3277. return (
  3278. f"Dynamo failed to run FX node with fake tensors: {op} {node.target}(*{args}, **{kwargs}): got "
  3279. + repr(e)
  3280. )
  3281. from .exc import Unsupported
  3282. try:
  3283. if op == "call_function":
  3284. return node.target(*args, **kwargs) # type: ignore[operator]
  3285. elif op == "call_method":
  3286. if not hasattr(args[0], node.target): # type: ignore[arg-type]
  3287. from . import graph_break_hints
  3288. from .exc import unimplemented
  3289. unimplemented(
  3290. gb_type="Missing attribute when running call_method node",
  3291. context="",
  3292. explanation=make_error_message("attribute not defined"),
  3293. hints=[*graph_break_hints.USER_ERROR],
  3294. )
  3295. return getattr(args[0], node.target)(*args[1:], **kwargs) # type: ignore[arg-type]
  3296. elif op == "call_module":
  3297. assert nnmodule is not None
  3298. return nnmodule(*args, **kwargs)
  3299. elif op == "get_attr":
  3300. return tracer.output_graph.get_submodule(node.target)
  3301. elif op == "placeholder":
  3302. assert "example_value" in node.meta
  3303. return node.meta["example_value"]
  3304. except (NotImplementedError, UnsupportedFakeTensorException) as e:
  3305. # NB: mimic how wrap_fake_exception does it
  3306. from . import graph_break_hints
  3307. from .exc import unimplemented
  3308. hints = [*graph_break_hints.USER_ERROR]
  3309. if isinstance(e, NotImplementedError):
  3310. hints += [
  3311. "If the op is a custom op, did you implement a fake tensor implementation? "
  3312. "(e.g. with `@my_custom_op.register_fake`)",
  3313. "If the op is a PyTorch op, please file an issue to PyTorch.",
  3314. ]
  3315. unimplemented(
  3316. gb_type="NotImplementedError/UnsupportedFakeTensorException when running FX node",
  3317. context="",
  3318. explanation=make_error_message(e),
  3319. hints=hints,
  3320. from_exc=e,
  3321. )
  3322. except Unsupported:
  3323. raise
  3324. except Exception as e:
  3325. raise RuntimeError(make_error_message(e)).with_traceback(
  3326. e.__traceback__
  3327. ) from e
  3328. raise AssertionError(op)
  3329. def get_real_value(node: torch.fx.Node, tracer: Any) -> Any:
  3330. """
  3331. Run the actual computation represented by `node` and return the result.
  3332. This will execute any dependent nodes in the graph as well.
  3333. """
  3334. from . import graph_break_hints
  3335. from .exc import unimplemented
  3336. cache = tracer.real_value_cache
  3337. if node in cache:
  3338. return cache[node]
  3339. op = node.op
  3340. args, kwargs = torch.fx.node.map_arg( # type: ignore[misc]
  3341. (node.args, node.kwargs),
  3342. lambda n: get_real_value(n, tracer),
  3343. )
  3344. if op == "placeholder" and "grapharg" in node.meta:
  3345. return node.meta["grapharg"].example
  3346. if op == "call_module":
  3347. nn_module = tracer.output_graph.nn_modules[node.target]
  3348. if not is_lazy_module(nn_module):
  3349. nn_module = copy.deepcopy(nn_module)
  3350. else:
  3351. # In the case of a lazy module, we want to run
  3352. # the pre-hooks which initialize it
  3353. nn_module(*args, **kwargs)
  3354. else:
  3355. nn_module = None
  3356. try:
  3357. real_value = run_node(tracer, node, args, kwargs, nn_module)
  3358. cache[node] = real_value
  3359. except RuntimeError as e:
  3360. exn = e # to make typing happy for the lambda
  3361. _wrap_graph_break_with_torch_runtime_err(
  3362. lambda: unimplemented(
  3363. gb_type="RuntimeError when trying to get real value from fx.Node",
  3364. context="",
  3365. explanation="",
  3366. hints=[*graph_break_hints.USER_ERROR],
  3367. from_exc=exn,
  3368. )
  3369. )
  3370. raise AssertionError("should not be reachable") from None
  3371. return real_value
  3372. def assert_no_fake_params_or_buffers(gm: torch.nn.Module) -> None:
  3373. from torch._subclasses.fake_tensor import FakeTensorConfig, is_fake
  3374. def stack_or_hint(t: Any) -> str:
  3375. if FakeTensorConfig.debug:
  3376. import traceback
  3377. return f"FAKE TENSOR CREATION TRACEBACK: \n {traceback.format_list(t._debug_trace)}"
  3378. else:
  3379. return "Enable TORCH_FAKE_TENSOR_DEBUG=1 to get creation stack traces on fake tensors."
  3380. for name, buffer in gm.named_buffers():
  3381. assert not is_fake(buffer), (
  3382. f"Unexpected fake buffer {name} {stack_or_hint(buffer)}"
  3383. )
  3384. for name, param in gm.named_parameters():
  3385. assert not is_fake(param), (
  3386. f"Unexpected fake param {name} {stack_or_hint(param)}"
  3387. )
  3388. def fqn(obj: Any) -> str:
  3389. """
  3390. Returns the fully qualified name of the object.
  3391. """
  3392. return f"{obj.__module__}.{obj.__qualname__}"
  3393. def ifdynstaticdefault(count1: Any, count2: Any) -> Any:
  3394. if torch._dynamo.config.assume_static_by_default:
  3395. return count1
  3396. else:
  3397. return count2
  3398. def import_submodule(mod: types.ModuleType) -> None:
  3399. """
  3400. Ensure all the files in a given submodule are imported
  3401. """
  3402. for filename in sorted(os.listdir(os.path.dirname(cast(str, mod.__file__)))):
  3403. if filename.endswith(".py") and filename[0] != "_":
  3404. importlib.import_module(f"{mod.__name__}.{filename[:-3]}")
  3405. def object_has_getattribute(value: Any) -> bool:
  3406. return class_has_getattribute(type(value))
  3407. def object_setattr_ignore_descriptor(obj: Any, name: str, value: Any) -> None:
  3408. # https://github.com/python/cpython/blob/3.11/Objects/object.c#L1286-L1335
  3409. d = object.__getattribute__(obj, "__dict__")
  3410. d[name] = value
  3411. def class_has_getattribute(cls: type) -> bool:
  3412. try:
  3413. if isinstance(
  3414. inspect.getattr_static(cls, "__getattribute__"),
  3415. types.FunctionType,
  3416. ):
  3417. return True
  3418. except AttributeError:
  3419. pass
  3420. return False
  3421. def get_custom_getattr(
  3422. value: Any, ignore_nn_module_getattr: bool = False
  3423. ) -> Optional[Any]:
  3424. try:
  3425. getattr_fn = inspect.getattr_static(type(value), "__getattr__")
  3426. except AttributeError:
  3427. getattr_fn = None
  3428. if ignore_nn_module_getattr and getattr_fn is torch.nn.Module.__getattr__:
  3429. # ignore this case of getattr
  3430. getattr_fn = None
  3431. return getattr_fn
  3432. class TensorStaticReason(enum.Enum):
  3433. PARAMETER = 2
  3434. NOT_TENSOR = 4
  3435. NN_MODULE_PROPERTY = 5
  3436. def tensor_static_reason_to_message(reason: TensorStaticReason) -> str:
  3437. if reason == TensorStaticReason.PARAMETER:
  3438. return "mark_dynamic on parameter, parameters are always static today."
  3439. if reason == TensorStaticReason.NOT_TENSOR:
  3440. return "mark_dynamic on a non tensor, how did this happen?"
  3441. if reason == TensorStaticReason.NN_MODULE_PROPERTY:
  3442. return "tensor is static because it is nn module associated."
  3443. raise AssertionError(f"Illegal reason {reason}")
  3444. def tensor_always_has_static_shape(
  3445. tensor: Union[torch.Tensor, Any],
  3446. is_tensor: bool,
  3447. tensor_source: Source,
  3448. ) -> tuple[bool, Optional[TensorStaticReason]]:
  3449. """
  3450. Given a tensor, source, and is_tensor flag, determine if a shape should be static.
  3451. Args:
  3452. tensor - the real tensor to evaluate, parameters force a static shape.
  3453. is_tensor - internal dynamo check, essentially "is_tensor": target_cls is TensorVariable,
  3454. tensors not in a TensorVariable for whatever reason are forced static.
  3455. Returns a tuple, where the first element is the bool of whether or not this tensor should have a static shape.
  3456. The second element is a TensorStaticReason, useful for passing to tensor_static_reason_to_message if needed.
  3457. """
  3458. from .source import is_from_unspecialized_param_buffer_source
  3459. if (
  3460. tensor_source.guard_source.is_specialized_nn_module()
  3461. or tensor_source.guard_source.is_unspecialized_builtin_nn_module()
  3462. ) and config.force_nn_module_property_static_shapes:
  3463. return True, TensorStaticReason.NN_MODULE_PROPERTY
  3464. if (
  3465. type(tensor) is torch.nn.Parameter
  3466. or is_from_unspecialized_param_buffer_source(tensor_source)
  3467. ) and config.force_parameter_static_shapes:
  3468. return True, TensorStaticReason.PARAMETER
  3469. if not is_tensor:
  3470. return True, TensorStaticReason.NOT_TENSOR
  3471. return False, None
  3472. def lazy_format_graph_tabular(fn_name: str, gm: torch.fx.GraphModule) -> Any:
  3473. def inner() -> str:
  3474. try:
  3475. from tabulate import tabulate # TODO: Check that this is installed
  3476. except ImportError:
  3477. return (
  3478. "Tabulate module missing, please install tabulate to log the graph in tabular format, logging code instead:\n"
  3479. + str(lazy_format_graph_code(fn_name, gm))
  3480. )
  3481. node_specs = [
  3482. [n.op, n.name, n.target, n.args, n.kwargs] for n in gm.graph.nodes
  3483. ]
  3484. graph_str = tabulate(
  3485. node_specs, headers=["opcode", "name", "target", "args", "kwargs"]
  3486. )
  3487. return _format_graph_code(fn_name, gm.forward.__code__.co_filename, graph_str)
  3488. return LazyString(inner)
  3489. def format_bytecode(
  3490. prefix: str, name: str, filename: str, line_no: int, code: Any
  3491. ) -> str:
  3492. return f"{prefix} {name} {filename} line {line_no} \n{dis.Bytecode(code).dis()}\n"
  3493. forward_hook_names = [
  3494. "_forward_pre_hooks",
  3495. "_forward_pre_hooks_with_kwargs",
  3496. "_forward_hooks_with_kwargs",
  3497. "_forward_hooks",
  3498. ]
  3499. backward_hook_names = ["_backward_pre_hooks", "_backward_hooks"]
  3500. state_dict_hook_names = [
  3501. "_state_dict_pre_hooks",
  3502. "_state_dict_hooks",
  3503. "_load_state_dict_pre_hooks",
  3504. "_load_state_dict_post_hooks",
  3505. ]
  3506. all_hook_names = forward_hook_names + backward_hook_names + state_dict_hook_names
  3507. def nn_module_has_global_hooks() -> bool:
  3508. # This is limited to backward hooks for now because NNModuleVariable
  3509. # supports fwd hooks underneath.
  3510. return bool(
  3511. len(torch.nn.modules.module._global_backward_hooks)
  3512. or len(torch.nn.modules.module._global_backward_pre_hooks)
  3513. )
  3514. def nn_module_get_all_hooks(
  3515. mod: torch.nn.Module,
  3516. check_forward_hooks: bool = False,
  3517. check_backward_hooks: bool = False,
  3518. check_state_dict_hooks: bool = False,
  3519. ) -> list[Any]:
  3520. """
  3521. Sometimes its useful to differentiate between types of hooks such as forward/backward/pre
  3522. hooks executed during module.__call__, and state_dict hooks which are executed separately.
  3523. """
  3524. hook_dicts_to_check = []
  3525. check_all_hooks = (
  3526. not check_forward_hooks
  3527. and not check_backward_hooks
  3528. and not check_state_dict_hooks
  3529. )
  3530. if check_forward_hooks or check_all_hooks:
  3531. hook_dicts_to_check.extend(forward_hook_names)
  3532. if check_backward_hooks or check_all_hooks:
  3533. hook_dicts_to_check.extend(backward_hook_names)
  3534. if check_state_dict_hooks:
  3535. hook_dicts_to_check.extend(state_dict_hook_names)
  3536. all_hooks = []
  3537. for hook_dict_name in hook_dicts_to_check:
  3538. hooks = getattr(mod, hook_dict_name, [])
  3539. for hook_name in hooks:
  3540. hook = hooks[hook_name]
  3541. all_hooks.append(hook)
  3542. return all_hooks
  3543. def nnmodule_has_hooks(
  3544. mod: torch.nn.Module,
  3545. check_forward_hooks: bool = False,
  3546. check_backward_hooks: bool = False,
  3547. check_state_dict_hooks: bool = False,
  3548. ) -> bool:
  3549. """
  3550. Helper function to check if a module has any hooks attached to it.
  3551. """
  3552. hooks = nn_module_get_all_hooks(
  3553. mod,
  3554. check_forward_hooks=check_forward_hooks,
  3555. check_backward_hooks=check_backward_hooks,
  3556. check_state_dict_hooks=check_state_dict_hooks,
  3557. )
  3558. return bool(hooks)
  3559. def to_numpy_helper(value: Any) -> Any:
  3560. """Convert tensor and tnp.ndarray to numpy.ndarray."""
  3561. if is_fake(value):
  3562. return value
  3563. if isinstance(value, tnp.ndarray):
  3564. return to_numpy_helper(value.tensor)
  3565. elif isinstance(value, torch.Tensor):
  3566. return value.numpy(force=True)
  3567. elif isinstance(value, (tuple, list)):
  3568. return type(value)(to_numpy_helper(obj) for obj in value)
  3569. else:
  3570. return value
  3571. def numpy_to_tensor(value: Any) -> Any:
  3572. """Convert tnp.ndarray to tensor, leave other types intact. If a list/tuple, loop through it to convert."""
  3573. assert np is not None
  3574. if isinstance(value, np.ndarray):
  3575. return torch.as_tensor(value)
  3576. if isinstance(value, tnp.ndarray):
  3577. return value.tensor
  3578. elif isinstance(value, (tuple, list)):
  3579. return type(value)(numpy_to_tensor(obj) for obj in value)
  3580. else:
  3581. return value
  3582. class numpy_to_tensor_wrapper(Generic[_P, R]):
  3583. def __init__(self, f: Callable[_P, R]) -> None:
  3584. self.f = f
  3585. self.__name__ = "wrapped_" + self.f.__name__
  3586. def __repr__(self) -> str:
  3587. return f"<Wrapped function <original {self.f.__name__}>>"
  3588. def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> Any:
  3589. out = self.f(*args, **kwargs)
  3590. return numpy_to_tensor(out)
  3591. def numpy_attr_wrapper(obj: Any, name: str) -> Any:
  3592. if isinstance(obj, tnp.ndarray):
  3593. out = getattr(obj, name)
  3594. return numpy_to_tensor(out)
  3595. elif isinstance(obj, torch.Tensor):
  3596. out = getattr(tnp.ndarray(obj), name)
  3597. return numpy_to_tensor(out)
  3598. class numpy_method_wrapper:
  3599. """Convert obj from torch.Tensor to tnp.ndarray and call method. Then convert result back to torch.Tensor."""
  3600. def __init__(self, method: str) -> None:
  3601. self.method = method
  3602. self.__name__ = "wrapped_" + self.method
  3603. def __repr__(self) -> str:
  3604. return f"<Wrapped method <original {self.method}>>"
  3605. def __call__(self, *args: Any, **kwargs: Any) -> Any:
  3606. obj = args[0]
  3607. if isinstance(obj, torch.Tensor):
  3608. obj = tnp.ndarray(obj)
  3609. method_callable = getattr(obj, self.method)
  3610. out = method_callable(*args[1:], **kwargs)
  3611. return numpy_to_tensor(out)
  3612. class numpy_operator_wrapper(Generic[_P, R]):
  3613. """Implements dunder methods for tnp.ndarray via functions from the operator library"""
  3614. def __init__(self, op: Callable[..., Any]) -> None:
  3615. self.op = op
  3616. self.__name__ = f"wrapped_{op.__name__}"
  3617. def __repr__(self) -> str:
  3618. return f"<Wrapped operator <original {self.__name__}>>"
  3619. def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> Any:
  3620. assert not kwargs
  3621. # pyrefly: ignore [bad-assignment]
  3622. args = (
  3623. tnp.ndarray(arg) if isinstance(arg, torch.Tensor) else arg for arg in args
  3624. )
  3625. out = self.op(*args)
  3626. return numpy_to_tensor(out)
  3627. def defake(x: Any) -> Any:
  3628. if not isinstance(x, FakeTensor):
  3629. return x
  3630. size: torch._prims_common.ShapeType
  3631. stride: torch._prims_common.StrideType
  3632. if x._has_symbolic_sizes_strides:
  3633. size = []
  3634. for s in x.size():
  3635. if isinstance(s, torch.SymInt):
  3636. size.append(s.node.shape_env.size_hint(s.node.expr))
  3637. else:
  3638. size.append(s)
  3639. stride = []
  3640. for s in x.stride():
  3641. if isinstance(s, torch.SymInt):
  3642. stride.append(s.node.shape_env.size_hint(s.node.expr))
  3643. else:
  3644. stride.append(s)
  3645. else:
  3646. size = x.size()
  3647. stride = x.stride()
  3648. y = torch.empty_strided(
  3649. size,
  3650. stride,
  3651. dtype=x.dtype,
  3652. device=x.device,
  3653. requires_grad=x.requires_grad,
  3654. )
  3655. y.zero_()
  3656. return y
  3657. def _disable_side_effect_safety_checks_for_current_subtracer(
  3658. fn: Callable[_P, R], *args: _P.args, **kwargs: _P.kwargs
  3659. ) -> R:
  3660. return fn(*args, **kwargs)
  3661. def is_utils_checkpoint(obj: Any) -> bool:
  3662. # Lazy import to avoid circular dependencies
  3663. import torch.utils.checkpoint
  3664. return obj is torch.utils.checkpoint.checkpoint
  3665. def is_invoke_subgraph(obj: Any) -> bool:
  3666. from torch._higher_order_ops.invoke_subgraph import invoke_subgraph_placeholder
  3667. return obj is invoke_subgraph_placeholder
  3668. def build_invoke_subgraph_variable(**options: Any) -> Any:
  3669. from .variables.higher_order_ops import TorchHigherOrderOperatorVariable
  3670. return TorchHigherOrderOperatorVariable.make(
  3671. torch._higher_order_ops.invoke_subgraph,
  3672. **options,
  3673. )
  3674. def build_checkpoint_variable(**options: Any) -> Any:
  3675. import torch._higher_order_ops.wrap as higher_order_ops
  3676. from .variables.higher_order_ops import TorchHigherOrderOperatorVariable
  3677. # TODO - This is a temporary situation where we have two versions of
  3678. # checkpointing implementation. We will converge on one and remove the other.
  3679. activation_checkpoint_op: torch._ops.HigherOrderOperator = (
  3680. higher_order_ops.tag_activation_checkpoint
  3681. )
  3682. if torch._functorch.config.functionalize_rng_ops:
  3683. activation_checkpoint_op = higher_order_ops.wrap_activation_checkpoint
  3684. return TorchHigherOrderOperatorVariable.make(
  3685. activation_checkpoint_op,
  3686. **options,
  3687. )
  3688. def is_compile_supported(device_type: DeviceLikeType) -> Any:
  3689. from .eval_frame import is_dynamo_supported
  3690. type = torch.device(device_type).type
  3691. compile_supported = is_dynamo_supported()
  3692. if type == "cpu":
  3693. pass
  3694. elif type in ["cuda", "xpu", "mtia"] and compile_supported:
  3695. compile_supported = has_triton()
  3696. else:
  3697. compile_supported = False
  3698. return compile_supported
  3699. # The following 3.11 source code functions are adapted from
  3700. # https://github.com/python/cpython/blob/v3.11.4/Lib/traceback.py
  3701. # in order to output source code corresponding to bytecode in 3.11+.
  3702. # We need our own versions since we want to support multiline expressions.
  3703. def _fix_offset(str: str, offset: int) -> int:
  3704. """
  3705. Convert byte offset `offset` of `str` into character offset.
  3706. Byte offset is used for 3.11+ instruction column data.
  3707. Takes things like unicode characters into consideration.
  3708. Unchanged from CPython implementation.
  3709. """
  3710. as_utf8 = str.encode("utf-8")
  3711. return len(as_utf8[:offset].decode("utf-8", errors="replace"))
  3712. @dataclasses.dataclass
  3713. class _Anchors:
  3714. # inclusive
  3715. left_end_lineno: int
  3716. left_end_offset: int
  3717. right_start_lineno: int
  3718. # exclusive
  3719. right_start_offset: int
  3720. def _extract_anchors_from_expr(segment: str) -> Optional[_Anchors]:
  3721. """
  3722. Given source code `segment` corresponding to a bytecode
  3723. instruction, determine:
  3724. - for binary ops, the location of the binary op
  3725. - for indexing, the location of the brackets.
  3726. `segment` is expected to be a valid Python expression
  3727. """
  3728. assert sys.version_info >= (3, 11)
  3729. import ast
  3730. tree: Any | None = None
  3731. try:
  3732. # Without brackets, `segment` is parsed as a statement.
  3733. # We expect an expression, so wrap `segment` in
  3734. # brackets to handle multi-line expressions.
  3735. tree = ast.parse("(\n" + segment + "\n)")
  3736. except SyntaxError:
  3737. return None
  3738. assert tree is not None
  3739. if len(tree.body) != 1:
  3740. return None
  3741. lines = segment.split("\n")
  3742. # get character index given byte offset
  3743. def normalize(lineno: int, offset: int) -> int:
  3744. return _fix_offset(lines[lineno], offset)
  3745. # Gets the next valid character index in `lines`, if
  3746. # the current location is not valid. Handles empty lines.
  3747. def next_valid_char(lineno: int, col: int) -> tuple[int, int]:
  3748. while lineno < len(lines) and col >= len(lines[lineno]):
  3749. col = 0
  3750. lineno += 1
  3751. assert lineno < len(lines) and col < len(lines[lineno])
  3752. return lineno, col
  3753. # Get the next valid character index in `lines`.
  3754. def increment(lineno: int, col: int) -> tuple[int, int]:
  3755. col += 1
  3756. lineno, col = next_valid_char(lineno, col)
  3757. assert lineno < len(lines) and col < len(lines[lineno])
  3758. return lineno, col
  3759. # Get the next valid character at least on the next line
  3760. def nextline(lineno: int, col: int) -> tuple[int, int]:
  3761. col = 0
  3762. lineno += 1
  3763. lineno, col = next_valid_char(lineno, col)
  3764. assert lineno < len(lines) and col < len(lines[lineno])
  3765. return lineno, col
  3766. statement = tree.body[0]
  3767. if isinstance(statement, ast.Expr):
  3768. expr = statement.value
  3769. if isinstance(expr, ast.BinOp):
  3770. # ast gives locations for BinOp subexpressions, e.g.
  3771. # ( left_expr ) + ( right_expr )
  3772. # left^^^^^ right^^^^^
  3773. # -2 since end_lineno is 1-indexed and because we added an extra
  3774. # bracket to `segment` when calling ast.parse
  3775. cur_lineno = cast(int, expr.left.end_lineno) - 2
  3776. assert expr.left.end_col_offset is not None
  3777. cur_col = normalize(cur_lineno, expr.left.end_col_offset)
  3778. cur_lineno, cur_col = next_valid_char(cur_lineno, cur_col)
  3779. # Heuristic to find the operator character.
  3780. # The original CPython implementation did not look for ), \, or #,
  3781. # leading to incorrect anchor location, e.g.
  3782. # (x) + (y)
  3783. # ~~^~~~~~~
  3784. while (ch := lines[cur_lineno][cur_col]).isspace() or ch in ")\\#":
  3785. if ch in "\\#":
  3786. cur_lineno, cur_col = nextline(cur_lineno, cur_col)
  3787. else:
  3788. cur_lineno, cur_col = increment(cur_lineno, cur_col)
  3789. # binary op is 1 or 2 characters long, on the same line
  3790. right_col = cur_col + 1
  3791. if (
  3792. right_col < len(lines[cur_lineno])
  3793. and not (ch := lines[cur_lineno][right_col]).isspace()
  3794. and ch not in "\\#"
  3795. ):
  3796. right_col += 1
  3797. # right_col can be invalid since it is exclusive
  3798. return _Anchors(cur_lineno, cur_col, cur_lineno, right_col)
  3799. elif isinstance(expr, ast.Subscript):
  3800. # ast gives locations for value and slice subexpressions, e.g.
  3801. # ( value_expr ) [ slice_expr ]
  3802. # value^^^^^ slice^^^^^
  3803. # subscript^^^^^^^^^^^^^^^^^^^^
  3804. # find left bracket (first '[' after value)
  3805. left_lineno = cast(int, expr.value.end_lineno) - 2
  3806. assert expr.value.end_col_offset is not None
  3807. left_col = normalize(left_lineno, expr.value.end_col_offset)
  3808. left_lineno, left_col = next_valid_char(left_lineno, left_col)
  3809. while lines[left_lineno][left_col] != "[":
  3810. left_lineno, left_col = increment(left_lineno, left_col)
  3811. # find right bracket (final character of expression)
  3812. right_lineno = cast(int, expr.end_lineno) - 2
  3813. assert expr.end_col_offset is not None
  3814. right_col = normalize(right_lineno, expr.end_col_offset)
  3815. return _Anchors(left_lineno, left_col, right_lineno, right_col)
  3816. elif isinstance(expr, ast.Call):
  3817. # ( func_expr ) (args, kwargs)
  3818. # func^^^^^
  3819. # call^^^^^^^^^^^^^^^^^^^^^^^^
  3820. # find left bracket (first '(' after func)
  3821. left_lineno = cast(int, expr.func.end_lineno) - 2
  3822. assert expr.func.end_col_offset is not None
  3823. left_col = normalize(left_lineno, expr.func.end_col_offset)
  3824. left_lineno, left_col = next_valid_char(left_lineno, left_col)
  3825. while lines[left_lineno][left_col] != "(":
  3826. left_lineno, left_col = increment(left_lineno, left_col)
  3827. # find right bracket (final character of expression)
  3828. right_lineno = cast(int, expr.end_lineno) - 2
  3829. assert expr.end_col_offset is not None
  3830. right_col = normalize(right_lineno, expr.end_col_offset)
  3831. return _Anchors(left_lineno, left_col, right_lineno, right_col)
  3832. return None
  3833. def get_instruction_source_311(code: types.CodeType, inst: Instruction) -> str:
  3834. """
  3835. Python 3.11+ only. Returns lines of source code (from code object `code`)
  3836. corresponding to `inst`'s location data, and underlines relevant code to `inst`.
  3837. Example: CALL on `g`:
  3838. f(g(
  3839. ^^
  3840. h(x)))
  3841. ^^^^^
  3842. We need our own implementation in < 3.13 since `format_frame_summary` in
  3843. Python's `traceback` module doesn't handle multi-line expressions
  3844. (and their anchor extraction code is not completely correct).
  3845. """
  3846. if sys.version_info >= (3, 13):
  3847. # multiline traceback implemented in 3.13+
  3848. frame_summary = traceback.FrameSummary(
  3849. code.co_filename,
  3850. inst.positions.lineno,
  3851. code.co_name,
  3852. end_lineno=inst.positions.end_lineno,
  3853. colno=inst.positions.col_offset,
  3854. end_colno=inst.positions.end_col_offset,
  3855. )
  3856. result = traceback.format_list([frame_summary])[0]
  3857. # remove first line containing filename info
  3858. result = "\n".join(result.splitlines()[1:])
  3859. # indent lines with original indentation
  3860. orig_lines = [
  3861. linecache.getline(code.co_filename, lineno).rstrip()
  3862. for lineno in range(inst.positions.lineno, inst.positions.end_lineno + 1)
  3863. ]
  3864. orig_lines_dedent = textwrap.dedent("\n".join(orig_lines)).splitlines()
  3865. indent_len = len(orig_lines[0]) - len(orig_lines_dedent[0])
  3866. indent = orig_lines[0][:indent_len]
  3867. result = textwrap.indent(textwrap.dedent(result), indent)
  3868. return result
  3869. assert hasattr(inst, "positions") and inst.positions is not None
  3870. if inst.positions.lineno is None:
  3871. return ""
  3872. # The rstrip + "\n" pattern is used throughout this function to handle
  3873. # linecache.getline errors. Error lines are treated as empty strings "", but we want
  3874. # to treat them as blank lines "\n".
  3875. first_line = linecache.getline(code.co_filename, inst.positions.lineno).rstrip()
  3876. if inst.positions.end_lineno is None:
  3877. return first_line
  3878. if inst.positions.col_offset is None or inst.positions.end_col_offset is None:
  3879. return first_line
  3880. # character index of the start of the instruction
  3881. start_offset = _fix_offset(first_line, inst.positions.col_offset)
  3882. # character index of the end of the instruction
  3883. # compute later since end may be a different line
  3884. end_offset = None
  3885. # expression corresponding to the instruction so we can get anchors
  3886. segment = ""
  3887. # underline markers to be printed - start with `~` marker and replace with `^` later
  3888. markers = []
  3889. # Compute segment and initial markers
  3890. if inst.positions.end_lineno == inst.positions.lineno:
  3891. end_offset = _fix_offset(first_line, inst.positions.end_col_offset)
  3892. segment = first_line[start_offset:end_offset]
  3893. markers.append(" " * start_offset + "~" * (end_offset - start_offset))
  3894. else:
  3895. segment = first_line[start_offset:] + "\n"
  3896. markers.append(" " * start_offset + "~" * (len(first_line) - start_offset))
  3897. last_line = linecache.getline(
  3898. code.co_filename, inst.positions.end_lineno
  3899. ).rstrip()
  3900. end_offset = _fix_offset(last_line, inst.positions.end_col_offset)
  3901. for lineno in range(inst.positions.lineno + 1, inst.positions.end_lineno):
  3902. line = linecache.getline(code.co_filename, lineno).rstrip()
  3903. segment += line + "\n"
  3904. # don't underline leading spaces
  3905. num_spaces = len(line) - len(line.lstrip())
  3906. markers.append(" " * num_spaces + "~" * (len(line) - num_spaces))
  3907. segment += last_line[:end_offset]
  3908. num_spaces = len(last_line) - len(last_line.lstrip())
  3909. markers.append(" " * num_spaces + "~" * (end_offset - num_spaces))
  3910. anchors: Optional[_Anchors] = None
  3911. try:
  3912. anchors = _extract_anchors_from_expr(segment)
  3913. except AssertionError:
  3914. pass
  3915. # replace `~` markers with `^` where necessary
  3916. if anchors is None:
  3917. markers = [marker.replace("~", "^") for marker in markers]
  3918. else:
  3919. # make markers mutable
  3920. mutable_markers: list[list[str]] = [list(marker) for marker in markers]
  3921. # anchor positions do not take start_offset into account
  3922. if anchors.left_end_lineno == 0:
  3923. anchors.left_end_offset += start_offset
  3924. if anchors.right_start_lineno == 0:
  3925. anchors.right_start_offset += start_offset
  3926. # Turn `~`` markers between anchors to `^`
  3927. for lineno in range(len(markers)):
  3928. for col in range(len(mutable_markers[lineno])):
  3929. if lineno < anchors.left_end_lineno:
  3930. continue
  3931. if lineno == anchors.left_end_lineno and col < anchors.left_end_offset:
  3932. continue
  3933. if (
  3934. lineno == anchors.right_start_lineno
  3935. and col >= anchors.right_start_offset
  3936. ):
  3937. continue
  3938. if lineno > anchors.right_start_lineno:
  3939. continue
  3940. if mutable_markers[lineno][col] == "~":
  3941. mutable_markers[lineno][col] = "^"
  3942. # make markers into strings again
  3943. markers = ["".join(marker) for marker in mutable_markers]
  3944. result = ""
  3945. for i in range(len(markers)):
  3946. result += (
  3947. linecache.getline(code.co_filename, inst.positions.lineno + i).rstrip()
  3948. + "\n"
  3949. )
  3950. result += markers[i] + "\n"
  3951. return result
  3952. def get_static_address_type(t: Any) -> Any:
  3953. if isinstance(t, torch.Tensor):
  3954. return getattr(t, "_dynamo_static_input_type", None)
  3955. return None
  3956. def is_rng_state_getter_or_setter(value: Any) -> bool:
  3957. getters = (
  3958. # The following two functions are not identical, so don't remove anyone!
  3959. torch._C.Generator.get_state,
  3960. torch.default_generator.get_state,
  3961. torch.get_rng_state,
  3962. torch.cuda.get_rng_state,
  3963. )
  3964. setters = (
  3965. torch._C.Generator.set_state,
  3966. torch.default_generator.set_state,
  3967. torch.set_rng_state,
  3968. torch.cuda.set_rng_state,
  3969. )
  3970. return value in (*setters, *getters)
  3971. def is_tensor_base_attr_getter(value: Any) -> bool:
  3972. return (
  3973. isinstance(value, types.MethodWrapperType)
  3974. and value.__name__ == "__get__"
  3975. and value.__self__.__objclass__ is torch._C._TensorBase # type: ignore[attr-defined]
  3976. )
  3977. def is_tensor_getset_descriptor(name: str) -> bool:
  3978. try:
  3979. attr = inspect.getattr_static(torch.Tensor, name)
  3980. return type(attr) is types.GetSetDescriptorType
  3981. except AttributeError:
  3982. return False
  3983. def is_torch_function_object(value: Any) -> bool:
  3984. return hasattr(value, "__torch_function__")
  3985. def has_torch_function(vt: VariableTracker) -> bool:
  3986. # This emulates
  3987. # https://github.com/pytorch/pytorch/blob/8d81806211bc3c0ee6c2ef235017bacf1d775a85/torch/csrc/utils/disable_torch_function.cpp#L315-L323
  3988. from torch._dynamo.variables import UserDefinedObjectVariable
  3989. from torch._dynamo.variables.torch_function import TensorWithTFOverrideVariable
  3990. # Note on lazy vars: The value will either be realized or not throughout the course of execution
  3991. # if the value has a torch function, it will eventually be realized so we can realize it here
  3992. # if the value does not have a torch function, it may or may not be realized
  3993. # if it is realized it will be used and guards will be installed properly
  3994. # if it is not used, guards won't be installed, and it doesn't matter
  3995. # if the value has a torch function or not, so we should *not* realize it.
  3996. # NB: We technically know that if is_realized is False, LazyVariableTracker has the peek_value method
  3997. # but mypy does not unfortunately
  3998. if vt.is_realized() or (
  3999. hasattr(vt, "peek_value") and hasattr(vt.peek_value(), "__torch_function__")
  4000. ):
  4001. func = None
  4002. if isinstance(vt, TensorWithTFOverrideVariable):
  4003. func = getattr(vt.class_type, "__torch_function__", None)
  4004. elif isinstance(vt, UserDefinedObjectVariable):
  4005. func = getattr(vt.value, "__torch_function__", None)
  4006. return func not in (None, torch._C._disabled_torch_function_impl)
  4007. return False
  4008. # see note [Tensor Fakification and Symbol Caching]
  4009. def to_fake_tensor(
  4010. t: torch.Tensor, fake_mode: torch._subclasses.fake_tensor.FakeTensorMode
  4011. ) -> Any:
  4012. symbolic_context = None
  4013. source = None
  4014. if tracing_context := torch._guards.TracingContext.try_get():
  4015. if t in tracing_context.tensor_to_context:
  4016. symbolic_context = tracing_context.tensor_to_context[t]
  4017. source = symbolic_context.tensor_source
  4018. return fake_mode.from_tensor(
  4019. t, static_shapes=False, symbolic_context=symbolic_context, source=source
  4020. )
  4021. # NB: this works for both classes and instances
  4022. def is_frozen_dataclass(value: Any) -> bool:
  4023. return (
  4024. not object_has_getattribute(value)
  4025. and not class_has_getattribute(value)
  4026. and is_dataclass(value)
  4027. and hasattr(value, "__dataclass_params__")
  4028. and hasattr(value.__dataclass_params__, "frozen")
  4029. and value.__dataclass_params__.frozen
  4030. )
  4031. def get_first_attr(obj: Any, *attrs: str) -> Any:
  4032. """
  4033. Return the first available attribute or throw an exception if none is present.
  4034. """
  4035. for attr in attrs:
  4036. if hasattr(obj, attr):
  4037. return getattr(obj, attr)
  4038. raise AssertionError(f"{obj} does not has any of the attributes: {attrs}")
  4039. @contextlib.contextmanager
  4040. def maybe_enable_compiled_autograd(
  4041. should_enable: bool, fullgraph: bool = True, dynamic: bool = True
  4042. ) -> Generator[Any, None, None]:
  4043. if not should_enable:
  4044. yield
  4045. else:
  4046. def compiler_fn(gm: Any) -> Any:
  4047. def inner_compiler(gm_: Any, example_inputs_: Any) -> Any:
  4048. torch._dynamo.utils.counters["compiled_autograd"]["compiles"] += 1
  4049. return torch._inductor.compile(gm_, example_inputs_)
  4050. return torch.compile(
  4051. gm, backend=inner_compiler, fullgraph=fullgraph, dynamic=dynamic
  4052. )
  4053. with torch._dynamo.compiled_autograd._enable(compiler_fn) as ctx:
  4054. yield ctx
  4055. def invalid_removeable_handle() -> RemovableHandle:
  4056. # need a subclass so weakref works
  4057. class Invalid(dict): # type: ignore[type-arg]
  4058. pass
  4059. return RemovableHandle(Invalid())
  4060. # Returns a "proxy" (new object with the same class and dict) for (non-GraphModule) nn.Module's.
  4061. # Attribute changes to the original object/proxy will be reflected in the other.
  4062. # This is useful for cases where we want a keep-alive reference to a module without increasing
  4063. # its reference count.
  4064. def nn_module_proxy(mod: Any) -> Any:
  4065. if not isinstance(mod, torch.nn.Module):
  4066. return mod
  4067. if isinstance(mod, torch.fx.GraphModule):
  4068. # Dynamo-generated GM's shouldn't contain user-created GM's
  4069. return mod
  4070. proxy = mod.__class__.__new__(mod.__class__)
  4071. proxy.__dict__ = mod.__dict__
  4072. return proxy
  4073. class GmWrapper(torch.nn.Module):
  4074. def __init__(
  4075. self, gm: torch.fx.GraphModule, unflatten_fn: Callable[[list[Any]], Any]
  4076. ) -> None:
  4077. super().__init__()
  4078. self.gm = gm
  4079. self.unflatten_fn = unflatten_fn
  4080. def forward(self, *args: Any) -> Any:
  4081. # pyrefly: ignore [annotation-mismatch, redefinition]
  4082. args: list[Any] = list(args)
  4083. return self.gm(*self.unflatten_fn(args))
  4084. def flatten_graph_inputs(
  4085. gm: torch.fx.GraphModule, inputs: Any, compile_gm: Callable[[Any, Any], Any]
  4086. ) -> Callable[..., Any]:
  4087. """
  4088. Mutate inputs so that they are flat and wrap gm such that it
  4089. accepts those inputs. This is needed for graphs that take
  4090. bumpy inputs.
  4091. """
  4092. inputs_idx_to_clear = [
  4093. i
  4094. for i, node in enumerate(gm.graph.nodes)
  4095. if node.op == "placeholder" and node.meta.get("steal_arg", False)
  4096. ]
  4097. if torch._dynamo.compiled_autograd.in_compiled_autograd_region:
  4098. # fast path, avoid pytree overhead
  4099. # compiled autograd inputs are always a list of tensors, maybe followed by symints
  4100. assert inputs_idx_to_clear == [0]
  4101. assert isinstance(inputs[0], list)
  4102. boxed_inputs_count = len(inputs[0])
  4103. def flatten_fn(args: Any) -> Any:
  4104. return args[0] + list(args[1:])
  4105. def unflatten_fn(flat_args: Any) -> Any:
  4106. return (flat_args[:boxed_inputs_count], *flat_args[boxed_inputs_count:])
  4107. compiled_fn = compile_gm(GmWrapper(gm, unflatten_fn), flatten_fn(inputs))
  4108. else:
  4109. # slow path, don't know inputs structure
  4110. flat_inputs, spec = pytree.tree_flatten(inputs)
  4111. unflatten_fn = functools.partial(pytree.tree_unflatten, treespec=spec)
  4112. compiled_fn = compile_gm(GmWrapper(gm, unflatten_fn), flat_inputs)
  4113. # note this doesn't check the spec, assuming it is the same
  4114. flatten_fn = pytree.arg_tree_leaves
  4115. def wrapper(*args: Any) -> Any:
  4116. flat_args = flatten_fn(args)
  4117. # flat_args is a new list, so we need to clear references from the old list
  4118. for i in inputs_idx_to_clear:
  4119. args[i].clear()
  4120. # this call is boxed to avoid increasing refcount until we reach aot_module_simplified forward
  4121. return compiled_fn(flat_args)
  4122. return wrapper
  4123. def get_locals_to_steal(maybe_gm: Any) -> list[Any]:
  4124. if not isinstance(maybe_gm, torch.fx.GraphModule) or not hasattr(maybe_gm, "meta"):
  4125. return []
  4126. return maybe_gm.meta.get("locals_to_steal", [])
  4127. def set_locals_to_steal(gm: torch.fx.GraphModule, locals_to_steal: list[Any]) -> None:
  4128. gm.meta["locals_to_steal"] = locals_to_steal
  4129. class Lit:
  4130. def __init__(self, s: str) -> None:
  4131. self.s = s
  4132. def __repr__(self) -> str:
  4133. return self.s
  4134. warn_once_cache: set[str] = set()
  4135. def warn_once(msg: str, stacklevel: int = 1) -> None:
  4136. # Dynamo causes all warnings.warn (in user code and in Dynamo code) to print all the time.
  4137. # https://github.com/pytorch/pytorch/issues/128427.
  4138. # warn_once is a workaround: if the msg has been warned on before, then we will not
  4139. # warn again.
  4140. # NB: it's totally ok to store a cache of all the strings: this is what warnings.warn does as well.
  4141. if msg in warn_once_cache:
  4142. return
  4143. warn_once_cache.add(msg)
  4144. warnings.warn(msg, stacklevel=stacklevel + 1)
  4145. def strip_color_from_string(text: str) -> str:
  4146. # This regular expression matches ANSI escape codes
  4147. ansi_escape = re.compile(r"\x1B[@-_][0-?]*[ -/]*[@-~]")
  4148. return ansi_escape.sub("", text)
  4149. @contextlib.contextmanager
  4150. def _disable_saved_tensors_hooks_during_tracing() -> Generator[None, None, None]:
  4151. # See NOTE: [Deferring tensor pack/unpack hooks until runtime]
  4152. try:
  4153. prior = torch._C._autograd._saved_tensors_hooks_set_tracing(True)
  4154. yield
  4155. finally:
  4156. torch._C._autograd._saved_tensors_hooks_set_tracing(prior)
  4157. def is_parameter_freezing() -> bool:
  4158. return torch._inductor.config.freezing and not torch.is_grad_enabled()
  4159. def get_torch_function_mode_stack() -> list[Any]:
  4160. return [
  4161. get_torch_function_mode_stack_at(i) for i in range(_len_torch_function_stack())
  4162. ]
  4163. def get_torch_function_mode_stack_at(ind: int) -> Any:
  4164. assert ind < _len_torch_function_stack() and ind >= 0
  4165. return torch._C._get_function_stack_at(ind)
  4166. def set_torch_function_mode_stack(stack: list[Any]) -> None:
  4167. for _ in range(_len_torch_function_stack()):
  4168. _pop_torch_function_stack()
  4169. for mode in stack:
  4170. _push_on_torch_function_stack(mode)
  4171. def clear_torch_function_mode_stack() -> None:
  4172. for _ in range(_len_torch_function_stack()):
  4173. _pop_torch_function_stack()
  4174. def get_current_stream(device: torch.device) -> torch.Stream:
  4175. return torch.accelerator.current_stream(device)
  4176. # call from C dynamo in order to inspect values in pdb
  4177. def _breakpoint_for_c_dynamo(*args: Any) -> None:
  4178. breakpoint()
  4179. def verify_guard_fn_signature(value: Any) -> None:
  4180. fn = value.__metadata_guard__
  4181. sig = inspect.signature(fn)
  4182. if len(sig.parameters) != 2:
  4183. from .exc import InternalTorchDynamoError
  4184. raise InternalTorchDynamoError(
  4185. "Tensor subclass method __metadata_guard__ must take exactly two subclass metadata arguments"
  4186. )
  4187. if fn.__self__ != value.__class__:
  4188. from .exc import InternalTorchDynamoError
  4189. raise InternalTorchDynamoError(
  4190. "Tensor subclass method __metadata_guard__ must be a classmethod"
  4191. )
  4192. def does_not_override_dict_iter_methods(user_cls: Any) -> bool:
  4193. return (
  4194. user_cls.items in (dict.items, OrderedDict.items)
  4195. and user_cls.values in (dict.values, OrderedDict.values)
  4196. and user_cls.keys in (dict.keys, OrderedDict.keys)
  4197. and user_cls.__iter__ in (dict.__iter__, OrderedDict.__iter__)
  4198. )
  4199. # Helper functions below are to prevent TorchDynamo to prevent tracing of
  4200. # __torch_function__ calls triggered on tensor properties in the pre graph
  4201. # bytecode.
  4202. @torch._disable_dynamo
  4203. def call_size(x: Any, i: int) -> int:
  4204. return x.size(i)
  4205. @torch._disable_dynamo
  4206. def call_stride(x: Any, i: int) -> int:
  4207. return x.stride(i)
  4208. @torch._disable_dynamo
  4209. def call_storage_offset(x: Any) -> int:
  4210. return x.storage_offset()
  4211. # Helper function to extract relevant parts of a tensor's __dict__ to store in node meta.
  4212. # To avoid ref cycles, it's important that no tensors are present here, so leave those out.
  4213. def _extract_tensor_dict(t: torch.Tensor) -> dict[str, Any]:
  4214. KEYS_TO_COPY = [
  4215. "_dynamo_static_input_type",
  4216. "tag",
  4217. ]
  4218. tensor_dict = {
  4219. key: copy.copy(t.__dict__[key]) for key in KEYS_TO_COPY if key in t.__dict__
  4220. }
  4221. return tensor_dict
  4222. def build_stream(args: tuple[Any], kwargs: dict[Any, Any]) -> torch.Stream:
  4223. return torch._C.Stream(*args, **kwargs)
  4224. def build_event(args: tuple[Any], kwargs: dict[Any, Any]) -> torch.Event:
  4225. return torch._C.Event(*args, **kwargs)
  4226. class CompileTimeInstructionCounter:
  4227. _counter: int = 0
  4228. _id: int = -1
  4229. _depth = 0
  4230. @classmethod
  4231. def start(cls) -> None:
  4232. cls._depth = cls._depth + 1
  4233. if cls._depth == 1:
  4234. cls._id = _instruction_counter.start()
  4235. @classmethod
  4236. def end(cls) -> None:
  4237. cls._depth = cls._depth - 1
  4238. if cls._depth == 0:
  4239. cls._counter += _instruction_counter.end(cls._id)
  4240. cls._id = -1
  4241. @classmethod
  4242. def clear(cls) -> None:
  4243. cls._counter = 0
  4244. @classmethod
  4245. def value(cls) -> int:
  4246. return cls._counter
  4247. @classmethod
  4248. @contextmanager
  4249. def record(cls) -> Generator[None, None, None]:
  4250. try:
  4251. if config.record_compile_time_instruction_count:
  4252. cls.start()
  4253. yield
  4254. finally:
  4255. if config.record_compile_time_instruction_count:
  4256. cls.end()
  4257. class CompileCounterInt(int):
  4258. def __add__(self, other: Any) -> CompileCounterInt:
  4259. return CompileCounterInt(super().__add__(other))
  4260. def set_feature_use(feature: str, usage: bool) -> None:
  4261. """
  4262. Records whether we are using a feature
  4263. Generally a feature is a JK.
  4264. """
  4265. # Note that sometimes (tests etc...) we're not in a context which we can record into
  4266. if get_metrics_context().in_progress():
  4267. get_metrics_context().set_key_value("feature_usage", feature, usage)
  4268. _ddp_optimization_mode: tuple[str, ...] = (
  4269. "ddp_optimizer",
  4270. "python_reducer", # experimental mode
  4271. "python_reducer_without_compiled_forward",
  4272. "no_optimization",
  4273. )
  4274. def get_optimize_ddp_mode() -> str:
  4275. optimize_ddp = config.optimize_ddp
  4276. if isinstance(optimize_ddp, bool):
  4277. mode = "ddp_optimizer" if optimize_ddp else "no_optimization"
  4278. elif isinstance(optimize_ddp, str):
  4279. mode = optimize_ddp
  4280. else:
  4281. raise ValueError(
  4282. f"Invalid dynamo config optimize_ddp type {type(optimize_ddp)=}"
  4283. )
  4284. assert mode in _ddp_optimization_mode, (
  4285. f"Invalid dynamo config optimize_ddp value {mode=}"
  4286. )
  4287. return mode
  4288. @contextmanager
  4289. def maybe_disable_inference_mode() -> Generator[None, None, None]:
  4290. """
  4291. Disables torch.inference_mode for the compilation (still on at runtime).
  4292. This simplifies the compile stack where we can assume that inference_mode
  4293. will always be off.
  4294. Since inference_mode is equivalent to no_grad + some optimizations (version
  4295. counts etc), we turn on no_grad here. The other optimizations are not
  4296. relevant to torch.compile.
  4297. """
  4298. is_inference_mode_on = (
  4299. config.fake_tensor_disable_inference_mode and torch.is_inference_mode_enabled()
  4300. )
  4301. if is_inference_mode_on:
  4302. with (
  4303. torch.inference_mode(False),
  4304. torch.no_grad(),
  4305. ):
  4306. yield
  4307. else:
  4308. yield
  4309. @contextmanager
  4310. def maybe_disable_inference_mode_for_fake_prop() -> Generator[None, None, None]:
  4311. """
  4312. Turns off tracking of inference_mode for fake tensor propagation. With this
  4313. context manager, when a real tensor is converted to fake tensor, the fake
  4314. tensor looses its inference-ness.
  4315. """
  4316. if config.fake_tensor_disable_inference_mode:
  4317. with torch._subclasses.meta_utils.disable_inference_mode_for_fake_prop():
  4318. yield
  4319. else:
  4320. yield
  4321. def is_node_meta_valid(node: Optional[torch.fx.Node]) -> bool:
  4322. return node is None or "example_value" in node.meta or "val" in node.meta
  4323. # If True, enforce fullgraph=True - raise errors on graph break
  4324. _error_on_graph_break = False
  4325. def _get_error_on_graph_break() -> bool:
  4326. return _error_on_graph_break
  4327. def _set_error_on_graph_break(value: bool) -> None:
  4328. global _error_on_graph_break
  4329. _error_on_graph_break = value
  4330. @torch._disable_dynamo
  4331. def record_pregraph_bytecode_enter() -> AbstractContextManager[None]:
  4332. cm: AbstractContextManager[None] = (
  4333. torch._C._profiler._RecordFunctionFast("Pregraph bytecode")
  4334. if torch.autograd.profiler._is_profiler_enabled
  4335. else contextlib.nullcontext()
  4336. )
  4337. cm.__enter__()
  4338. return cm
  4339. @torch._disable_dynamo
  4340. def record_pregraph_bytecode_exit(cm: AbstractContextManager[None]) -> None:
  4341. cm.__exit__(None, None, None)
  4342. # Returns a set of code objects present traced in the current TracingContext, or None
  4343. # if there is no current TracingContext.
  4344. def get_traced_code() -> Optional[list[CodeType]]:
  4345. from torch._guards import TracingContext
  4346. return TracingContext.get_traced_code()
  4347. def raise_on_overridden_hash(obj: Any, vt: VariableTracker) -> None:
  4348. from . import graph_break_hints
  4349. from .exc import unimplemented
  4350. is_overridden = type(obj).__dict__.get("__hash__", False)
  4351. if is_overridden:
  4352. unimplemented(
  4353. gb_type="User-defined object with overridden __hash__",
  4354. context=f"hashing object of type={type(obj)} and variable tracker {vt}",
  4355. explanation=f"Found a user-defined object {vt} with overridden __hash__ when attempting to hash it",
  4356. hints=[
  4357. "Dynamo does not support hashing user-defined objects with overridden __hash__",
  4358. *graph_break_hints.SUPPORTABLE,
  4359. ],
  4360. )