utils.py 171 KB

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