utils.py 166 KB

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