guards.py 185 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645
  1. """
  2. Core guard system for Dynamo that detects when compiled code needs to be recompiled due to
  3. changes in program state. Guards are conditions that must remain true for previously-compiled
  4. code to be valid for reuse.
  5. This module provides the infrastructure for creating, managing and checking guards, including:
  6. - Guard creation and composition
  7. - Guard state management and invalidation
  8. - Guard checking and failure handling
  9. - Utilities for guard optimization and debugging
  10. - Integration with Dynamo's compilation caching
  11. The guard system is critical for Dynamo's ability to efficiently reuse compiled code while
  12. maintaining correctness by detecting when recompilation is necessary due to changes in
  13. program state, tensor properties, or control flow.
  14. """
  15. from __future__ import annotations
  16. import ast
  17. import builtins
  18. import collections
  19. import dataclasses
  20. import enum
  21. import functools
  22. import importlib
  23. import inspect
  24. import io
  25. import logging
  26. import math
  27. import pickle
  28. import sys
  29. import textwrap
  30. import traceback
  31. import types
  32. import warnings
  33. import weakref
  34. from contextlib import contextmanager
  35. from copy import deepcopy
  36. from inspect import currentframe
  37. from typing import Any, NoReturn, Optional, TYPE_CHECKING, Union
  38. try:
  39. from typing import LiteralString
  40. except ImportError:
  41. from typing_extensions import LiteralString
  42. from typing_extensions import TypeAliasType, TypeVar
  43. from weakref import ReferenceType
  44. import torch
  45. import torch.overrides
  46. import torch.utils._device
  47. from torch._C._dynamo.eval_frame import code_framelocals_names
  48. from torch._C._dynamo.guards import (
  49. check_obj_id,
  50. check_type_id,
  51. ClosureGuardAccessor,
  52. CodeGuardAccessor,
  53. dict_version,
  54. DictGetItemGuardAccessor,
  55. DictGuardManager,
  56. FuncDefaultsGuardAccessor,
  57. FuncKwDefaultsGuardAccessor,
  58. GetAttrGuardAccessor,
  59. GetGenericDictGuardAccessor,
  60. GuardAccessor,
  61. GuardDebugInfo,
  62. GuardManager,
  63. install_no_tensor_aliasing_guard,
  64. install_object_aliasing_guard,
  65. install_storage_overlapping_guard,
  66. install_symbolic_shape_guard,
  67. LeafGuard,
  68. profile_guard_manager,
  69. RelationalGuard,
  70. RootGuardManager,
  71. TupleGetItemGuardAccessor,
  72. TypeDictGuardAccessor,
  73. TypeGuardAccessor,
  74. TypeMROGuardAccessor,
  75. )
  76. from torch._dynamo.source import (
  77. get_global_source_name,
  78. get_local_source_name,
  79. IndexedSource,
  80. is_from_flatten_script_object_source,
  81. is_from_local_source,
  82. is_from_optimizer_source,
  83. is_from_skip_guard_source,
  84. is_from_unspecialized_builtin_nn_module_source,
  85. TensorProperty,
  86. TensorPropertySource,
  87. )
  88. from torch._dynamo.utils import CompileEventLogger, get_metrics_context
  89. from torch._guards import (
  90. CompileContext,
  91. CompileId,
  92. DuplicateInputs,
  93. Guard,
  94. GuardBuilderBase,
  95. GuardEnvExpr,
  96. GuardSource,
  97. Source,
  98. StorageOverlap,
  99. )
  100. from torch._inductor.utils import IndentedBuffer
  101. from torch._library.opaque_object import is_opaque_value_type
  102. from torch._logging import structured
  103. from torch._utils_internal import justknobs_check
  104. from torch.fx.experimental.symbolic_shapes import (
  105. _CppShapeGuardsHelper,
  106. _ShapeGuardsHelper,
  107. EqualityConstraint,
  108. is_symbolic,
  109. SYMPY_INTERP,
  110. )
  111. from torch.utils import _pytree as pytree
  112. from torch.utils._ordered_set import OrderedSet
  113. from torch.utils._traceback import format_frame, report_compile_source_on_error
  114. from torch.utils.weak import TensorWeakRef
  115. from . import config, convert_frame, exc
  116. from .eval_frame import set_guard_error_hook
  117. from .source import (
  118. AttrProxySource,
  119. AttrSource,
  120. CallFunctionNoArgsSource,
  121. CallMethodItemSource,
  122. ChainedSource,
  123. ClosureSource,
  124. CodeSource,
  125. CollectionsSource,
  126. ConstantSource,
  127. ConstDictKeySource,
  128. CurrentStreamSource,
  129. DataclassFieldsSource,
  130. DefaultsSource,
  131. DictGetItemSource,
  132. DictSubclassGetItemSource,
  133. DynamicScalarSource,
  134. FlattenScriptObjectSource,
  135. FloatTensorSource,
  136. FSDPNNModuleSource,
  137. GenericAttrSource,
  138. GetItemSource,
  139. GlobalSource,
  140. GlobalStateSource,
  141. GlobalWeakRefSource,
  142. GradSource,
  143. ListGetItemSource,
  144. LocalSource,
  145. NamedTupleFieldsSource,
  146. NNModuleSource,
  147. NonSerializableSetGetItemSource,
  148. NumpyTensorSource,
  149. OptimizerSource,
  150. ScriptObjectQualifiedNameSource,
  151. ShapeEnvSource,
  152. SubclassAttrListSource,
  153. TorchFunctionModeStackSource,
  154. TorchSource,
  155. TupleIteratorGetItemSource,
  156. TypeDictSource,
  157. TypeMROSource,
  158. TypeSource,
  159. UnspecializedBuiltinNNModuleSource,
  160. UnspecializedNNModuleSource,
  161. UnspecializedParamBufferSource,
  162. WeakRefCallSource,
  163. )
  164. from .types import ( # noqa: F401
  165. CacheEntry,
  166. DynamoFrameType,
  167. ExtraState,
  168. GuardedCode,
  169. GuardFail,
  170. GuardFilterEntry,
  171. GuardFn,
  172. )
  173. from .utils import (
  174. builtin_dict_keys,
  175. common_constant_types,
  176. dataclass_fields,
  177. dict_keys,
  178. get_current_stream,
  179. get_custom_getattr,
  180. get_torch_function_mode_stack,
  181. get_torch_function_mode_stack_at,
  182. guard_failures,
  183. istype,
  184. key_is_id,
  185. key_to_id,
  186. normalize_range_iter,
  187. orig_code_map,
  188. tensor_always_has_static_shape,
  189. tuple_iterator_getitem,
  190. tuple_iterator_len,
  191. unpatched_nn_module_getattr,
  192. verify_guard_fn_signature,
  193. )
  194. if TYPE_CHECKING:
  195. from collections.abc import Callable
  196. guard_manager_testing_hook_fn: Optional[Callable[[Any, Any, Any], Any]] = None
  197. try:
  198. import numpy as np
  199. except ModuleNotFoundError:
  200. np = None # type: ignore[assignment]
  201. if TYPE_CHECKING:
  202. from collections.abc import Generator, KeysView, Sequence
  203. from sympy import Symbol
  204. from torch._C import DispatchKeySet
  205. from torch._dynamo.output_graph import OutputGraphCommon, OutputGraphGuardsState
  206. T = TypeVar("T")
  207. log = logging.getLogger(__name__)
  208. guards_log = torch._logging.getArtifactLogger(__name__, "guards")
  209. recompiles_log = torch._logging.getArtifactLogger(__name__, "recompiles")
  210. recompiles_verbose_log = torch._logging.getArtifactLogger(
  211. __name__, "recompiles_verbose"
  212. )
  213. verbose_guards_log = torch._logging.getArtifactLogger(__name__, "verbose_guards")
  214. dunder_attrs_assumed_constants = (
  215. "__defaults__",
  216. "__kwdefaults__",
  217. "__code__",
  218. "__closure__",
  219. "__annotations__",
  220. "__func__",
  221. "__mro__",
  222. )
  223. def get_framelocals_idx(code: types.CodeType, var_name: str) -> int:
  224. # Refer to index in the frame's localsplus directly.
  225. # NOTE: name order for a code object doesn't change.
  226. # NOTE: we need to find the LAST matching index because <= 3.10 contains
  227. # duplicate names in the case of cells: a name can be both local and cell
  228. # and will take up 2 slots of the frame's localsplus. The correct behavior
  229. # is to refer to the cell, which has a higher index.
  230. framelocals_names_reversed = code_framelocals_names_reversed_cached(code)
  231. framelocals_idx = (
  232. len(framelocals_names_reversed) - framelocals_names_reversed.index(var_name) - 1
  233. )
  234. return framelocals_idx
  235. class IndentedBufferWithPrefix(IndentedBuffer):
  236. def prefix(self) -> str:
  237. return "| " * (self._indent * self.tabwidth)
  238. def writeline(self, line: str, skip_prefix: bool = False) -> None: # type: ignore[override]
  239. if skip_prefix:
  240. super().writeline(line)
  241. else:
  242. super().writeline("+- " + line)
  243. class GuardManagerWrapper:
  244. """
  245. A helper class that contains the root guard manager. An instance of this
  246. class is stored in the Dynamo cache entry, so that the cache entry can
  247. access the RootGuardManager stored in the "root" attribute and directly call
  248. the check_nopybind from C++.
  249. """
  250. def __init__(self, root: Optional[RootGuardManager] = None) -> None:
  251. if root is None:
  252. self.root = RootGuardManager()
  253. else:
  254. self.root = root
  255. self.diff_guard_root: Optional[RootGuardManager] = None
  256. self.closure_vars: Optional[dict[str, Any]] = None
  257. self.args: Optional[list[str]] = None
  258. self.code_parts: list[str] = []
  259. self.verbose_code_parts: Optional[list[str]] = None
  260. self.global_scope: Optional[dict[str, Any]] = None
  261. self.guard_fail_fn: Optional[Callable[[GuardFail], None]] = None
  262. self.cache_entry: Optional[CacheEntry] = None
  263. self.extra_state: Optional[ExtraState] = None
  264. self.id_matched_objs: dict[str, ReferenceType[object]] = {}
  265. self.no_tensor_aliasing_sources: list[str] = []
  266. self.printed_relational_guards: set[RelationalGuard] = set()
  267. self.diff_guard_sources: OrderedSet[str] = OrderedSet()
  268. @contextmanager
  269. def _preserve_printed_relational_guards(self) -> Generator[None, None, None]:
  270. self.printed_relational_guards = set()
  271. try:
  272. yield
  273. finally:
  274. self.printed_relational_guards = set()
  275. # TODO: clarify what fn and attributes guard manager has to get the right things here
  276. def collect_diff_guard_sources(self) -> OrderedSet[str]:
  277. # At the time of finalize, we have only marked guard managers with
  278. # TENSOR_MATCH guards as diff guard managers. So, we do a tree traversal
  279. # and collect all the nodes in the tree (branches) that lead to tensor
  280. # guards.
  281. # After a recompilation, some of guard managers will have a fail_count >
  282. # 0, so we collect them as well. Later on, we accumulate the diff guard
  283. # sources for all the guard managers.
  284. def visit_dict_manager(node: DictGuardManager) -> bool:
  285. is_diff_guard_node = (
  286. node.get_source() in self.diff_guard_sources or node.fail_count() > 0
  287. )
  288. for _idx, (key_mgr, val_mgr) in sorted(
  289. node.get_key_value_managers().items()
  290. ):
  291. is_diff_guard_node |= visit(key_mgr) | visit(val_mgr)
  292. if is_diff_guard_node:
  293. self.diff_guard_sources.add(node.get_source())
  294. return is_diff_guard_node
  295. def visit_manager(node: GuardManager) -> bool:
  296. assert not isinstance(node, DictGuardManager)
  297. is_diff_guard_node = (
  298. node.get_source() in self.diff_guard_sources or node.fail_count() > 0
  299. )
  300. for child_mgr in node.get_child_managers():
  301. is_diff_guard_node |= visit(child_mgr)
  302. if is_diff_guard_node:
  303. self.diff_guard_sources.add(node.get_source())
  304. return is_diff_guard_node
  305. def visit(node: GuardManager) -> bool:
  306. if node is None:
  307. return False
  308. if isinstance(node, DictGuardManager):
  309. return visit_dict_manager(node)
  310. return visit_manager(node)
  311. visit(self.root)
  312. return self.diff_guard_sources
  313. def finalize(self) -> None:
  314. if config.use_recursive_dict_tags_for_guards and justknobs_check(
  315. "pytorch/compiler:use_recursive_dict_tags_for_guards"
  316. ):
  317. self.find_tag_safe_roots()
  318. self.prepare_diff_guard_manager()
  319. def prepare_diff_guard_manager(self) -> None:
  320. self.collect_diff_guard_sources()
  321. self.populate_diff_guard_manager()
  322. def find_tag_safe_roots(self) -> None:
  323. """
  324. Identify ``tag safe nodes`` and ``tag safe roots`` within a guard tree.
  325. -----------------------------------------------------------------------
  326. tag safe node
  327. -----------------------------------------------------------------------
  328. A *tag safe node* is a ``GuardManager`` whose guarded value satisfies one
  329. of the following conditions:
  330. 1. Immutable value - The value is intrinsically immutable according to
  331. ``is_immutable_object``. Tensors are considered immutable. To ensure
  332. that symbolic guards run, we also check that the GuardManager has no
  333. accessors.
  334. 2. Nested tag safe dictionary - The value is a ``dict`` whose keys and
  335. values are all tag safe nodes (checked recursively). Such dictionaries
  336. allow entire nested structures to be skipped once their identity tag
  337. matches.
  338. 3. Pure ``nn.Module`` - The value is an ``nn.Module`` whose sole
  339. accessor is ``GetGenericDictGuardAccessor``—i.e., it only exposes its
  340. ``__dict__`` and nothing else that could mutate between runs.
  341. For every tag safe node, verifying the identity/tag of just the top-level
  342. dictionary is enough to guarantee the entire subtree is unchanged, enabling
  343. a *fast-path* guard check.
  344. -----------------------------------------------------------------------
  345. tag safe root
  346. -----------------------------------------------------------------------
  347. A ``tag safe root`` is a tag safe node whose parent is not tag safe.
  348. These boundary nodes mark the points where guard evaluation can safely
  349. prune traversal: if a tag-safe root's dictionary tag matches, the entire
  350. subtree beneath it is skipped.
  351. One strong requirement for tag safe root is for the guarded object to
  352. support weakref. Refer to more details in the Recursive dict tag
  353. matching note. In short, we need to save the weakref of the object on
  354. first invocation, and check if it is still valid in later iterations, to
  355. apply recursive dict tag optimizations. `dict` objects do NOT support
  356. weakref. Therefore, as of now, we only mark nn module related guard
  357. managers as tag safe roots.
  358. Algorithm
  359. ---------
  360. The search runs in post-order traversal
  361. 1. Visit leaves and classify them as tag safe or not.
  362. 2. Propagate tag-safety upward: a parent dictionary becomes tag safe only if
  363. all of its children are already tag-safe.
  364. 3. Propagate tag-safe-rootness upward: if the whole subtree is tag safe,
  365. the current node becomes the new tag safe root, otherwise propagate the
  366. subtree tag safe roots.
  367. 4. Collect every tag safe node and, by inspecting parent tags, label the
  368. subset that are tag safe roots.
  369. """
  370. def check_tag_safety(
  371. node: GuardManager, accepted_accessors: tuple[type[GuardAccessor], ...]
  372. ) -> bool:
  373. accessors = node.get_accessors()
  374. child_mgrs = node.get_child_managers()
  375. return all(
  376. isinstance(accessor, accepted_accessors) and mgr.is_tag_safe()
  377. for accessor, mgr in zip(accessors, child_mgrs)
  378. )
  379. def visit_dict_manager(node: DictGuardManager) -> list[GuardManager]:
  380. # Just recurse through the key and value dict managers and check if
  381. # all of them are tag safe nodes.
  382. assert issubclass(node.get_type_of_guarded_value(), dict)
  383. tag_safe_roots = []
  384. is_subtree_tag_safe = True
  385. # Recurse to get the tag safe roots from subtree.
  386. for _idx, (key_mgr, val_mgr) in sorted(
  387. node.get_key_value_managers().items()
  388. ):
  389. if key_mgr is not None:
  390. visit(key_mgr)
  391. if val_mgr is not None:
  392. tag_safe_roots.extend(visit(val_mgr))
  393. for key_mgr, val_mgr in node.get_key_value_managers().values():
  394. if key_mgr:
  395. is_subtree_tag_safe &= key_mgr.is_tag_safe()
  396. if val_mgr:
  397. is_subtree_tag_safe &= val_mgr.is_tag_safe()
  398. if is_subtree_tag_safe:
  399. node.mark_tag_safe()
  400. return tag_safe_roots
  401. def visit_manager(node: GuardManager) -> list[GuardManager]:
  402. assert not isinstance(node, DictGuardManager)
  403. # Collect the subtree tag safe roots
  404. tag_safe_roots = []
  405. for child_mgr in node.get_child_managers():
  406. tag_safe_roots.extend(visit(child_mgr))
  407. if node.is_guarded_value_immutable():
  408. # If the node guards a tensor, mark it tag safe only if there
  409. # are no accessors. Presence of accessors means presence of
  410. # symbolic shape guards.
  411. if issubclass(node.get_type_of_guarded_value(), torch.Tensor):
  412. if node.has_no_accessors() and not node.has_object_aliasing_guard():
  413. node.mark_tag_safe()
  414. else:
  415. node.mark_tag_safe()
  416. elif issubclass(node.get_type_of_guarded_value(), dict):
  417. accessors = node.get_accessors()
  418. child_mgrs = node.get_child_managers()
  419. is_subtree_tag_safe = all(
  420. isinstance(accessor, DictGetItemGuardAccessor) and mgr.is_tag_safe()
  421. for accessor, mgr in zip(accessors, child_mgrs)
  422. )
  423. if is_subtree_tag_safe:
  424. node.mark_tag_safe()
  425. elif issubclass(node.get_type_of_guarded_value(), torch.nn.Module):
  426. is_subtree_tag_safe = check_tag_safety(
  427. node, (GetGenericDictGuardAccessor, TypeGuardAccessor)
  428. )
  429. if is_subtree_tag_safe:
  430. node.mark_tag_safe()
  431. # Return the current node as tag safe root, discarding the
  432. # subtree tag safe roots.
  433. return [
  434. node,
  435. ]
  436. elif (
  437. node.get_type_of_guarded_value()
  438. in (
  439. types.FunctionType,
  440. types.MethodType,
  441. staticmethod,
  442. classmethod,
  443. )
  444. and config.assume_dunder_attributes_remain_unchanged
  445. ):
  446. # Assumption: callers will not reassignthe attributes
  447. # func.__code__, func.__closure__, func.__defaults__, or func.__kwdefaults__.
  448. # Mutating the objects those attributes point to is fine;
  449. # rebinding the attribute itself is not.
  450. # Example ─ allowed: foo.__defaults__[0].bar = 99
  451. # forbidden: foo.__defaults__ = (3, 4)
  452. is_subtree_tag_safe = check_tag_safety(
  453. node,
  454. (
  455. CodeGuardAccessor,
  456. ClosureGuardAccessor,
  457. FuncDefaultsGuardAccessor,
  458. FuncKwDefaultsGuardAccessor,
  459. GetAttrGuardAccessor,
  460. ),
  461. )
  462. for accessor in node.get_accessors():
  463. if isinstance(accessor, GetAttrGuardAccessor):
  464. is_subtree_tag_safe &= (
  465. accessor.get_attr_name() in dunder_attrs_assumed_constants
  466. )
  467. if is_subtree_tag_safe:
  468. node.mark_tag_safe()
  469. elif issubclass(node.get_type_of_guarded_value(), types.CellType):
  470. is_subtree_tag_safe = check_tag_safety(node, (GetAttrGuardAccessor,))
  471. is_subtree_tag_safe &= all(
  472. isinstance(accessor, GetAttrGuardAccessor)
  473. and accessor.get_attr_name() == "cell_contents"
  474. for accessor in node.get_accessors()
  475. )
  476. if is_subtree_tag_safe:
  477. node.mark_tag_safe()
  478. elif (
  479. issubclass(node.get_type_of_guarded_value(), tuple)
  480. and node.get_source().endswith(dunder_attrs_assumed_constants)
  481. and config.assume_dunder_attributes_remain_unchanged
  482. ):
  483. # We trust tuples obtained from a function's __closure__ or
  484. # __defaults__. Any *other* tuple-valued attribute can be
  485. # silently replaced—for example:
  486. #
  487. # foo.bar = (1, 2) # original
  488. # foo.bar = (3, 4) # rebinding that our dict-tag optimisation won't see
  489. #
  490. # Therefore only tuples from __closure__ / __defaults__ participate in the
  491. # recursive-dict-tag optimization; all others are ignored.
  492. is_subtree_tag_safe = check_tag_safety(
  493. node, (TupleGetItemGuardAccessor,)
  494. )
  495. if is_subtree_tag_safe:
  496. node.mark_tag_safe()
  497. elif issubclass(node.get_type_of_guarded_value(), type):
  498. is_subtree_tag_safe = check_tag_safety(
  499. node, (TypeDictGuardAccessor, TypeMROGuardAccessor)
  500. )
  501. if is_subtree_tag_safe:
  502. node.mark_tag_safe()
  503. return tag_safe_roots
  504. def visit(node: GuardManager) -> list[GuardManager]:
  505. if node is None:
  506. return []
  507. if isinstance(node, DictGuardManager):
  508. return visit_dict_manager(node)
  509. return visit_manager(node)
  510. tag_safe_roots = visit(self.root)
  511. for node in tag_safe_roots:
  512. if issubclass(node.get_type_of_guarded_value(), torch.nn.Module):
  513. node.mark_tag_safe_root()
  514. def populate_diff_guard_manager(self) -> None:
  515. self.diff_guard_root = self.clone_with_chosen_sources(self.diff_guard_sources)
  516. # Ensure that that C++ side points to the updated diff guard manager.
  517. # When a new GuardManagerWrapper is created, it does not have a
  518. # cache_entry attribute, so it relies on the CacheEntry constructor to
  519. # set the diff_guard_root in C++. But once it is saved in the Dynamo
  520. # cache, C++ side adds a cache_entry attribute. On recompiles, this
  521. # cache_entry is visible, so we update the C++ side to point to the
  522. # update guard manager.
  523. if self.cache_entry:
  524. self.cache_entry.update_diff_guard_root_manager()
  525. def clone_with_chosen_sources(
  526. self, chosen_sources: OrderedSet[str]
  527. ) -> RootGuardManager:
  528. def filter_fn(node_mgr: GuardManager) -> bool:
  529. return node_mgr.get_source() in chosen_sources
  530. return self.root.clone_manager(filter_fn)
  531. def get_guard_lines(self, guard: LeafGuard) -> list[str]:
  532. guard_name = guard.__class__.__name__
  533. parts = guard.verbose_code_parts()
  534. parts = [guard_name + ": " + part for part in parts]
  535. return parts
  536. def get_manager_line(
  537. self, guard_manager: GuardManager, accessor_str: Optional[str] = None
  538. ) -> str:
  539. source = guard_manager.get_source()
  540. t = guard_manager.__class__.__name__
  541. s = t + ": source=" + source
  542. if accessor_str:
  543. s += ", " + accessor_str
  544. s += f", type={guard_manager.get_type_of_guarded_value()}"
  545. s += f", tag_safe=({guard_manager.is_tag_safe()}, {guard_manager.is_tag_safe_root()})"
  546. return s
  547. def construct_dict_manager_string(
  548. self, mgr: DictGuardManager, body: IndentedBufferWithPrefix
  549. ) -> None:
  550. for idx, (key_mgr, val_mgr) in sorted(mgr.get_key_value_managers().items()):
  551. body.writeline(f"KeyValueManager pair at index={idx}")
  552. with body.indent():
  553. if key_mgr:
  554. body.writeline(f"KeyManager: {self.get_manager_line(key_mgr)}")
  555. self.construct_manager_string(key_mgr, body)
  556. if val_mgr:
  557. body.writeline(f"ValueManager: {self.get_manager_line(val_mgr)}")
  558. self.construct_manager_string(val_mgr, body)
  559. def construct_manager_string(
  560. self, mgr: GuardManager, body: IndentedBufferWithPrefix
  561. ) -> None:
  562. with body.indent():
  563. for guard in mgr.get_leaf_guards():
  564. if isinstance(guard, RelationalGuard):
  565. if guard not in self.printed_relational_guards:
  566. self.printed_relational_guards.add(guard)
  567. # pyrefly: ignore [bad-argument-type]
  568. body.writelines(self.get_guard_lines(guard))
  569. else:
  570. body.writelines(
  571. [
  572. guard.__class__.__name__,
  573. ]
  574. )
  575. else:
  576. body.writelines(self.get_guard_lines(guard))
  577. # This works for both DictGuardManager and SubclassedDictGuardManager
  578. if isinstance(mgr, DictGuardManager):
  579. self.construct_dict_manager_string(mgr, body)
  580. # General case of GuardManager/RootGuardManager
  581. for accessor, child_mgr in zip(
  582. mgr.get_accessors(), mgr.get_child_managers()
  583. ):
  584. body.writeline(
  585. self.get_manager_line(child_mgr, f"accessed_by={accessor.repr()}")
  586. )
  587. self.construct_manager_string(child_mgr, body)
  588. def __str__(self) -> str:
  589. with self._preserve_printed_relational_guards():
  590. body = IndentedBufferWithPrefix()
  591. body.tabwidth = 1
  592. body.writeline("", skip_prefix=True)
  593. body.writeline("TREE_GUARD_MANAGER:", skip_prefix=True)
  594. body.writeline("RootGuardManager")
  595. self.construct_manager_string(self.root, body)
  596. if hasattr(self.root, "get_epilogue_lambda_guards"):
  597. for guard in self.root.get_epilogue_lambda_guards():
  598. body.writelines(self.get_guard_lines(guard))
  599. return body.getvalue()
  600. def check(self, x: Any) -> bool:
  601. # Only needed for debugging purposes.
  602. return self.root.check(x)
  603. def check_verbose(self, x: Any) -> GuardDebugInfo:
  604. # Only needed for debugging purposes.
  605. return self.root.check_verbose(x)
  606. def populate_code_parts_for_debugging(self) -> None:
  607. # This should be called when the guard manager is fully populated
  608. relational_guards_seen = set()
  609. def get_code_parts(leaf_guard: LeafGuard) -> list[str]:
  610. code_parts = []
  611. for verbose_code_part in leaf_guard.verbose_code_parts():
  612. code_part = verbose_code_part.split("#")[0].rstrip()
  613. code_parts.append(code_part)
  614. return code_parts
  615. def visit(mgr: GuardManager) -> None:
  616. nonlocal relational_guards_seen
  617. for guard in mgr.get_leaf_guards():
  618. if isinstance(guard, RelationalGuard):
  619. if guard not in relational_guards_seen:
  620. # pyrefly: ignore [bad-argument-type]
  621. self.code_parts.extend(get_code_parts(guard))
  622. relational_guards_seen.add(guard)
  623. else:
  624. self.code_parts.extend(get_code_parts(guard))
  625. for child_mgr in mgr.get_child_managers():
  626. visit(child_mgr)
  627. visit(self.root)
  628. def from_numpy(a: Any) -> torch.Tensor:
  629. # If not numpy array, piggy back on e.g. tensor guards to check type
  630. # Re-enable torch function since we disable it on leaf guards
  631. # we need it to properly construct the tensor if a default device is set
  632. with torch.overrides._enable_torch_function():
  633. # pyrefly: ignore [missing-attribute]
  634. return torch.as_tensor(a) if isinstance(a, (np.generic, np.ndarray)) else a
  635. # For user stack printing
  636. @functools.cache
  637. def uninteresting_files() -> set[str]:
  638. import torch._dynamo.external_utils
  639. import torch._dynamo.polyfills
  640. mods = [torch._dynamo.external_utils, torch._dynamo.polyfills]
  641. from torch._dynamo.polyfills.loader import POLYFILLED_MODULES
  642. # pyrefly: ignore [bad-argument-type]
  643. mods.extend(POLYFILLED_MODULES)
  644. return {inspect.getfile(m) for m in mods}
  645. _CLOSURE_VARS: Optional[dict[str, object]] = None
  646. def _get_closure_vars() -> dict[str, object]:
  647. global _CLOSURE_VARS
  648. if _CLOSURE_VARS is None:
  649. _CLOSURE_VARS = {
  650. "___check_type_id": check_type_id,
  651. "___check_obj_id": check_obj_id,
  652. "___odict_getitem": collections.OrderedDict.__getitem__,
  653. "___key_to_id": key_to_id,
  654. "___dict_version": dict_version,
  655. "___dict_contains": lambda a, b: dict.__contains__(b, a),
  656. "___tuple_iterator_len": tuple_iterator_len,
  657. "___normalize_range_iter": normalize_range_iter,
  658. "___tuple_iterator_getitem": tuple_iterator_getitem,
  659. "___dataclass_fields": dataclass_fields,
  660. "___namedtuple_fields": lambda x: x._fields,
  661. "___get_torch_function_mode_stack_at": get_torch_function_mode_stack_at,
  662. "___get_current_stream": get_current_stream,
  663. "__math_isnan": math.isnan,
  664. "__numpy_isnan": None if np is None else np.isnan,
  665. "inf": float("inf"),
  666. "__load_module": importlib.import_module,
  667. "utils_device": torch.utils._device,
  668. "device": torch.device,
  669. "___from_numpy": from_numpy,
  670. "___as_tensor": torch._as_tensor_fullprec,
  671. "torch": torch,
  672. "inspect": inspect,
  673. }
  674. return _CLOSURE_VARS
  675. def _ast_unparse(node: ast.AST) -> str:
  676. return ast.unparse(node).replace("\n", "")
  677. strip_function_call = torch._C._dynamo.strip_function_call
  678. def get_verbose_code_part(code_part: str, guard: Optional[Guard]) -> str:
  679. extra = ""
  680. if guard is not None:
  681. if guard.user_stack:
  682. for fs in reversed(guard.user_stack):
  683. if fs.filename not in uninteresting_files():
  684. extra = f" # {format_frame(fs, line=True)}"
  685. if len(extra) > 1024:
  686. # For fx graphs, the line can be very long in case of
  687. # torch.stack ops, where many inputs are set to None
  688. # after the operation. This increases the size of the
  689. # guards log file. In such cases, do not print the line
  690. # contents.
  691. extra = f" # {format_frame(fs)}"
  692. break
  693. elif guard.stack:
  694. summary = guard.stack.summary()
  695. if len(summary) > 0:
  696. extra = f" # {format_frame(summary[-1])}"
  697. else:
  698. extra = " # <unknown>"
  699. return f"{code_part:<60}{extra}"
  700. def get_verbose_code_parts(
  701. code_parts: Union[str, list[str]],
  702. guard: Optional[Guard],
  703. recompile_hint: Optional[str] = None,
  704. ) -> list[str]:
  705. if not isinstance(code_parts, list):
  706. code_parts = [code_parts]
  707. verbose_code_parts = [
  708. get_verbose_code_part(code_part, guard) for code_part in code_parts
  709. ]
  710. if recompile_hint:
  711. verbose_code_parts = [
  712. f"{part} (HINT: {recompile_hint})" for part in verbose_code_parts
  713. ]
  714. return verbose_code_parts
  715. def convert_int_to_concrete_values(dim: Any) -> Optional[int]:
  716. if dim is None:
  717. return None
  718. if not is_symbolic(dim):
  719. return dim
  720. else:
  721. assert isinstance(dim, torch.SymInt)
  722. return dim.node.maybe_as_int()
  723. def convert_to_concrete_values(size_or_stride: list[Any]) -> list[Optional[int]]:
  724. return [convert_int_to_concrete_values(dim) for dim in size_or_stride]
  725. def get_tensor_guard_code_part(
  726. value: torch.Tensor,
  727. name: str,
  728. sizes: list[Optional[int]],
  729. strides: list[Optional[int]],
  730. pytype: type,
  731. dispatch_keys: DispatchKeySet,
  732. ) -> str:
  733. dispatch_key = (
  734. dispatch_keys | torch._C._dispatch_tls_local_include_set()
  735. ) - torch._C._dispatch_tls_local_exclude_set()
  736. dtype = value.dtype
  737. device_index = value.device.index
  738. requires_grad = value.requires_grad
  739. guard_str = (
  740. f"check_tensor({name}, {pytype.__qualname__}, {dispatch_key}, {dtype}, "
  741. f"device={device_index}, requires_grad={requires_grad}, size={sizes}, stride={strides})"
  742. )
  743. return guard_str
  744. def get_key_index(dct: dict[Any, Any], key: Any) -> int:
  745. # Ensure that we call dict.keys and not value.keys (which can call
  746. # overridden keys method). In the C++ guards, we relied on PyDict_Next
  747. # to traverse the dictionary, which uses the internal data structure and
  748. # does not call the overridden keys method.
  749. return list(builtin_dict_keys(dct)).index(key)
  750. def get_key_index_source(source: Any, index: Any) -> str:
  751. return f"list(dict.keys({source}))[{index}]"
  752. def raise_local_type_error(obj: Any) -> NoReturn:
  753. raise TypeError(
  754. f"Type {type(obj)} for object {obj} cannot be saved "
  755. + "into torch.compile() package since it's defined in local scope. "
  756. + "Please define the class at global scope (top level of a module)."
  757. )
  758. def should_optimize_getattr_on_nn_module(value: Any) -> bool:
  759. # If inline_inbuilt_nn_modules flag is True, Dynamo has already traced
  760. # through the __getattr__, and therefore it is always safe to optimize
  761. # getattr on nn modules.
  762. return isinstance(value, torch.nn.Module) and (
  763. config.inline_inbuilt_nn_modules
  764. or get_custom_getattr(value) is unpatched_nn_module_getattr
  765. )
  766. @dataclasses.dataclass(frozen=True)
  767. class NNModuleAttrAccessorInfo:
  768. # Represents where is the attr name is present in the nn module attribute
  769. # access
  770. # Tells that the attribute can be accessed via __dict__
  771. present_in_generic_dict: bool = False
  772. # Either the actual name or _parameters/_buffers/_modules
  773. l1_key: Optional[str] = None
  774. # Actual parameter/buffer/submodule name
  775. l2_key: Optional[str] = None
  776. def getitem_on_dict_manager(
  777. source: Union[DictGetItemSource, DictSubclassGetItemSource],
  778. base_guard_manager: DictGuardManager,
  779. base_example_value: Any,
  780. example_value: Any,
  781. guard_manager_enum: GuardManagerType,
  782. ) -> GuardManager:
  783. base_source_name = source.base.name
  784. if isinstance(source.index, ConstDictKeySource):
  785. index = source.index.index
  786. else:
  787. assert isinstance(base_example_value, dict)
  788. index = get_key_index(base_example_value, source.index)
  789. key_source = get_key_index_source(base_source_name, index)
  790. # Ensure that we call dict.keys and not value.keys (which can call
  791. # overridden keys method). In the C++ guards, we relied on PyDict_Next
  792. # to traverse the dictionary, which uses the internal data structure and
  793. # does not call the overridden keys method.
  794. key_example_value = list(builtin_dict_keys(base_example_value))[index]
  795. if isinstance(key_example_value, (int, str)):
  796. value_source = f"{base_source_name}[{key_example_value!r}]"
  797. else:
  798. value_source = f"{base_source_name}[{key_source}]"
  799. if not isinstance(source.index, ConstDictKeySource):
  800. # We have to insert a key manager guard here
  801. # TODO - source debug string is probably wrong here.
  802. base_guard_manager.get_key_manager(
  803. index=index,
  804. source=key_source,
  805. example_value=source.index,
  806. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  807. ).add_equals_match_guard(
  808. source.index, [f"{key_source} == {key_example_value!r}"]
  809. )
  810. return base_guard_manager.get_value_manager(
  811. index=index,
  812. source=value_source,
  813. example_value=example_value,
  814. guard_manager_enum=guard_manager_enum,
  815. )
  816. def match_on_id_for_tensor(guard: Guard) -> bool:
  817. source = guard.originating_source
  818. # For numpy tensors, always use TENSOR_MATCH because __from_numpy leads
  819. # to a new tensor every time and therefore id differs.
  820. if isinstance(source, NumpyTensorSource):
  821. return False
  822. if guard.is_specialized_nn_module():
  823. return True
  824. return source.is_dict_key() and not isinstance(source, GradSource)
  825. # The ready to eval generated code (possibly multiple parts) for a guard, plus
  826. # the original guard object that created it for provenance
  827. @dataclasses.dataclass
  828. class GuardCodeList:
  829. code_list: list[str]
  830. guard: Guard
  831. class GuardManagerType(enum.Enum):
  832. GUARD_MANAGER = 1
  833. DICT_GUARD_MANAGER = 2
  834. @functools.cache
  835. def code_framelocals_names_reversed_cached(code: types.CodeType) -> list[str]:
  836. return list(reversed(code_framelocals_names(code)))
  837. class GuardBuilder(GuardBuilderBase):
  838. def __init__(
  839. self,
  840. f_code: types.CodeType,
  841. id_ref: Callable[[object, str], int],
  842. source_ref: Callable[[Source], str],
  843. lookup_weakrefs: Callable[[object], Optional[weakref.ref[object]]],
  844. local_scope: dict[str, object],
  845. global_scope: dict[str, object],
  846. guard_manager: GuardManagerWrapper,
  847. check_fn_manager: CheckFunctionManager,
  848. save_guards: bool = False,
  849. runtime_global_scope: Optional[dict[str, object]] = None,
  850. source_get_cache: Optional[dict[str, Any]] = None,
  851. ) -> None:
  852. self.f_code = f_code
  853. self.id_ref = id_ref
  854. self.source_ref = source_ref
  855. self.lookup_weakrefs = lookup_weakrefs
  856. self.scope: dict[str, dict[str, object]] = {"L": local_scope, "G": global_scope}
  857. self.src_get_value_cache: weakref.WeakKeyDictionary[Source, object] = (
  858. weakref.WeakKeyDictionary()
  859. )
  860. self.runtime_global_scope = runtime_global_scope or global_scope
  861. self.source_get_cache = source_get_cache or {}
  862. self.scope["__builtins__"] = builtins.__dict__.copy()
  863. for (
  864. name,
  865. package_module,
  866. ) in torch.package.package_importer._package_imported_modules.items():
  867. name = name.replace(">", "_").replace("<", "_").replace(".", "_dot_")
  868. # Write the package module into the scope so that we can import it
  869. self.scope["__builtins__"][name] = package_module
  870. # Write the demangled name to the scope so that we can use it
  871. self.scope[name] = package_module
  872. self.guard_manager = guard_manager
  873. self.argnames: list[str] = []
  874. # Code is python expression strings generated for each guard
  875. self.code: list[GuardCodeList] = []
  876. # shape_env_code is only used by builder and is used for
  877. # shape env code. This exists only because we need to make sure
  878. # shape env guards get run after tensor match guards (since the
  879. # tensor match guards make sure we actually have tensors)
  880. self.shape_env_code: list[GuardCodeList] = []
  881. # Collect the guard managers and debug info to insert no tensor aliasing
  882. # guards.
  883. self.no_tensor_aliasing_names: list[str] = []
  884. self.no_tensor_aliasing_guard_managers: list[GuardManager] = []
  885. self.check_fn_manager: CheckFunctionManager = check_fn_manager
  886. self.guard_tree_values: dict[int, Any] = {}
  887. self.save_guards = save_guards
  888. # Collect the ids of dicts which need key order guarding. source_name is
  889. # not sufficient because for nn modules, we can have different sources
  890. # to access the same object - self._module["param"] is same as
  891. # self.param.
  892. self.key_order_guarded_dict_ids = set()
  893. assert self.check_fn_manager.output_graph is not None
  894. for source in self.check_fn_manager.output_graph.guard_on_key_order:
  895. dict_obj = self.get(source)
  896. if self.save_guards:
  897. self.source_get_cache[source.name] = dict_obj
  898. self.key_order_guarded_dict_ids.add(id(dict_obj))
  899. # Keep track of weak references of objects with ID_MATCH guard. This
  900. # info is stored alongside optimized_code and guard_manager and is used to
  901. # limit the number of cache entries with same ID_MATCH'd object.
  902. self.id_matched_objs: dict[str, ReferenceType[object]] = {}
  903. # Save the guard managers to avoid repeatedly traversing sources.
  904. self._cached_guard_managers: dict[str, GuardManager] = {}
  905. self._cached_duplicate_input_guards: set[tuple[str, str]] = set()
  906. self.object_aliasing_guard_codes: list[tuple[str, str]] = []
  907. self.guard_nn_modules = config.guard_nn_modules and justknobs_check(
  908. "pytorch/compiler:guard_nn_modules"
  909. )
  910. self.already_added_code_parts: OrderedSet[str] = OrderedSet()
  911. def guard_on_dict_keys_and_ignore_order(
  912. self, example_value: dict[Any, Any], guard: Guard
  913. ) -> None:
  914. dict_mgr = self.get_guard_manager(guard)
  915. if isinstance(dict_mgr, DictGuardManager):
  916. raise NotImplementedError(
  917. "Not expecting a DictGuardManager. Seems like Dynamo incorrectly "
  918. f"added the dict to tx.output.guard_on_key_order for {guard.name}"
  919. )
  920. # Iterate over the dicts and install a dict_getitem_manager.
  921. dict_source = guard.originating_source.name
  922. # Ensure that we call dict.keys and not value.keys (which can call
  923. # overridden keys method). In the C++ guards, we relied on PyDict_Next
  924. # to traverse the dictionary, which uses the internal data structure and
  925. # does not call the overridden keys method.
  926. for key in builtin_dict_keys(example_value):
  927. value = example_value[key]
  928. value_source = DictGetItemSource(guard.originating_source, index=key)
  929. guard_manager_enum = self.get_guard_manager_type(
  930. value_source, example_value
  931. )
  932. dict_mgr.dict_getitem_manager(
  933. key=key,
  934. source=f"{dict_source}[{key!r}]",
  935. example_value=value,
  936. guard_manager_enum=guard_manager_enum,
  937. )
  938. def guard_on_dict_keys_and_order(self, value: dict[Any, Any], guard: Guard) -> None:
  939. # Add key managers for the DictGuardManager. Then add either an
  940. # ID_MATCH or EQUALS_MATCH guard on the key.
  941. dict_mgr = self.get_guard_manager(guard)
  942. if not isinstance(dict_mgr, DictGuardManager):
  943. raise NotImplementedError(
  944. "Expecting a DictGuardManager. Seems like Dynamo forgot "
  945. f"to set the right guard manager enum for {guard.name}"
  946. )
  947. assert isinstance(dict_mgr, DictGuardManager)
  948. # Ensure that we call dict.keys and not value.keys (which can call
  949. # overridden keys method). In the C++ guards, we relied on PyDict_Next
  950. # to traverse the dictionary, which uses the internal data structure and
  951. # does not call the overridden keys method.
  952. for idx, key in enumerate(builtin_dict_keys(value)):
  953. key_source = get_key_index_source(guard.name, idx)
  954. key_manager = dict_mgr.get_key_manager(
  955. index=idx,
  956. source=key_source,
  957. example_value=key,
  958. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  959. )
  960. if key_is_id(key):
  961. # Install ID_MATCH guard
  962. id_val = self.id_ref(key, key_source)
  963. key_manager.add_id_match_guard(
  964. id_val,
  965. get_verbose_code_parts(
  966. f"__check_obj_id({key_source}, {id_val})", guard
  967. ),
  968. )
  969. else:
  970. # Install EQUALS_MATCH guard
  971. key_manager.add_equals_match_guard(
  972. key, get_verbose_code_parts(f"{key_source} == {key!r}", guard)
  973. )
  974. @staticmethod
  975. def _get_generic_dict_manager_example_value(example_value: Any) -> Optional[Any]:
  976. # due to a bug in 3.13.0 (introduced by https://github.com/python/cpython/pull/116115,
  977. # reported in https://github.com/python/cpython/issues/125608,
  978. # fixed by https://github.com/python/cpython/pull/125611), we cannot take
  979. # advantage of __dict__ versions to speed up guard checks.
  980. if (
  981. config.issue_3_13_0_warning
  982. and sys.version_info >= (3, 13)
  983. and sys.version_info < (3, 13, 1)
  984. ):
  985. warnings.warn(
  986. "Guards may run slower on Python 3.13.0. Consider upgrading to Python 3.13.1+.",
  987. RuntimeWarning,
  988. )
  989. return None
  990. return example_value
  991. def getattr_on_nn_module(
  992. self,
  993. source: AttrSource,
  994. base_guard_manager: GuardManager,
  995. base_example_value: Any,
  996. example_value: Any,
  997. base_source_name: str,
  998. source_name: str,
  999. guard_manager_enum: GuardManagerType,
  1000. ) -> GuardManager:
  1001. """
  1002. This tries to avoid calling the expensive nn module custom getattr method by
  1003. checking if the attribute is accessible via __dict__. For attributes that
  1004. are not accessible via __dict__ (like descriptors), we fallback to
  1005. PyObject_GetAttr.
  1006. There are two cases that we optimize for
  1007. 1) attributes present directly in __dict__, e.g training.
  1008. 2) parameters/buffers/modules - they can be accessed via _parameters,
  1009. _buffers, _modules keys in __dict__. For example, mod.linear can be
  1010. accessed as mod.__dict__["_parameters"]["linear"]
  1011. The most common and expensive case for nn module guards is of type
  1012. mod.submod1.submod2.submod3.training. We avoid the python getattr of nn
  1013. modules by going through the __dict__.
  1014. """
  1015. def getitem_on_dict_mgr(
  1016. mgr: GuardManager,
  1017. key: Any,
  1018. source_name: str,
  1019. base_example_value: Any,
  1020. example_value: Any,
  1021. guard_manager_enum: GuardManagerType,
  1022. ) -> GuardManager:
  1023. if isinstance(mgr, DictGuardManager):
  1024. # Case where the user code relies on key order, e.g.,
  1025. # named_parameters
  1026. index = get_key_index(base_example_value, key)
  1027. # Install the key manager and add equals match guard
  1028. key_source = f"list(dict.keys({source_name}))[{index!r}]"
  1029. mgr.get_key_manager(
  1030. index=index,
  1031. source=key_source,
  1032. example_value=key,
  1033. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  1034. ).add_equals_match_guard(key, [f"{key_source} == {key!r}"])
  1035. # Install the value manager
  1036. return mgr.get_value_manager(
  1037. index=index,
  1038. source=source_name,
  1039. example_value=example_value,
  1040. guard_manager_enum=guard_manager_enum,
  1041. )
  1042. else:
  1043. return mgr.dict_getitem_manager(
  1044. key=key,
  1045. source=source_name,
  1046. example_value=example_value,
  1047. guard_manager_enum=guard_manager_enum,
  1048. )
  1049. attr_name = source.member
  1050. mod_dict = base_example_value.__dict__
  1051. all_class_attribute_names: set[str] = set()
  1052. for x in inspect.getmro(base_example_value.__class__):
  1053. all_class_attribute_names.update(x.__dict__.keys())
  1054. accessor_info = NNModuleAttrAccessorInfo(False, None, None)
  1055. if attr_name in mod_dict:
  1056. accessor_info = NNModuleAttrAccessorInfo(True, attr_name, None)
  1057. elif "_parameters" in mod_dict and attr_name in mod_dict["_parameters"]:
  1058. accessor_info = NNModuleAttrAccessorInfo(True, "_parameters", attr_name)
  1059. elif "_buffers" in mod_dict and attr_name in mod_dict["_buffers"]:
  1060. accessor_info = NNModuleAttrAccessorInfo(True, "_buffers", attr_name)
  1061. elif (
  1062. attr_name not in all_class_attribute_names
  1063. and "_modules" in mod_dict
  1064. and attr_name in mod_dict["_modules"]
  1065. ):
  1066. # Check test_attr_precedence test - instance attributes always take precedence unless its an nn.Module.
  1067. accessor_info = NNModuleAttrAccessorInfo(True, "_modules", attr_name)
  1068. if not accessor_info.present_in_generic_dict:
  1069. # The attribute can be accessed by __getattribute__ call, so rely on
  1070. # PyObject_GetAttr
  1071. return base_guard_manager.getattr_manager(
  1072. attr=source.member,
  1073. source=source_name,
  1074. example_value=example_value,
  1075. guard_manager_enum=guard_manager_enum,
  1076. )
  1077. else:
  1078. assert accessor_info.l1_key
  1079. l1_key = accessor_info.l1_key
  1080. l2_key = accessor_info.l2_key
  1081. # Set source strings for debug info
  1082. mod_dict_source = f"{base_source_name}.__dict__"
  1083. l1_source_name = l2_source_name = None
  1084. l1_value = l2_value = None
  1085. l1_guard_manager_enum = l2_guard_manager_enum = None
  1086. if l2_key:
  1087. l1_source = AttrSource(source.base, l1_key)
  1088. l1_source_name = l1_source.name
  1089. l1_value = mod_dict[l1_key]
  1090. # do not guard on key order for _parameters etc unless the user code
  1091. # actually needs the key order (e.g. calling named_parameters)
  1092. l1_guard_manager_enum = self.get_guard_manager_type(l1_source, l1_value)
  1093. l2_source_name = source_name
  1094. l2_value = example_value
  1095. l2_guard_manager_enum = self.get_guard_manager_type(
  1096. source, example_value
  1097. )
  1098. else:
  1099. l1_source_name = source_name
  1100. l1_value = example_value
  1101. l1_guard_manager_enum = self.get_guard_manager_type(
  1102. source, example_value
  1103. )
  1104. # Get __dict__ accessor. No need to guard on dict key order, so use base
  1105. # Guard Manager
  1106. mod_generic_dict_manager = base_guard_manager.get_generic_dict_manager(
  1107. source=mod_dict_source,
  1108. example_value=self._get_generic_dict_manager_example_value(mod_dict),
  1109. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  1110. )
  1111. l1_mgr = getitem_on_dict_mgr(
  1112. mgr=mod_generic_dict_manager,
  1113. key=l1_key,
  1114. source_name=l1_source_name,
  1115. base_example_value=mod_dict,
  1116. example_value=l1_value,
  1117. guard_manager_enum=l1_guard_manager_enum,
  1118. )
  1119. if l2_key:
  1120. assert l2_source_name is not None and l2_guard_manager_enum is not None
  1121. return getitem_on_dict_mgr(
  1122. mgr=l1_mgr,
  1123. key=l2_key,
  1124. source_name=l2_source_name,
  1125. base_example_value=l1_value,
  1126. example_value=l2_value,
  1127. guard_manager_enum=l2_guard_manager_enum,
  1128. )
  1129. return l1_mgr
  1130. def requires_key_order_guarding(self, source: Source) -> bool:
  1131. source_name = source.name
  1132. if source_name == "":
  1133. return False
  1134. obj_id = id(self.get(source))
  1135. return obj_id in self.key_order_guarded_dict_ids
  1136. def get_guard_manager_type(
  1137. self,
  1138. source: Source,
  1139. example_value: Optional[
  1140. Union[KeysView[Any], set[Any], frozenset[Any], dict[Any, Any]]
  1141. ],
  1142. ) -> GuardManagerType:
  1143. guard_manager_enum = GuardManagerType.GUARD_MANAGER
  1144. if self.requires_key_order_guarding(source):
  1145. # Fix this if condition
  1146. if isinstance(example_value, dict_keys):
  1147. guard_manager_enum = GuardManagerType.DICT_GUARD_MANAGER
  1148. elif isinstance(example_value, (set, frozenset)):
  1149. # we don't need to guard on key order for set/frozenset
  1150. # but the if above will be true for these types as set is
  1151. # implemented using a dict in Dynamo
  1152. guard_manager_enum = GuardManagerType.GUARD_MANAGER
  1153. else:
  1154. assert isinstance(example_value, dict)
  1155. guard_manager_enum = GuardManagerType.DICT_GUARD_MANAGER
  1156. return guard_manager_enum
  1157. def manager_guards_on_keys(self, mgr_enum: GuardManagerType) -> bool:
  1158. return mgr_enum == GuardManagerType.DICT_GUARD_MANAGER
  1159. def get_global_guard_manager(self) -> GuardManager:
  1160. return self.guard_manager.root.globals_dict_manager(
  1161. f_globals=self.runtime_global_scope,
  1162. source="G",
  1163. example_value=self.scope["G"],
  1164. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  1165. )
  1166. def get_guard_manager_from_source(self, source: Source) -> GuardManager:
  1167. root_guard_manager = self.guard_manager.root
  1168. example_value = None
  1169. source_name = source.name
  1170. if source_name != "" and source_name in self._cached_guard_managers:
  1171. return self._cached_guard_managers[source_name]
  1172. if source_name != "":
  1173. example_value = self.get(source)
  1174. self.guard_tree_values[id(example_value)] = example_value
  1175. guard_manager_enum = self.get_guard_manager_type(source, example_value)
  1176. # Get base manager related information
  1177. base_source_name = None
  1178. base_example_value = None
  1179. base_guard_manager = None
  1180. base_guard_manager_enum = GuardManagerType.GUARD_MANAGER
  1181. if isinstance(source, ChainedSource):
  1182. base_source_name = source.base.name
  1183. base_example_value = self.get(source.base)
  1184. base_guard_manager = self.get_guard_manager_from_source(source.base)
  1185. base_guard_manager_enum = self.get_guard_manager_type(
  1186. source.base, base_example_value
  1187. )
  1188. # Use istype instead of isinstance to check for exact type of source.
  1189. if istype(source, LocalSource):
  1190. framelocals_idx = get_framelocals_idx(self.f_code, source.local_name)
  1191. out = root_guard_manager.framelocals_manager(
  1192. key=(source.local_name, framelocals_idx),
  1193. source=source_name,
  1194. example_value=example_value,
  1195. guard_manager_enum=guard_manager_enum,
  1196. )
  1197. elif istype(source, GlobalSource):
  1198. # Global manager accepts a dict but it is not a DictGuardManager
  1199. # because globals dict is big and we typically guard on a very
  1200. # selected items on globals.
  1201. out = self.get_global_guard_manager().dict_getitem_manager(
  1202. key=source.global_name,
  1203. source=source_name,
  1204. example_value=example_value,
  1205. guard_manager_enum=guard_manager_enum,
  1206. )
  1207. elif istype(source, GlobalWeakRefSource):
  1208. out = self.get_global_guard_manager().global_weakref_manager(
  1209. global_name=source.global_name,
  1210. source=source_name,
  1211. example_value=example_value,
  1212. guard_manager_enum=guard_manager_enum,
  1213. )
  1214. elif istype(source, GlobalStateSource):
  1215. # Don't do anything here. We guard on global state completely in
  1216. # C++. So just return the root mgr.
  1217. return root_guard_manager
  1218. elif istype(source, ShapeEnvSource):
  1219. return root_guard_manager
  1220. elif istype(source, TypeSource):
  1221. assert base_guard_manager # to make mypy happy
  1222. out = base_guard_manager.type_manager(
  1223. source=source_name,
  1224. example_value=example_value,
  1225. guard_manager_enum=guard_manager_enum,
  1226. )
  1227. elif istype(source, TypeDictSource):
  1228. assert base_guard_manager # to make mypy happy
  1229. out = base_guard_manager.type_dict_manager(
  1230. source=source_name,
  1231. example_value=example_value,
  1232. guard_manager_enum=guard_manager_enum,
  1233. )
  1234. elif istype(source, TypeMROSource):
  1235. assert base_guard_manager # to make mypy happy
  1236. out = base_guard_manager.type_mro_manager(
  1237. source=source_name,
  1238. example_value=example_value,
  1239. guard_manager_enum=guard_manager_enum,
  1240. )
  1241. elif istype(
  1242. source,
  1243. (
  1244. OptimizerSource,
  1245. NNModuleSource,
  1246. UnspecializedNNModuleSource,
  1247. UnspecializedBuiltinNNModuleSource,
  1248. FSDPNNModuleSource,
  1249. ),
  1250. ):
  1251. assert base_guard_manager # to make mypy happy
  1252. out = base_guard_manager
  1253. elif istype(source, TorchSource):
  1254. out = root_guard_manager.lambda_manager(
  1255. python_lambda=lambda _: torch,
  1256. source=source_name,
  1257. example_value=example_value,
  1258. guard_manager_enum=guard_manager_enum,
  1259. )
  1260. elif istype(source, CollectionsSource):
  1261. out = root_guard_manager.lambda_manager(
  1262. python_lambda=lambda _: collections,
  1263. source=source_name,
  1264. example_value=example_value,
  1265. guard_manager_enum=guard_manager_enum,
  1266. )
  1267. elif istype(source, TorchFunctionModeStackSource):
  1268. out = root_guard_manager.lambda_manager(
  1269. python_lambda=lambda _: get_torch_function_mode_stack_at(
  1270. source._get_index()
  1271. ),
  1272. source=source_name,
  1273. example_value=example_value,
  1274. guard_manager_enum=guard_manager_enum,
  1275. )
  1276. elif istype(source, CurrentStreamSource):
  1277. out = root_guard_manager.lambda_manager(
  1278. python_lambda=lambda _: get_current_stream(source.device),
  1279. source=source_name,
  1280. example_value=example_value,
  1281. guard_manager_enum=guard_manager_enum,
  1282. )
  1283. elif istype(source, GradSource):
  1284. assert base_guard_manager # to make mypy happy
  1285. out = base_guard_manager.grad_manager(
  1286. source=source_name,
  1287. example_value=example_value,
  1288. guard_manager_enum=guard_manager_enum,
  1289. )
  1290. elif istype(source, GenericAttrSource):
  1291. assert base_guard_manager # to make mypy happy
  1292. out = base_guard_manager.generic_getattr_manager(
  1293. attr=source.member,
  1294. source=source_name,
  1295. example_value=example_value,
  1296. guard_manager_enum=guard_manager_enum,
  1297. )
  1298. elif istype(source, (AttrSource, UnspecializedParamBufferSource)):
  1299. assert base_guard_manager # to make mypy happy
  1300. assert isinstance(source, AttrSource)
  1301. if should_optimize_getattr_on_nn_module(base_example_value):
  1302. assert base_source_name
  1303. out = self.getattr_on_nn_module(
  1304. source,
  1305. base_guard_manager,
  1306. base_example_value,
  1307. example_value,
  1308. base_source_name,
  1309. source_name,
  1310. guard_manager_enum,
  1311. )
  1312. else:
  1313. out = base_guard_manager.getattr_manager(
  1314. attr=source.member,
  1315. source=source_name,
  1316. example_value=example_value,
  1317. guard_manager_enum=guard_manager_enum,
  1318. )
  1319. elif istype(source, (DictGetItemSource, DictSubclassGetItemSource)):
  1320. assert base_guard_manager # to make mypy happy
  1321. assert isinstance(base_example_value, (dict, collections.OrderedDict))
  1322. assert isinstance(source, (DictGetItemSource, DictSubclassGetItemSource))
  1323. if isinstance(base_guard_manager, DictGuardManager):
  1324. assert self.manager_guards_on_keys(base_guard_manager_enum)
  1325. out = getitem_on_dict_manager(
  1326. source,
  1327. base_guard_manager,
  1328. base_example_value,
  1329. example_value,
  1330. guard_manager_enum,
  1331. )
  1332. else:
  1333. if isinstance(source.index, ConstDictKeySource):
  1334. raise RuntimeError(
  1335. "Expecting clean index here. Likely Dynamo forgot to mark"
  1336. " a dict as guard_on_key_order"
  1337. )
  1338. out = base_guard_manager.dict_getitem_manager(
  1339. key=source.index,
  1340. source=source_name,
  1341. example_value=example_value,
  1342. guard_manager_enum=guard_manager_enum,
  1343. )
  1344. elif istype(source, TensorPropertySource):
  1345. out = getattr(
  1346. base_guard_manager,
  1347. f"tensor_property_{source.prop.name.lower()}_manager",
  1348. )(
  1349. idx=source.idx,
  1350. source=source_name,
  1351. example_value=example_value,
  1352. guard_manager_enum=guard_manager_enum,
  1353. )
  1354. elif istype(source, IndexedSource):
  1355. assert base_guard_manager # to make mypy happy
  1356. out = base_guard_manager.indexed_manager(
  1357. idx=source.idx,
  1358. source=source_name,
  1359. example_value=example_value,
  1360. guard_manager_enum=guard_manager_enum,
  1361. )
  1362. elif istype(source, ListGetItemSource):
  1363. assert base_guard_manager # to make mypy happy
  1364. out = base_guard_manager.list_getitem_manager(
  1365. key=source.index,
  1366. source=source_name,
  1367. example_value=example_value,
  1368. guard_manager_enum=guard_manager_enum,
  1369. )
  1370. elif istype(source, GetItemSource):
  1371. assert base_guard_manager # to make mypy happy
  1372. assert not isinstance(
  1373. base_example_value, (dict, collections.OrderedDict)
  1374. ), "Use DictGetItemSource"
  1375. if isinstance(base_example_value, list) and not source.index_is_slice:
  1376. out = base_guard_manager.list_getitem_manager(
  1377. key=source.index,
  1378. source=source_name,
  1379. example_value=example_value,
  1380. guard_manager_enum=guard_manager_enum,
  1381. )
  1382. elif isinstance(base_example_value, tuple) and not source.index_is_slice:
  1383. out = base_guard_manager.tuple_getitem_manager(
  1384. key=source.index,
  1385. source=source_name,
  1386. example_value=example_value,
  1387. guard_manager_enum=guard_manager_enum,
  1388. )
  1389. else:
  1390. index = source.index
  1391. if source.index_is_slice:
  1392. index = source.unpack_slice()
  1393. out = base_guard_manager.getitem_manager(
  1394. key=index,
  1395. source=source_name,
  1396. example_value=example_value,
  1397. guard_manager_enum=guard_manager_enum,
  1398. )
  1399. elif istype(source, DefaultsSource):
  1400. assert base_guard_manager # to make mypy happy
  1401. assert base_source_name
  1402. assert callable(base_example_value)
  1403. if not source.is_kw:
  1404. out = base_guard_manager.func_defaults_manager(
  1405. source=base_source_name,
  1406. example_value=base_example_value.__defaults__,
  1407. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  1408. ).getitem_manager(
  1409. key=source.idx_key,
  1410. source=source_name,
  1411. example_value=example_value,
  1412. guard_manager_enum=guard_manager_enum,
  1413. )
  1414. else:
  1415. # kwdefauts is a dict, so use a DictGuardManager
  1416. kwdefaults = base_example_value.__kwdefaults__
  1417. assert base_source_name is not None
  1418. kw_source = base_source_name + ".__kwdefaults__"
  1419. # kwdefaults is a dict. No need to guard on dict order.
  1420. dict_mgr = base_guard_manager.func_kwdefaults_manager(
  1421. source=kw_source,
  1422. example_value=kwdefaults,
  1423. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  1424. )
  1425. assert not isinstance(dict_mgr, DictGuardManager)
  1426. out = dict_mgr.dict_getitem_manager(
  1427. key=source.idx_key,
  1428. source=source_name,
  1429. example_value=example_value,
  1430. guard_manager_enum=guard_manager_enum,
  1431. )
  1432. elif istype(source, NumpyTensorSource):
  1433. assert base_guard_manager # to make mypy happy
  1434. out = base_guard_manager.lambda_manager(
  1435. python_lambda=from_numpy,
  1436. source=source_name,
  1437. example_value=example_value,
  1438. guard_manager_enum=guard_manager_enum,
  1439. )
  1440. elif istype(source, SubclassAttrListSource):
  1441. assert base_guard_manager # to make mypy happy
  1442. out = base_guard_manager.lambda_manager(
  1443. python_lambda=lambda x: x.__tensor_flatten__()[0],
  1444. source=source_name,
  1445. example_value=example_value,
  1446. guard_manager_enum=guard_manager_enum,
  1447. )
  1448. elif istype(source, FlattenScriptObjectSource):
  1449. assert base_guard_manager # to make mypy happy
  1450. out = base_guard_manager.lambda_manager(
  1451. python_lambda=lambda x: x.__obj_flatten__(),
  1452. source=source_name,
  1453. example_value=example_value,
  1454. guard_manager_enum=guard_manager_enum,
  1455. )
  1456. elif istype(source, ScriptObjectQualifiedNameSource):
  1457. assert base_guard_manager # to make mypy happy
  1458. out = base_guard_manager.lambda_manager(
  1459. python_lambda=lambda x: x._type().qualified_name(),
  1460. source=source_name,
  1461. example_value=example_value,
  1462. guard_manager_enum=guard_manager_enum,
  1463. )
  1464. elif istype(source, AttrProxySource):
  1465. assert base_guard_manager # to make mypy happy
  1466. out = base_guard_manager.lambda_manager(
  1467. python_lambda=lambda x: x.get_base(),
  1468. source=source_name,
  1469. example_value=example_value,
  1470. guard_manager_enum=guard_manager_enum,
  1471. )
  1472. elif istype(source, CallMethodItemSource):
  1473. assert base_guard_manager # to make mypy happy
  1474. out = base_guard_manager.lambda_manager(
  1475. python_lambda=lambda x: x.item(),
  1476. source=source_name,
  1477. example_value=example_value,
  1478. guard_manager_enum=guard_manager_enum,
  1479. )
  1480. elif istype(source, FloatTensorSource):
  1481. assert base_guard_manager # to make mypy happy
  1482. out = base_guard_manager.lambda_manager(
  1483. python_lambda=lambda x: torch._as_tensor_fullprec(x),
  1484. source=source_name,
  1485. example_value=example_value,
  1486. guard_manager_enum=guard_manager_enum,
  1487. )
  1488. elif istype(source, TupleIteratorGetItemSource):
  1489. assert base_guard_manager # to make mypy happy
  1490. out = base_guard_manager.tuple_iterator_getitem_manager(
  1491. index=source.index,
  1492. source=source_name,
  1493. example_value=example_value,
  1494. guard_manager_enum=guard_manager_enum,
  1495. )
  1496. elif isinstance(source, ConstDictKeySource):
  1497. if not isinstance(base_guard_manager, DictGuardManager):
  1498. raise AssertionError(
  1499. "ConstDictKeySource can only work on DictGuardManager"
  1500. )
  1501. out = base_guard_manager.get_key_manager(
  1502. index=source.index,
  1503. source=source_name,
  1504. example_value=example_value,
  1505. guard_manager_enum=guard_manager_enum,
  1506. )
  1507. elif istype(source, NonSerializableSetGetItemSource):
  1508. assert base_guard_manager
  1509. out = base_guard_manager.set_getitem_manager(
  1510. index=source.index,
  1511. source=source_name,
  1512. example_value=example_value,
  1513. guard_manager_enum=guard_manager_enum,
  1514. )
  1515. elif istype(source, WeakRefCallSource):
  1516. assert base_guard_manager # to make mypy happy
  1517. out = base_guard_manager.weakref_call_manager(
  1518. source=source_name,
  1519. example_value=example_value,
  1520. guard_manager_enum=guard_manager_enum,
  1521. )
  1522. elif istype(source, CallFunctionNoArgsSource):
  1523. assert base_guard_manager # to make mypy happy
  1524. out = base_guard_manager.call_function_no_args_manager(
  1525. source=source_name,
  1526. example_value=example_value,
  1527. guard_manager_enum=guard_manager_enum,
  1528. )
  1529. elif istype(source, DataclassFieldsSource):
  1530. assert base_guard_manager
  1531. out = base_guard_manager.lambda_manager(
  1532. python_lambda=lambda x: dataclass_fields(x),
  1533. source=source_name,
  1534. example_value=example_value,
  1535. guard_manager_enum=guard_manager_enum,
  1536. )
  1537. elif istype(source, NamedTupleFieldsSource):
  1538. assert base_guard_manager
  1539. out = base_guard_manager.lambda_manager(
  1540. python_lambda=lambda x: x._fields,
  1541. source=source_name,
  1542. example_value=example_value,
  1543. guard_manager_enum=guard_manager_enum,
  1544. )
  1545. elif istype(source, CodeSource):
  1546. assert base_guard_manager # to make mypy happy
  1547. out = base_guard_manager.code_manager(
  1548. source=source_name,
  1549. example_value=example_value,
  1550. guard_manager_enum=guard_manager_enum,
  1551. )
  1552. elif istype(source, ClosureSource):
  1553. assert base_guard_manager # to make mypy happy
  1554. out = base_guard_manager.closure_manager(
  1555. source=source_name,
  1556. example_value=example_value,
  1557. guard_manager_enum=guard_manager_enum,
  1558. )
  1559. elif istype(source, DynamicScalarSource):
  1560. assert base_guard_manager
  1561. out = base_guard_manager.lambda_manager(
  1562. python_lambda=lambda x: int(x),
  1563. source=source_name,
  1564. example_value=example_value,
  1565. guard_manager_enum=guard_manager_enum,
  1566. )
  1567. else:
  1568. raise AssertionError(
  1569. f"missing guard manager builder {source} - {source.name}"
  1570. )
  1571. self._cached_guard_managers[source.name] = out
  1572. return out
  1573. def get_guard_manager(self, guard: Guard) -> GuardManager:
  1574. return self.get_guard_manager_from_source(guard.originating_source)
  1575. def add_python_lambda_leaf_guard_to_root(
  1576. self,
  1577. code_parts: list[str],
  1578. verbose_code_parts: list[str],
  1579. closure_vars: Optional[dict[str, object]] = None,
  1580. is_epilogue: bool = True,
  1581. ) -> None:
  1582. if closure_vars is None:
  1583. closure_vars = _get_closure_vars()
  1584. # Adds a lambda leaf guard to the root guard manager. It wraps the
  1585. # code_parts in a function object which is then passed on to the leaf
  1586. # guard.
  1587. make_guard_fn_args = ", ".join(closure_vars.keys())
  1588. _guard_body, pycode = build_guard_function(code_parts, make_guard_fn_args)
  1589. out: dict[str, Any] = {}
  1590. globals_for_guard_fn = {"G": self.scope["G"]}
  1591. guards_log.debug("Python shape guard function:\n%s", pycode)
  1592. exec(pycode, globals_for_guard_fn, out)
  1593. guard_fn = out["___make_guard_fn"](*closure_vars.values())
  1594. if is_epilogue:
  1595. # Epilogue guards are run after all the other guards have finished.
  1596. # If epilogue guards contain a getattr or getitem access, one of the
  1597. # other guards would fail preventing the epilogue guards to run.
  1598. self.guard_manager.root.add_epilogue_lambda_guard(
  1599. guard_fn, verbose_code_parts
  1600. )
  1601. else:
  1602. self.guard_manager.root.add_lambda_guard(guard_fn, verbose_code_parts)
  1603. # Warning: use this with care! This lets you access what the current
  1604. # value of the value you are guarding on is. You probably don't want
  1605. # to actually durably save this value though (because it's specific
  1606. # to this frame!) Instead, you should be reading out some property
  1607. # (like its type) which is what you permanently install into the
  1608. # guard code.
  1609. def get(
  1610. self,
  1611. guard_or_source: Guard | Source,
  1612. closure_vars: Optional[dict[str, Any]] = None,
  1613. ) -> Any:
  1614. name = guard_or_source.name
  1615. if isinstance(guard_or_source, Source):
  1616. src = guard_or_source
  1617. else:
  1618. src = guard_or_source.originating_source
  1619. if self.source_get_cache:
  1620. if name in self.source_get_cache:
  1621. return self.source_get_cache[name]
  1622. if closure_vars is None:
  1623. closure_vars = _get_closure_vars()
  1624. ret = src.get_value(self.scope, closure_vars, self.src_get_value_cache)
  1625. if self.save_guards and ".__closure__" in name:
  1626. self.source_get_cache[name] = ret
  1627. return ret
  1628. # Registers the usage of the source name referenced by the
  1629. # string (or stored in the Guard) as being guarded upon. It's important
  1630. # to call this before generating some code that makes use of 'guard',
  1631. # because without this call, we won't actually bind the variable
  1632. # you reference in the actual guard closure (oops!)
  1633. def arg_ref(self, guard: Union[str, Guard]) -> str:
  1634. name: str
  1635. if isinstance(guard, str):
  1636. name = guard
  1637. else:
  1638. name = guard.name
  1639. base = strip_function_call(name)
  1640. if base not in self.argnames:
  1641. is_valid = torch._C._dynamo.is_valid_var_name(base)
  1642. if is_valid:
  1643. if is_valid == 2:
  1644. log.warning("invalid var name: %s", guard)
  1645. self.argnames.append(base)
  1646. return name
  1647. def _guard_on_attribute(
  1648. self,
  1649. guard: Guard,
  1650. attr_name: str,
  1651. guard_fn: Callable[[GuardBuilderBase, Guard], Any],
  1652. ) -> None:
  1653. if attr_name == "__code__":
  1654. attr_source = CodeSource(guard.originating_source)
  1655. else:
  1656. attr_source = AttrSource(guard.originating_source, attr_name) # type: ignore[assignment]
  1657. # Copy the stack info
  1658. new_guard = Guard(
  1659. attr_source, guard_fn, stack=guard.stack, user_stack=guard.user_stack
  1660. )
  1661. new_guard.create(self)
  1662. # Note: the order of the guards in this file matters since we sort guards on the same object by lineno
  1663. def HASATTR(self, guard: Guard) -> None:
  1664. source = guard.originating_source
  1665. if isinstance(source, NNModuleSource):
  1666. source = source.base
  1667. if isinstance(source, CodeSource):
  1668. # No need to guard that a function has a __code__ attribute
  1669. return
  1670. assert isinstance(source, AttrSource), f"invalid source {guard.name}"
  1671. base_source = source.base
  1672. base = base_source.name
  1673. attr = source.member
  1674. ref = self.arg_ref(base)
  1675. val = hasattr(self.get(base_source), attr)
  1676. code = None
  1677. if val:
  1678. code = f"hasattr({ref}, {attr!r})"
  1679. else:
  1680. code = f"not hasattr({ref}, {attr!r})"
  1681. if code in self.already_added_code_parts:
  1682. return
  1683. self._set_guard_export_info(
  1684. guard, [code], provided_guarded_object=self.get(base_source)
  1685. )
  1686. base_manager = self.get_guard_manager_from_source(base_source)
  1687. if val:
  1688. # Just install a getattr manager. GetAttrGuardAccessor itself
  1689. # acts as hasattr guard.
  1690. example_value = self.get(source)
  1691. base_example_value = self.get(base_source)
  1692. guard_manager_enum = self.get_guard_manager_type(source, example_value)
  1693. # if the base value is nn.Module, check if we can speedup the
  1694. # guard by going through __dict__ attrs.
  1695. if should_optimize_getattr_on_nn_module(base_example_value):
  1696. self.getattr_on_nn_module(
  1697. source,
  1698. base_manager,
  1699. base_example_value,
  1700. example_value,
  1701. base,
  1702. source.name,
  1703. guard_manager_enum,
  1704. )
  1705. else:
  1706. base_manager.getattr_manager(
  1707. attr=attr,
  1708. source=guard.name,
  1709. example_value=example_value,
  1710. guard_manager_enum=guard_manager_enum,
  1711. )
  1712. else:
  1713. base_manager.add_no_hasattr_guard(attr, get_verbose_code_parts(code, guard))
  1714. self.already_added_code_parts.add(code)
  1715. def NOT_PRESENT_IN_GENERIC_DICT(
  1716. self, guard: Guard, attr: Optional[Any] = None
  1717. ) -> None:
  1718. assert attr is not None
  1719. ref = self.arg_ref(guard)
  1720. val = self.get(guard)
  1721. base_manager = self.get_guard_manager(guard)
  1722. code = f"not ___dict_contains({attr!r}, {ref}.__dict__)"
  1723. if code in self.already_added_code_parts:
  1724. return
  1725. mod_dict_source = f"{guard.name}.__dict__"
  1726. mod_generic_dict_manager = base_manager.get_generic_dict_manager(
  1727. source=mod_dict_source,
  1728. example_value=self._get_generic_dict_manager_example_value(val.__dict__),
  1729. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  1730. )
  1731. mod_generic_dict_manager.add_dict_contains_guard(
  1732. False, attr, get_verbose_code_parts(code, guard)
  1733. )
  1734. self.already_added_code_parts.add(code)
  1735. def TYPE_MATCH(self, guard: Guard) -> None:
  1736. # ___check_type_id is same as `id(type(x)) == y`
  1737. value = self.get(guard)
  1738. if isinstance(value, torch._subclasses.FakeTensor) and value.pytype:
  1739. t = value.pytype
  1740. else:
  1741. t = type(value)
  1742. if t.__qualname__ != t.__name__:
  1743. # Type match guards must be local scope, this is
  1744. # raised in self.serialize_guards
  1745. guard._unserializable = True
  1746. obj_id = self.id_ref(t, f"type({guard.name})")
  1747. type_repr = repr(t)
  1748. code = f"___check_type_id({self.arg_ref(guard)}, {obj_id}), type={type_repr}"
  1749. self._set_guard_export_info(guard, [code])
  1750. self.get_guard_manager(guard).add_type_match_guard(
  1751. obj_id, get_verbose_code_parts(code, guard)
  1752. )
  1753. def DICT_VERSION(self, guard: Guard) -> None:
  1754. # ___check_dict_version is same as `dict_version(x) == y`
  1755. ref = self.arg_ref(guard)
  1756. val = self.get(guard)
  1757. version = dict_version(self.get(guard))
  1758. code = f"___dict_version({ref}) == {version}"
  1759. self._set_guard_export_info(guard, [code])
  1760. # TODO(anijain2305) - Delete this when DictGuardManager uses tags
  1761. # for dicts.
  1762. self.get_guard_manager(guard).add_dict_version_guard(
  1763. val, get_verbose_code_parts(code, guard)
  1764. )
  1765. def DICT_CONTAINS(self, guard: Guard, key: str, invert: bool) -> None:
  1766. dict_ref = self.arg_ref(guard)
  1767. maybe_not = "not " if invert else ""
  1768. code = f"{maybe_not}___dict_contains({key!r}, {dict_ref})"
  1769. if code in self.already_added_code_parts:
  1770. return
  1771. self._set_guard_export_info(guard, [code])
  1772. self.get_guard_manager(guard).add_dict_contains_guard(
  1773. not invert, key, get_verbose_code_parts(code, guard)
  1774. )
  1775. self.already_added_code_parts.add(code)
  1776. def SET_CONTAINS(self, guard: Guard, key: Any, invert: bool) -> None:
  1777. set_ref = self.arg_ref(guard)
  1778. item = key
  1779. contains = not invert # install_dict_contains_guard inverts "contains"
  1780. code = f"set.__contains__({set_ref}, {item!r})"
  1781. if code in self.already_added_code_parts:
  1782. return
  1783. self._set_guard_export_info(guard, [code])
  1784. self.get_guard_manager(guard).add_set_contains_guard(
  1785. contains, item, get_verbose_code_parts(code, guard)
  1786. )
  1787. self.already_added_code_parts.add(code)
  1788. def BOOL_MATCH(self, guard: Guard) -> None:
  1789. # checks val == True or val == False
  1790. ref = self.arg_ref(guard)
  1791. val = self.get(guard)
  1792. assert istype(val, bool)
  1793. code = [f"{ref} == {val!r}"]
  1794. self._set_guard_export_info(guard, code)
  1795. if val:
  1796. self.get_guard_manager(guard).add_true_match_guard(
  1797. get_verbose_code_parts(code, guard)
  1798. )
  1799. else:
  1800. self.get_guard_manager(guard).add_false_match_guard(
  1801. get_verbose_code_parts(code, guard)
  1802. )
  1803. def NONE_MATCH(self, guard: Guard) -> None:
  1804. # checks `val is None`
  1805. ref = self.arg_ref(guard)
  1806. val = self.get(guard)
  1807. assert val is None
  1808. code = [f"{ref} is None"]
  1809. self._set_guard_export_info(guard, code)
  1810. self.get_guard_manager(guard).add_none_match_guard(
  1811. get_verbose_code_parts(code, guard)
  1812. )
  1813. def ID_MATCH(self, guard: Guard, recompile_hint: Optional[str] = None) -> None:
  1814. # TODO - Run a CI with the following uncommented to find the remaining places
  1815. # val = self.get(guard)
  1816. # if inspect.isclass(val):
  1817. # raise AssertionError(f"{guard.name} is a class, use CLASS_MATCH guard")
  1818. # if inspect.ismodule(val):
  1819. # raise AssertionError(f"{guard.name} is a module, use MODULE_MATCH guard")
  1820. return self.id_match_unchecked(guard, recompile_hint)
  1821. def id_match_unchecked(
  1822. self, guard: Guard, recompile_hint: Optional[str] = None
  1823. ) -> None:
  1824. # ___check_obj_id is same as `id(x) == y`
  1825. if isinstance(guard.originating_source, TypeSource):
  1826. # optional optimization to produce cleaner/faster guard code
  1827. return self.TYPE_MATCH(
  1828. Guard(guard.originating_source.base, GuardBuilder.TYPE_MATCH) # type: ignore[arg-type]
  1829. )
  1830. ref = self.arg_ref(guard)
  1831. val = self.get(guard)
  1832. id_val = self.id_ref(val, guard.name)
  1833. try:
  1834. type_repr = repr(val)
  1835. except Exception:
  1836. # During deepcopy reconstruction or other state transitions,
  1837. # objects may be in an incomplete state where repr() fails
  1838. type_repr = f"<{type(val).__name__}>"
  1839. code = f"___check_obj_id({ref}, {id_val}), type={type_repr}"
  1840. self._set_guard_export_info(guard, [code], provided_func_name="ID_MATCH")
  1841. self.get_guard_manager(guard).add_id_match_guard(
  1842. id_val, get_verbose_code_parts(code, guard, recompile_hint)
  1843. )
  1844. # Keep track of ID_MATCH'd objects. This will be used to modify the
  1845. # cache size logic
  1846. if isinstance(guard.originating_source, LocalSource):
  1847. # TODO(anijain2305) - This is currently restricted to nn.Module objects
  1848. # because many other ID_MATCH'd objects fail - like DeviceMesh.
  1849. # Increase the scope of ID_MATCH'd objects.
  1850. if isinstance(val, torch.nn.Module):
  1851. local_name = guard.originating_source.local_name
  1852. weak_id = self.lookup_weakrefs(val)
  1853. if weak_id is not None:
  1854. self.id_matched_objs[local_name] = weak_id
  1855. def NOT_NONE_MATCH(self, guard: Guard, value: Optional[Any] = None) -> None:
  1856. ref = self.arg_ref(guard)
  1857. val = self.get(guard)
  1858. assert isinstance(val, torch.Tensor)
  1859. code = f"{ref} is not None"
  1860. self._set_guard_export_info(guard, [code])
  1861. self.get_guard_manager(guard).add_not_none_guard(
  1862. get_verbose_code_parts(code, guard)
  1863. )
  1864. def DISPATCH_KEY_SET_MATCH(self, guard: Guard) -> None:
  1865. ref = self.arg_ref(guard)
  1866. val = self.get(guard)
  1867. assert isinstance(val, torch._C.DispatchKeySet)
  1868. code_parts = f"{ref}.raw_repr() == {val!r}.raw_repr()"
  1869. self.get_guard_manager(guard).add_dispatch_key_set_guard(
  1870. val, get_verbose_code_parts(code_parts, guard)
  1871. )
  1872. def DUAL_LEVEL(self, guard: Guard) -> None:
  1873. # Invalidate dual level if current dual level is different than the one
  1874. # in the fx graph
  1875. assert self.check_fn_manager.output_graph is not None
  1876. dual_level = self.check_fn_manager.output_graph.dual_level
  1877. code = [f"torch.autograd.forward_ad._current_level == {dual_level}"]
  1878. self._set_guard_export_info(guard, code)
  1879. self.guard_manager.root.add_dual_level_match_guard(
  1880. dual_level, get_verbose_code_parts(code, guard)
  1881. )
  1882. def FUNCTORCH_STACK_MATCH(self, guard: Guard) -> None:
  1883. # Invalidate functorch code if current level is different than
  1884. # the one when FX graph was generated
  1885. assert self.check_fn_manager.output_graph is not None
  1886. cis = self.check_fn_manager.output_graph.functorch_layers
  1887. states = [ci.get_state() for ci in cis]
  1888. code = [f"torch._functorch.pyfunctorch.compare_functorch_state({states})"]
  1889. self._set_guard_export_info(guard, code)
  1890. # TODO(anijain2305) - Consider this moving this guard to C++
  1891. compare_fn = torch._functorch.pyfunctorch.compare_functorch_state
  1892. def fn(x: Any) -> bool:
  1893. return compare_fn(states)
  1894. self.guard_manager.root.add_lambda_guard(
  1895. fn, get_verbose_code_parts(code, guard)
  1896. )
  1897. def AUTOGRAD_SAVED_TENSORS_HOOKS(self, guard: Guard) -> None:
  1898. get_hooks = torch._functorch._aot_autograd.utils.top_saved_tensors_hooks
  1899. are_inline_hooks = (
  1900. torch._functorch._aot_autograd.utils.saved_tensors_hooks_are_inlineable
  1901. )
  1902. def hooks_ids_fn(
  1903. hooks: tuple[Callable[[torch.Tensor], Any], Callable[[Any], torch.Tensor]],
  1904. ) -> Optional[tuple[int, ...]]:
  1905. if not are_inline_hooks(hooks):
  1906. return None
  1907. return tuple(map(id, hooks))
  1908. guard_hooks_ids = hooks_ids_fn(get_hooks())
  1909. code = [
  1910. f"torch._functorch.aot_autograd.utils.top_saved_tensors_hooks ids == {guard_hooks_ids}"
  1911. ]
  1912. self._set_guard_export_info(guard, code)
  1913. def fn(x: Any) -> bool:
  1914. return guard_hooks_ids == hooks_ids_fn(get_hooks())
  1915. self.guard_manager.root.add_lambda_guard(
  1916. fn, get_verbose_code_parts(code, guard)
  1917. )
  1918. def TENSOR_SUBCLASS_METADATA_MATCH(self, guard: Guard) -> None:
  1919. value = self.get(guard)
  1920. original_metadata = deepcopy(self.get(guard).__tensor_flatten__()[1])
  1921. if hasattr(value, "__metadata_guard__"):
  1922. verify_guard_fn_signature(value)
  1923. cls = type(value)
  1924. def metadata_checker(x: Any) -> bool:
  1925. return cls.__metadata_guard__(
  1926. original_metadata, x.__tensor_flatten__()[1]
  1927. )
  1928. else:
  1929. def metadata_checker(x: Any) -> bool:
  1930. return x.__tensor_flatten__()[1] == original_metadata
  1931. global_name = f"___check_metadata_{id(metadata_checker)}_c{CompileContext.current_compile_id()}"
  1932. self.get_guard_manager(guard).add_lambda_guard(
  1933. metadata_checker, get_verbose_code_parts(global_name, guard)
  1934. )
  1935. def DTENSOR_SPEC_MATCH(self, guard: Guard) -> None:
  1936. # Copied from DTensor __metadata_guard__
  1937. # TODO - Consider moving this to C++ if stable
  1938. value = deepcopy(self.get(guard))
  1939. def guard_fn(x: Any) -> bool:
  1940. return x._check_equals(value, skip_shapes=True)
  1941. code = f"__dtensor_spec_{id(guard_fn)}"
  1942. self.get_guard_manager(guard).add_lambda_guard(
  1943. guard_fn, get_verbose_code_parts(code, guard)
  1944. )
  1945. def EQUALS_MATCH(self, guard: Guard, recompile_hint: Optional[str] = None) -> None:
  1946. ref = self.arg_ref(guard)
  1947. val = self.get(guard)
  1948. if np:
  1949. np_types: tuple[type[Any], ...] = (
  1950. np.int8,
  1951. np.int16,
  1952. np.int32,
  1953. np.int64,
  1954. np.uint8,
  1955. np.uint16,
  1956. np.uint32,
  1957. np.uint64,
  1958. np.float16,
  1959. np.float32,
  1960. np.float64,
  1961. )
  1962. else:
  1963. np_types = ()
  1964. ok_mutable_types = (list, set)
  1965. ok_types = tuple(
  1966. common_constant_types
  1967. | {
  1968. type,
  1969. tuple,
  1970. frozenset,
  1971. slice,
  1972. range,
  1973. dict_keys,
  1974. torch.Size,
  1975. torch.Stream,
  1976. torch.cuda.streams.Stream,
  1977. *np_types,
  1978. *ok_mutable_types,
  1979. }
  1980. )
  1981. if torch.distributed.is_available():
  1982. from torch.distributed.device_mesh import DeviceMesh
  1983. from torch.distributed.tensor.placement_types import (
  1984. _StridedShard,
  1985. Partial,
  1986. Replicate,
  1987. Shard,
  1988. )
  1989. ok_types = ok_types + (
  1990. Shard,
  1991. Replicate,
  1992. Partial,
  1993. DeviceMesh,
  1994. _StridedShard,
  1995. )
  1996. from torch.export.dynamic_shapes import _IntWrapper
  1997. ok_types = ok_types + (_IntWrapper,)
  1998. import torch.utils._pytree as pytree
  1999. assert (
  2000. isinstance(val, ok_types)
  2001. or pytree.is_constant_class(type(val))
  2002. or is_opaque_value_type(type(val))
  2003. ), f"Unexpected type {type(val)}"
  2004. # Special case for nan because float("nan") == float("nan") evaluates to False
  2005. if istype(val, float) and math.isnan(val):
  2006. code = [f"(type({ref}) is float and __math_isnan({ref}))"]
  2007. self._set_guard_export_info(guard, code)
  2008. self.get_guard_manager(guard).add_float_is_nan_guard(
  2009. get_verbose_code_parts(code, guard),
  2010. )
  2011. return
  2012. # Python math library doesn't support complex nan, so we need to use numpy
  2013. # pyrefly: ignore [missing-attribute]
  2014. if istype(val, complex) and np.isnan(val):
  2015. code = [f"(type({ref}) is complex and __numpy_isnan({ref}))"]
  2016. self._set_guard_export_info(guard, code)
  2017. self.get_guard_manager(guard).add_complex_is_nan_guard(
  2018. get_verbose_code_parts(code, guard),
  2019. )
  2020. return
  2021. # Construct a debug string to put into the c++ equals match guard.
  2022. code = [f"{ref} == {val!r}"]
  2023. if istype(val, ok_mutable_types):
  2024. # C++ guards perform a pointer equality check to speedup guards, but the assumption is that the object
  2025. # is immutable. For a few corner cases like sets and lists, we make a deepcopy to purposefully fail the
  2026. # pointer equality check.
  2027. val = deepcopy(val)
  2028. verbose_code_parts = get_verbose_code_parts(code, guard)
  2029. if recompile_hint:
  2030. verbose_code_parts = [
  2031. f"{part} (HINT: {recompile_hint})" for part in verbose_code_parts
  2032. ]
  2033. self.get_guard_manager(guard).add_equals_match_guard(val, verbose_code_parts)
  2034. self._set_guard_export_info(guard, code)
  2035. return
  2036. def CONSTANT_MATCH(self, guard: Guard) -> None:
  2037. val = self.get(guard)
  2038. if istype(val, bool):
  2039. self.BOOL_MATCH(guard)
  2040. elif val is None:
  2041. self.NONE_MATCH(guard)
  2042. elif istype(val, types.CodeType):
  2043. self.ID_MATCH(guard)
  2044. else:
  2045. self.EQUALS_MATCH(guard)
  2046. def NN_MODULE(self, guard: Guard) -> None:
  2047. # don't support this in serialization because it uses unsupported ID_MATCH
  2048. self.ID_MATCH(guard, "[inline-inbuilt-nn-modules-candidate]")
  2049. val = self.get(guard)
  2050. if hasattr(val, "training"):
  2051. assert istype(val.training, bool)
  2052. if not self.guard_nn_modules:
  2053. # If guard_nn_modules is true, we will guard on the right set of guards
  2054. self._guard_on_attribute(guard, "training", GuardBuilder.CONSTANT_MATCH) # type: ignore[arg-type]
  2055. else:
  2056. exc.unimplemented(
  2057. gb_type="Attempted to guard on uninitialized nn.Module",
  2058. context="",
  2059. explanation="Attempted to setup an NN_MODULE guard on uninitialized "
  2060. f"nn.Module subclass `{type(val)}`.",
  2061. hints=[
  2062. "Ensure the `nn.Module` subclass instance has called `super().__init__()`.",
  2063. ],
  2064. )
  2065. def FUNCTION_MATCH(self, guard: Guard) -> None:
  2066. """things like torch.add and user defined functions"""
  2067. # don't support this in serialization because it uses unsupported ID_MATCH
  2068. return self.ID_MATCH(guard)
  2069. def CLASS_MATCH(self, guard: Guard) -> None:
  2070. """Equals ID_MATCH on classes - better readability than directly calling ID_MATCH"""
  2071. val = self.get(guard)
  2072. if not inspect.isclass(val):
  2073. raise AssertionError(
  2074. f"{guard.name} is not a class, but CLASS_MATCH is used"
  2075. )
  2076. self.id_match_unchecked(guard)
  2077. def MODULE_MATCH(self, guard: Guard) -> None:
  2078. """Equals ID_MATCH on modules - better readability than directly calling ID_MATCH"""
  2079. val = self.get(guard)
  2080. if not inspect.ismodule(val):
  2081. raise AssertionError(
  2082. f"{guard.name} is not a module, but MODULE_MATCH is used"
  2083. )
  2084. self.id_match_unchecked(guard)
  2085. def CLOSURE_MATCH(self, guard: Guard) -> None:
  2086. """matches a closure by __code__ id."""
  2087. # don't support this in serialization because it uses unsupported FUNCTION_MATCH
  2088. val = self.get(guard)
  2089. # Strictly only want user-defined functions
  2090. if type(val) is types.FunctionType and hasattr(val, "__code__"):
  2091. self._guard_on_attribute(guard, "__code__", GuardBuilder.HASATTR) # type: ignore[arg-type]
  2092. self._guard_on_attribute(guard, "__code__", GuardBuilder.CONSTANT_MATCH) # type: ignore[arg-type]
  2093. else:
  2094. self.FUNCTION_MATCH(guard)
  2095. def BUILTIN_MATCH(self, guard: Guard) -> None:
  2096. if self.save_guards:
  2097. # Record which builtin variables are used for pruning later.
  2098. if isinstance(guard.originating_source, DictGetItemSource):
  2099. self.check_fn_manager.used_builtin_vars.add(
  2100. guard.originating_source.index
  2101. )
  2102. return self.id_match_unchecked(guard)
  2103. def SEQUENCE_LENGTH(self, guard: Guard) -> None:
  2104. # This guard is used to check length of PySequence objects like list,
  2105. # tuple, collections.deque etc
  2106. ref = self.arg_ref(guard)
  2107. value = self.get(guard)
  2108. if not isinstance(value, dict):
  2109. # C++ DICT_LENGTH checks for type
  2110. self.TYPE_MATCH(guard)
  2111. code = []
  2112. if len(value) == 0:
  2113. code.append(f"not {ref}")
  2114. else:
  2115. code.append(f"len({ref}) == {len(value)}")
  2116. self._set_guard_export_info(guard, code)
  2117. if isinstance(value, dict):
  2118. self.get_guard_manager(guard).add_dict_length_check_guard(
  2119. len(value), get_verbose_code_parts(code, guard)
  2120. )
  2121. else:
  2122. self.get_guard_manager(guard).add_length_check_guard(
  2123. len(value), get_verbose_code_parts(code, guard)
  2124. )
  2125. def TUPLE_ITERATOR_LEN(self, guard: Guard) -> None:
  2126. ref = self.arg_ref(guard)
  2127. value = self.get(guard)
  2128. t = type(value)
  2129. code = []
  2130. code.append(f"___tuple_iterator_len({ref}) == {tuple_iterator_len(value)}")
  2131. self._set_guard_export_info(guard, code)
  2132. t = type(value)
  2133. obj_id = self.id_ref(t, f"type({guard.name})")
  2134. self.get_guard_manager(guard).add_tuple_iterator_length_guard(
  2135. tuple_iterator_len(value), obj_id, get_verbose_code_parts(code, guard)
  2136. )
  2137. def RANGE_ITERATOR_MATCH(self, guard: Guard) -> None:
  2138. ref = self.arg_ref(guard)
  2139. value = self.get(guard)
  2140. t = type(value)
  2141. code = []
  2142. normalized_range_iter = normalize_range_iter(value)
  2143. code.append(f"___normalize_range_iter({ref}) == {normalized_range_iter}")
  2144. self._set_guard_export_info(guard, code)
  2145. t = type(value)
  2146. obj_id = self.id_ref(t, f"type({guard.name})")
  2147. start, stop, step = normalized_range_iter
  2148. self.get_guard_manager(guard).add_range_iterator_match_guard(
  2149. start, stop, step, obj_id, get_verbose_code_parts(code, guard)
  2150. )
  2151. # TODO(voz): Deduplicate w/ AOTAutograd dupe input guards
  2152. def DUPLICATE_INPUT(self, guard: Guard, source_b: Source) -> None:
  2153. if is_from_skip_guard_source(
  2154. guard.originating_source
  2155. ) or is_from_skip_guard_source(source_b):
  2156. return
  2157. if self.save_guards:
  2158. if name := get_local_source_name(source_b):
  2159. self.check_fn_manager.additional_used_local_vars.add(name)
  2160. if name := get_global_source_name(source_b):
  2161. self.check_fn_manager.additional_used_global_vars.add(name)
  2162. ref_a = self.arg_ref(guard)
  2163. ref_b = self.arg_ref(source_b.name)
  2164. if is_from_optimizer_source(
  2165. guard.originating_source
  2166. ) or is_from_optimizer_source(source_b):
  2167. return
  2168. # Check that the guard has not been inserted already
  2169. key = (ref_a, ref_b)
  2170. if key in self._cached_duplicate_input_guards:
  2171. return
  2172. self._cached_duplicate_input_guards.add((ref_a, ref_b))
  2173. self._cached_duplicate_input_guards.add((ref_b, ref_a))
  2174. code = [f"{ref_b} is {ref_a}"]
  2175. self._set_guard_export_info(guard, code)
  2176. if config.use_lamba_guard_for_object_aliasing:
  2177. # Save the code part so that we can install a lambda guard at the
  2178. # end. Read the Note - On Lambda guarding of object aliasing - to
  2179. # get more information.
  2180. code_part = code[0]
  2181. verbose_code_part = get_verbose_code_parts(code_part, guard)[0]
  2182. self.object_aliasing_guard_codes.append((code_part, verbose_code_part))
  2183. else:
  2184. install_object_aliasing_guard(
  2185. self.get_guard_manager(guard),
  2186. self.get_guard_manager_from_source(source_b),
  2187. get_verbose_code_parts(code, guard),
  2188. )
  2189. def WEAKREF_ALIVE(self, guard: Guard) -> None:
  2190. code = [f"{self.arg_ref(guard)} is not None"]
  2191. self._set_guard_export_info(guard, code)
  2192. self.get_guard_manager(guard).add_not_none_guard(
  2193. get_verbose_code_parts(code, guard)
  2194. )
  2195. def MAPPING_KEYS_CHECK(self, guard: Guard) -> None:
  2196. """Guard on the key order of types.MappingProxyType object"""
  2197. ref = self.arg_ref(guard)
  2198. value = self.get(guard)
  2199. code = []
  2200. code.append(f"list({ref}.keys()) == {list(value.keys())}")
  2201. self._set_guard_export_info(guard, code)
  2202. self.get_guard_manager(guard).add_mapping_keys_guard(value, code)
  2203. def DICT_KEYS_MATCH(self, guard: Guard) -> None:
  2204. """Insert guard to check that the keys of a dict are same"""
  2205. ref = self.arg_ref(guard)
  2206. value = self.get(guard)
  2207. if value is torch.utils._pytree.SUPPORTED_NODES:
  2208. # For SUPPORTED_NODES, we can guard on the dictionary version (PEP509).
  2209. self.DICT_VERSION(guard)
  2210. return
  2211. self.SEQUENCE_LENGTH(guard)
  2212. code = []
  2213. # Ensure that we call dict.keys and not value.keys (which can call
  2214. # overridden keys method). In the C++ guards, we relied on PyDict_Next
  2215. # to traverse the dictionary, which uses the internal data structure and
  2216. # does not call the overridden keys method.
  2217. code.append(f"list(dict.keys({ref})) == {list(builtin_dict_keys(value))!r}")
  2218. self._set_guard_export_info(guard, code)
  2219. if self.requires_key_order_guarding(guard.originating_source):
  2220. self.guard_on_dict_keys_and_order(value, guard)
  2221. else:
  2222. self.guard_on_dict_keys_and_ignore_order(value, guard)
  2223. def EMPTY_NN_MODULE_HOOKS_DICT(self, guard: Guard) -> None:
  2224. """Special guard to skip guards on empty hooks. This is controlled by skip_nnmodule_hook_guards"""
  2225. if config.skip_nnmodule_hook_guards:
  2226. # This is unsafe if you add/remove a hook on nn module variable
  2227. return
  2228. self.SEQUENCE_LENGTH(guard)
  2229. def GRAD_MODE(self, guard: Guard) -> None:
  2230. pass # we always guard on this via GlobalStateGuard()
  2231. def DETERMINISTIC_ALGORITHMS(self, guard: Guard) -> None:
  2232. pass # we always guard on this via GlobalStateGuard()
  2233. def FSDP_TRAINING_STATE(self, guard: Guard) -> None:
  2234. pass # we always guard on this via GlobalStateGuard()
  2235. def GLOBAL_STATE(self, guard: Guard) -> None:
  2236. output_graph = self.check_fn_manager.output_graph
  2237. assert output_graph is not None
  2238. global_state = output_graph.global_state_guard
  2239. self.check_fn_manager.global_state = global_state
  2240. self.guard_manager.root.add_global_state_guard(
  2241. global_state, ["___check_global_state()"]
  2242. )
  2243. def TORCH_FUNCTION_STATE(self, guard: Guard) -> None:
  2244. assert self.check_fn_manager.torch_function_mode_stack is not None
  2245. self.check_fn_manager.torch_function_mode_stack_check_fn = (
  2246. make_torch_function_mode_stack_guard(
  2247. self.check_fn_manager.torch_function_mode_stack
  2248. )
  2249. )
  2250. self.guard_manager.root.add_torch_function_mode_stack_guard(
  2251. self.check_fn_manager.torch_function_mode_stack,
  2252. ["___check_torch_function_mode_stack()"],
  2253. )
  2254. def DEFAULT_DEVICE(self, guard: Guard) -> None:
  2255. """Guard on CURRENT_DEVICE per torch.utils._device"""
  2256. assert guard.source is GuardSource.GLOBAL
  2257. assert self.check_fn_manager.output_graph is not None
  2258. code = [
  2259. f"utils_device.CURRENT_DEVICE == {self.check_fn_manager.output_graph.current_device!r}"
  2260. ]
  2261. self._set_guard_export_info(guard, code)
  2262. self.get_guard_manager(guard).add_default_device_guard(
  2263. get_verbose_code_parts(code, guard)
  2264. )
  2265. def SHAPE_ENV(self, guard: Guard) -> None:
  2266. from torch._dynamo.output_graph import OutputGraphCommon
  2267. assert guard.name == ""
  2268. output_graph = self.check_fn_manager.output_graph
  2269. assert output_graph is not None
  2270. if self.check_fn_manager.shape_code_parts is not None:
  2271. shape_code_parts = self.check_fn_manager.shape_code_parts
  2272. python_code_parts = shape_code_parts.python_code_parts
  2273. verbose_code_parts = shape_code_parts.verbose_code_parts
  2274. if shape_code_parts.cpp_code_parts is not None:
  2275. cpp_code_parts = shape_code_parts.cpp_code_parts
  2276. python_fallback = shape_code_parts.python_fallback
  2277. else:
  2278. # Let's handle ShapeEnv guards. To do this, we will resolve
  2279. # shape variables to sources from tracked_fakes. This must happen after
  2280. # tensor checks.
  2281. # NB: self.output_graph can be None in the debug_nops tests
  2282. assert isinstance(output_graph, OutputGraphCommon)
  2283. assert output_graph.shape_env is not None
  2284. fs = output_graph.shape_env.tracked_fakes or []
  2285. input_contexts = [a.symbolic_context for a in fs]
  2286. def get_sources(t_id: int, dim: int) -> list[Source]:
  2287. # Looks up base sources mapped to a tensor id and uses them to create
  2288. # sources for the corresponding tensor dimension.
  2289. return [
  2290. TensorPropertySource(source, TensorProperty.SIZE, dim)
  2291. # pyrefly: ignore [missing-attribute]
  2292. for source in output_graph.tracked_fakes_id_to_source[t_id]
  2293. ]
  2294. if output_graph.export_constraints:
  2295. names: dict[str, tuple[int, int]] = {}
  2296. source_pairs: list[tuple[Source, Source]] = []
  2297. derived_equalities: list[ # type: ignore[type-arg]
  2298. tuple[Source, Union[Source, Symbol], Callable]
  2299. ] = []
  2300. phantom_symbols: dict[str, Symbol] = {}
  2301. relaxed_sources: set[Source] = set()
  2302. for constraint in output_graph.export_constraints: # type: ignore[attr-defined]
  2303. if constraint.t_id in output_graph.tracked_fakes_id_to_source:
  2304. torch.export.dynamic_shapes._process_equalities(
  2305. constraint,
  2306. get_sources,
  2307. output_graph.shape_env,
  2308. names,
  2309. source_pairs,
  2310. derived_equalities,
  2311. phantom_symbols,
  2312. relaxed_sources,
  2313. )
  2314. else:
  2315. log.warning("Untracked tensor used in export constraints")
  2316. equalities_inputs = EqualityConstraint(
  2317. source_pairs=source_pairs,
  2318. derived_equalities=derived_equalities,
  2319. phantom_symbols=list(phantom_symbols.values()),
  2320. relaxed_sources=relaxed_sources,
  2321. warn_only=False,
  2322. )
  2323. else:
  2324. equalities_inputs = None
  2325. def _get_code_parts(langs: tuple[str, ...]) -> list[_ShapeGuardsHelper]:
  2326. # pyrefly: ignore [missing-attribute]
  2327. return output_graph.shape_env.produce_guards_verbose(
  2328. [a.fake for a in fs], # type: ignore[misc]
  2329. [a.source for a in fs],
  2330. input_contexts=input_contexts, # type: ignore[arg-type]
  2331. equalities_inputs=equalities_inputs,
  2332. source_ref=self.source_ref,
  2333. # Export keeps static.
  2334. # pyrefly: ignore [missing-attribute]
  2335. ignore_static=(not output_graph.export),
  2336. langs=langs,
  2337. )
  2338. if config.enable_cpp_symbolic_shape_guards:
  2339. try:
  2340. # For exporting we need the python code parts
  2341. python_code_parts, verbose_code_parts, cpp_code_parts = (
  2342. _get_code_parts(("python", "verbose_python", "cpp")) # type: ignore[assignment]
  2343. )
  2344. python_fallback = False
  2345. except OverflowError:
  2346. # Cannot use int64_t
  2347. python_fallback = True
  2348. python_code_parts, verbose_code_parts = _get_code_parts(
  2349. ("python", "verbose_python")
  2350. )
  2351. else:
  2352. python_fallback = True
  2353. python_code_parts, verbose_code_parts = _get_code_parts(
  2354. ("python", "verbose_python")
  2355. )
  2356. # When exporting, we may work with the shape constraints some more in
  2357. # postprocessing, so don't freeze yet
  2358. if not output_graph.export:
  2359. output_graph.shape_env.freeze()
  2360. if self.save_guards:
  2361. # For SHAPE_ENV we want to skip serializing the entire ShapeEnv so instead
  2362. # we directly serialize the generated code here.
  2363. maybe_cpp_code_parts = locals().get("cpp_code_parts")
  2364. assert maybe_cpp_code_parts is None or isinstance(
  2365. maybe_cpp_code_parts, _CppShapeGuardsHelper
  2366. )
  2367. maybe_shape_env_sources = (
  2368. []
  2369. if maybe_cpp_code_parts is None
  2370. else list(maybe_cpp_code_parts.source_to_symbol.keys())
  2371. )
  2372. self.check_fn_manager.shape_code_parts = ShapeCodeParts(
  2373. python_code_parts=python_code_parts,
  2374. verbose_code_parts=verbose_code_parts,
  2375. cpp_code_parts=maybe_cpp_code_parts,
  2376. python_fallback=python_fallback,
  2377. shape_env_sources=maybe_shape_env_sources,
  2378. )
  2379. for code in python_code_parts.exprs:
  2380. self._set_guard_export_info(guard, [code])
  2381. # Make ShapeEnv guards available for testing.
  2382. if compile_context := CompileContext.try_get():
  2383. compile_context.shape_env_guards.extend(verbose_code_parts.exprs)
  2384. int_source_to_symbol = []
  2385. float_source_to_symbol = []
  2386. if not python_fallback:
  2387. assert cpp_code_parts # type: ignore[possibly-undefined]
  2388. code_parts, source_to_symbol = (
  2389. # pyrefly: ignore [unbound-name]
  2390. cpp_code_parts.exprs,
  2391. # pyrefly: ignore [unbound-name, missing-attribute]
  2392. cpp_code_parts.source_to_symbol,
  2393. )
  2394. if not code_parts:
  2395. return
  2396. for source, symbol in source_to_symbol.items():
  2397. if isinstance(source, ConstantSource):
  2398. python_fallback = True
  2399. else:
  2400. example_value = self.get(
  2401. source,
  2402. closure_vars={**SYMPY_INTERP, **_get_closure_vars()},
  2403. )
  2404. if isinstance(example_value, int):
  2405. int_source_to_symbol.append((source, symbol))
  2406. elif isinstance(example_value, float):
  2407. float_source_to_symbol.append((source, symbol))
  2408. else:
  2409. # SymInts/SymFloats go through python guard as we only support
  2410. # int64_t/double in C++ guards for now.
  2411. python_fallback = True
  2412. if not python_fallback:
  2413. import ctypes
  2414. from torch._inductor.codecache import CppCodeCache
  2415. assert cpp_code_parts # type: ignore[possibly-undefined]
  2416. code_parts, source_to_symbol = (
  2417. # pyrefly: ignore [unbound-name]
  2418. cpp_code_parts.exprs,
  2419. # pyrefly: ignore [unbound-name, missing-attribute]
  2420. cpp_code_parts.source_to_symbol,
  2421. )
  2422. source_to_symbol = dict(int_source_to_symbol + float_source_to_symbol)
  2423. try:
  2424. guard_managers = [
  2425. self.get_guard_manager_from_source(IndexedSource(source, i))
  2426. for i, source in enumerate(source_to_symbol)
  2427. ]
  2428. int_symbols_str = ", ".join(
  2429. f"{symbol} = int_values[{i}]"
  2430. for i, (_, symbol) in enumerate(int_source_to_symbol)
  2431. )
  2432. float_symbols_str = ", ".join(
  2433. f"{symbol} = float_values[{i}]"
  2434. for i, (_, symbol) in enumerate(float_source_to_symbol)
  2435. )
  2436. if int_symbols_str:
  2437. int_symbols_str = f"int64_t {int_symbols_str};"
  2438. if float_symbols_str:
  2439. float_symbols_str = f"double {float_symbols_str};"
  2440. func_str = textwrap.dedent(
  2441. f"""
  2442. #include <algorithm>
  2443. #include <cstdint>
  2444. #include <cmath>
  2445. #include <c10/util/generic_math.h>
  2446. #if defined(_MSC_VER)
  2447. # define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
  2448. #else
  2449. # define EXTERN_DLL_EXPORT extern "C"
  2450. #endif
  2451. EXTERN_DLL_EXPORT int8_t guard(int64_t *int_values, double *float_values) {{
  2452. {int_symbols_str}
  2453. {float_symbols_str}
  2454. return ({") && (".join(code_parts)});
  2455. }}
  2456. """
  2457. )
  2458. guards_log.debug(
  2459. "C++ shape guard function: %s %s",
  2460. func_str,
  2461. verbose_code_parts.exprs,
  2462. )
  2463. clib = CppCodeCache.load(func_str)
  2464. cguard = ctypes.cast(clib.guard, ctypes.c_void_p).value
  2465. assert cguard
  2466. except torch._inductor.exc.InvalidCxxCompiler:
  2467. # No valid C++ compiler to compile the shape guard
  2468. pass
  2469. else:
  2470. install_symbolic_shape_guard(
  2471. guard_managers,
  2472. len(int_source_to_symbol),
  2473. len(float_source_to_symbol),
  2474. cguard,
  2475. clib,
  2476. verbose_code_parts.exprs,
  2477. )
  2478. return
  2479. # Install all the symbolic guards in one python lambda guard. These are run
  2480. # at the very end of the RootGuardManager via epilogue guards.
  2481. # TODO(anijain2305,williamwen42) - Consider moving this to C++.
  2482. if python_code_parts.exprs:
  2483. self.add_python_lambda_leaf_guard_to_root(
  2484. python_code_parts.exprs,
  2485. verbose_code_parts.exprs,
  2486. closure_vars={**SYMPY_INTERP, **_get_closure_vars()},
  2487. )
  2488. def TENSOR_MATCH(self, guard: Guard, value: Optional[Any] = None) -> None:
  2489. if config._unsafe_skip_fsdp_module_guards and guard.is_fsdp_module():
  2490. return
  2491. # For tensors that are part of the Dynamo extracted Fx graph module, an
  2492. # ID_MATCH suffices. Once we turn on inline_inbuilt_nn_modules, these
  2493. # will be lifted as inputs and have a TENSOR_MATCH guard.
  2494. if match_on_id_for_tensor(guard):
  2495. self.ID_MATCH(guard)
  2496. else:
  2497. if isinstance(value, TensorWeakRef):
  2498. value = value()
  2499. value = value if value is not None else self.get(guard)
  2500. pytype = type(value)
  2501. dispatch_keys = torch._C._dispatch_keys(value)
  2502. if isinstance(value, torch._subclasses.FakeTensor):
  2503. if value.pytype is not None:
  2504. pytype = value.pytype
  2505. if value.dispatch_keys is not None:
  2506. dispatch_keys = value.dispatch_keys
  2507. assert isinstance(value, torch.Tensor)
  2508. if config.log_compilation_metrics and isinstance(value, torch.nn.Parameter):
  2509. metrics_context = get_metrics_context()
  2510. if metrics_context.in_progress():
  2511. metrics_context.increment("param_numel", value.numel())
  2512. metrics_context.increment("param_bytes", value.nbytes)
  2513. metrics_context.increment("param_count", 1)
  2514. tensor_name = self.arg_ref(guard)
  2515. # [Note - On Export Tensor Guards]
  2516. #
  2517. # In eager mode, tensor guards are evaluated through C++, in guards.cpp
  2518. # see [Note - On Eager Tensor Guards] for more info.
  2519. #
  2520. # In export mode, we instead maintain parallel logic between C++ and python
  2521. # here, with an exception of checking the dispatch key - with the idea that a dispatch key
  2522. # is an entirely runtime notion that would make no sense to keep in an exported graph.
  2523. #
  2524. # Now, this idea is okay, but to paraphrase @ezyang, this mental model is sufficient for now, although
  2525. # not entirely true.
  2526. # For example, suppose one of the input tensors had the negative dispatch key.
  2527. # You should end up with a graph that is specialized for tensors that have a negative dispatch key.
  2528. # If you allow a Tensor that does NOT have this bit set, you will accidentally run it "as if" it were negated.
  2529. # Now, negative key only shows up for complex numbers, and most likely, the exported to target doesn't
  2530. # support this feature at all, but the point stands that :some: tensor state only shows up on dispatch key.
  2531. # TODO(voz): Either populate a dispatch_key check into the guards, or error on users passing in an unsupported
  2532. # subset of keys during export.
  2533. #
  2534. # The list of tensor fields and calls we care about can be found in `terms` below.
  2535. # TODO(voz): We are missing storage offset in all our tensor guards?
  2536. code: list[str] = []
  2537. assert self.check_fn_manager.output_graph is not None
  2538. if self.check_fn_manager.output_graph.export:
  2539. self.TYPE_MATCH(guard)
  2540. terms = [
  2541. "dtype",
  2542. "device",
  2543. "requires_grad",
  2544. "ndimension",
  2545. ]
  2546. for term in terms:
  2547. term_src = AttrSource(guard.originating_source, term)
  2548. if term == "ndimension":
  2549. term = "ndimension()"
  2550. term_src = CallFunctionNoArgsSource(term_src)
  2551. real_value = self.get(term_src)
  2552. if istype(real_value, (torch.device, torch.dtype)):
  2553. # copy pasted from EQUALS_MATCH
  2554. code.append(f"str({tensor_name}.{term}) == {str(real_value)!r}")
  2555. else:
  2556. code.append(f"{tensor_name}.{term} == {real_value}")
  2557. else:
  2558. guard_manager = self.get_guard_manager(guard)
  2559. # skip_no_tensor_aliasing_guards_on_parameters bring
  2560. # unsoundness. If you compile a function with two different
  2561. # parameters, but later on you pass on same tensor as two
  2562. # different outputs (aliasing), Dynamo will not detect this.
  2563. # But we deliberately take this soundness hit because this
  2564. # usecase is quite rare and there is substantial reduction in
  2565. # guard overhead.
  2566. # For numpy tensors, since those are ephemeral, we don't have to
  2567. # insert aliasing guards on them
  2568. if not (
  2569. config.skip_no_tensor_aliasing_guards_on_parameters
  2570. and (
  2571. istype(value, torch.nn.Parameter)
  2572. or is_from_unspecialized_builtin_nn_module_source(
  2573. guard.originating_source
  2574. )
  2575. )
  2576. ) and not isinstance(guard.originating_source, NumpyTensorSource):
  2577. # Keep track of all the tensor guard managers to insert
  2578. # NoAliasing check at the end.
  2579. self.no_tensor_aliasing_names.append(tensor_name)
  2580. self.no_tensor_aliasing_guard_managers.append(guard_manager)
  2581. output_graph = self.check_fn_manager.output_graph
  2582. metadata = output_graph.input_source_to_sizes_strides[
  2583. guard.originating_source
  2584. ]
  2585. size = convert_to_concrete_values(metadata["size"])
  2586. stride = convert_to_concrete_values(metadata["stride"])
  2587. verbose_code_parts = get_verbose_code_parts(
  2588. get_tensor_guard_code_part(
  2589. value,
  2590. tensor_name,
  2591. size,
  2592. stride,
  2593. pytype,
  2594. dispatch_keys,
  2595. ),
  2596. guard,
  2597. )
  2598. guard_manager.add_tensor_match_guard(
  2599. value,
  2600. size, # type: ignore[arg-type]
  2601. stride, # type: ignore[arg-type]
  2602. tensor_name,
  2603. verbose_code_parts,
  2604. pytype,
  2605. dispatch_keys,
  2606. )
  2607. # We consider TENSOR_MATCH guard to be important enough to be
  2608. # included in diff guard manager by default.
  2609. if not isinstance(value, torch.nn.Parameter):
  2610. self.guard_manager.diff_guard_sources.add(guard.name)
  2611. # A frame is valid for reuse with dynamic dimensions if the new
  2612. # (user-requested) dynamic dimensions are a subset of the old
  2613. # (already compiled) dynamic dimensions.
  2614. #
  2615. # It's a little non-obvious why you'd want this: in particular,
  2616. # if an already compiled frame matches all of the guards, why
  2617. # not just use it, why force a recompile?
  2618. #
  2619. # We force it for two reasons:
  2620. #
  2621. # - The user *required* us to compile with a new dynamic dimension,
  2622. # we should not ignore that and serve up the old, specialized
  2623. # frame. Listen to the user!
  2624. #
  2625. # - In fact, we are obligated to *raise an error* if we fail to
  2626. # make the requested dimension dynamic. If we don't
  2627. # recompile, we can't tell if that dimension can actually be
  2628. # made dynamic.
  2629. #
  2630. # If the new dynamic dims are a subset of the old, we already know
  2631. # we can make them dynamic (since we made them dynamic in old).
  2632. # This is slightly unsound, because maybe your input size is
  2633. # [s0, s0, s1] and so you can do it dynamic if you say dynamic
  2634. # dims {0, 1, 2} but you can't if you only do {0, 2} (because now
  2635. # the second s0 is specialized). But we're not entirely sure if
  2636. # this is a good idea anyway lol... (if you want to try removing
  2637. # this logic, be my guest! -- ezyang 2024)
  2638. #
  2639. assert guard.source is not None
  2640. static, _reason = tensor_always_has_static_shape(
  2641. value, is_tensor=True, tensor_source=guard.originating_source
  2642. )
  2643. if not static:
  2644. if hasattr(value, "_dynamo_dynamic_indices"):
  2645. dynamic_indices = value._dynamo_dynamic_indices
  2646. code_part = f"(({tensor_name}._dynamo_dynamic_indices.issubset({dynamic_indices})) if hasattr({tensor_name}, '_dynamo_dynamic_indices') else True)" # noqa: B950
  2647. code.append(code_part)
  2648. self.get_guard_manager(guard).add_dynamic_indices_guard(
  2649. dynamic_indices, get_verbose_code_parts(code_part, guard)
  2650. )
  2651. # In the case of us not having any dynamic dimension indices, we compiled the frame with no chance of
  2652. # raising for this specific tensor - and any inputs with more dynamic user directives specified must be recompiled.
  2653. else:
  2654. code_part = (
  2655. f"hasattr({tensor_name}, '_dynamo_dynamic_indices') == False"
  2656. )
  2657. code.append(code_part)
  2658. self.get_guard_manager(guard).add_no_hasattr_guard(
  2659. "_dynamo_dynamic_indices",
  2660. get_verbose_code_parts(code_part, guard),
  2661. )
  2662. if len(code) > 0:
  2663. self._set_guard_export_info(guard, code)
  2664. # A util that in the case of export, adds data onto guards
  2665. def _set_guard_export_info(
  2666. self,
  2667. guard: Guard,
  2668. code_list: list[str],
  2669. provided_guarded_object: Optional[Any] = None,
  2670. provided_func_name: Optional[str] = None,
  2671. ) -> None:
  2672. # WARNING: It is important that cur_frame/caller do NOT stay in
  2673. # the current frame, because they will keep things live longer
  2674. # than they should. See TestMisc.test_release_module_memory
  2675. cur_frame = currentframe()
  2676. assert cur_frame is not None
  2677. caller = cur_frame.f_back
  2678. del cur_frame
  2679. assert caller is not None
  2680. func_name = provided_func_name or caller.f_code.co_name
  2681. del caller
  2682. # We use func_name for export, so might as well get a nice defensive check out of it
  2683. assert func_name in self.__class__.__dict__, (
  2684. f"_produce_guard_code must be called from inside GuardedCode. Called from {func_name}"
  2685. )
  2686. # Not all guards have names, some can be installed globally (see asserts on HAS_GRAD)
  2687. if provided_guarded_object is None:
  2688. name = guard.name
  2689. guarded_object = None if not name else self.get(guard)
  2690. else:
  2691. guarded_object = provided_guarded_object
  2692. guarded_object_type = (
  2693. weakref.ref(type(guarded_object)) if guarded_object is not None else None
  2694. )
  2695. obj_ref = None
  2696. # Not necessary to have weakref for Enum type, but there is a bug that
  2697. # makes hasattr(guarded_object.__class__, "__weakref__") return True.
  2698. supports_weakref = (
  2699. getattr(guarded_object.__class__, "__weakrefoffset__", 0) != 0
  2700. )
  2701. # See D64140537 for why we are checking for tuple.
  2702. if supports_weakref and not isinstance(
  2703. guarded_object, (enum.Enum, tuple, weakref.ProxyTypes)
  2704. ):
  2705. obj_ref = weakref.ref(guarded_object)
  2706. guard.set_export_info(
  2707. func_name,
  2708. guarded_object_type,
  2709. code_list,
  2710. obj_ref,
  2711. )
  2712. # Common Sub-Expression Elimination for Python expressions.
  2713. #
  2714. # There are 2 steps to this pass:
  2715. # 1. Count the frequency of each sub-expression (i.e. inner
  2716. # node in the AST tree)
  2717. #
  2718. # 2. Replace those that occur more than once by a fresh variable 'v'.
  2719. # 'v' will be defined in the 'preface' list (output argument to
  2720. # 'NodeTransformer')
  2721. #
  2722. # NB: the use of 'ast.unparse' while visiting the nodes makes this pass
  2723. # quadratic on the depth of the tree.
  2724. #
  2725. # NB: this pass creates a new variable for each AST node that is repeated
  2726. # more than 'USE_THRESHOLD'. e.g. if 'a.b.c.d' is used 10 times, 'a.b.c'
  2727. # and 'a.b' are also used 10 times. So, there will be a new variable for
  2728. # each of them.
  2729. class PyExprCSEPass:
  2730. # Maximum number of times a given expression can be used without being
  2731. # replaced by a fresh variable.
  2732. USE_THRESHOLD = 1
  2733. # Ad-Hoc: AST nodes this pass focuses on.
  2734. ALLOWED_NODE_TYPES = (ast.Attribute, ast.Call, ast.Subscript)
  2735. @dataclasses.dataclass
  2736. class Config:
  2737. expr_count: dict[str, int]
  2738. expr_to_name: dict[str, str]
  2739. class ExprCounter(ast.NodeVisitor):
  2740. def __init__(self, config: PyExprCSEPass.Config) -> None:
  2741. self._config = config
  2742. def visit(self, node: ast.AST) -> None:
  2743. if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES):
  2744. self._config.expr_count[_ast_unparse(node)] += 1
  2745. super().visit(node)
  2746. class Replacer(ast.NodeTransformer):
  2747. def __init__(
  2748. self,
  2749. config: PyExprCSEPass.Config,
  2750. gen_name: Callable[[], str],
  2751. ) -> None:
  2752. super().__init__()
  2753. self._config = config
  2754. self._gen_name = gen_name
  2755. self.preface: list[str] = []
  2756. def visit(self, node: ast.AST) -> Any:
  2757. if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES):
  2758. expr = _ast_unparse(node)
  2759. # Replacement only occurs if a given expression is used more
  2760. # than once.
  2761. if self._config.expr_count[expr] > PyExprCSEPass.USE_THRESHOLD:
  2762. if expr not in self._config.expr_to_name:
  2763. # Parent 'visit' is called so that we CSE the inner expressions first.
  2764. #
  2765. # The resulting expression is used as right-hand-side of the variable
  2766. # assignment. i.e. we are CSE-ing the children before the parents.
  2767. #
  2768. # Indexing still uses the old 'node', since that's what was counted
  2769. # by the 'NodeVisitor'.
  2770. node_ = super().visit(node)
  2771. expr_ = _ast_unparse(node_)
  2772. var_name = self._gen_name()
  2773. self.preface.append(f"{var_name} = {expr_}")
  2774. self._config.expr_to_name[expr] = var_name
  2775. else:
  2776. var_name = self._config.expr_to_name[expr]
  2777. return ast.Name(var_name, ast.Load())
  2778. return super().visit(node)
  2779. def __init__(self) -> None:
  2780. self._counter = 0
  2781. self._config = self.Config(
  2782. expr_count=collections.defaultdict(lambda: 0), expr_to_name={}
  2783. )
  2784. def _new_var(self, prefix: str = "_var") -> str:
  2785. name = f"{prefix}{self._counter}"
  2786. self._counter += 1
  2787. return name
  2788. def count(self, exprs: list[str]) -> None:
  2789. counter = self.ExprCounter(self._config)
  2790. for e in exprs:
  2791. try:
  2792. counter.visit(ast.parse(e))
  2793. except SyntaxError as ex:
  2794. log.exception("Failed to visit expr at line %s.\n%s", ex.lineno, e)
  2795. raise
  2796. def replace(self, expr: str) -> tuple[list[str], str]:
  2797. replacer = self.Replacer(self._config, self._new_var)
  2798. new_node = replacer.visit(ast.parse(expr))
  2799. return replacer.preface, _ast_unparse(new_node)
  2800. def must_add_nn_module_guards(guard: Guard) -> bool:
  2801. # For config.guard_nn_modules=False, we can skip all the guards that
  2802. # originate from inside of nn module except for a few categories.
  2803. return (
  2804. # Guard for defaults
  2805. isinstance(guard.originating_source, DefaultsSource)
  2806. # Guard using dict tags if the config flag is set
  2807. or (
  2808. config.guard_nn_modules_using_dict_tags
  2809. and guard.create_fn is GuardBuilder.NN_MODULE
  2810. )
  2811. )
  2812. class DeletedGuardManagerWrapper(GuardManagerWrapper):
  2813. def __init__(self, reason: str) -> None:
  2814. super().__init__()
  2815. self.invalidation_reason = reason
  2816. def populate_diff_guard_manager(self) -> None:
  2817. self.diff_guard_root = None
  2818. @dataclasses.dataclass
  2819. class ShapeCodeParts:
  2820. python_code_parts: _ShapeGuardsHelper
  2821. verbose_code_parts: _ShapeGuardsHelper
  2822. cpp_code_parts: Optional[_CppShapeGuardsHelper]
  2823. python_fallback: bool
  2824. shape_env_sources: list[Source]
  2825. @dataclasses.dataclass
  2826. class GuardsState:
  2827. output_graph: OutputGraphGuardsState
  2828. shape_code_parts: Optional[ShapeCodeParts]
  2829. source_get_cache: Optional[dict[str, Any]] = None
  2830. class _Missing:
  2831. def __init__(self, reason: Optional[str] = None) -> None:
  2832. self._reason = reason
  2833. def __repr__(self) -> str:
  2834. return f"_Missing({self._reason})"
  2835. def __str__(self) -> str:
  2836. return f"_Missing({self._reason})"
  2837. # Sometimes _Missing object is used as the callable with functools.partial,
  2838. # so we add a dummy __call__ here to bypass TypeError from partial().
  2839. def __call__(self, *args: Any, **kwargs: Any) -> Any:
  2840. return _Missing()
  2841. @functools.cache
  2842. def _get_unsupported_types() -> tuple[type, ...]:
  2843. # We only do ID_MATCH on C objects which is already banned from guards serialization.
  2844. ret: tuple[type, ...] = (
  2845. types.CodeType,
  2846. torch._C.Stream,
  2847. weakref.ReferenceType,
  2848. )
  2849. try:
  2850. ret += (torch._C._distributed_c10d.ProcessGroup,)
  2851. except AttributeError:
  2852. pass
  2853. return ret
  2854. class GuardsStatePickler(pickle.Pickler):
  2855. def __init__(
  2856. self,
  2857. guard_tree_values: dict[int, Any],
  2858. empty_values: dict[int, Any],
  2859. missing_values: dict[int, Any],
  2860. *args: Any,
  2861. **kwargs: Any,
  2862. ) -> None:
  2863. super().__init__(*args, **kwargs)
  2864. self.fake_mode = torch._subclasses.FakeTensorMode()
  2865. self.tensor_converter = torch._subclasses.fake_tensor.FakeTensorConverter()
  2866. self.guard_tree_values = guard_tree_values
  2867. self.empty_values = empty_values
  2868. self.missing_values = missing_values
  2869. @classmethod
  2870. def _unpickle_module(cls, state: Any) -> torch.nn.Module:
  2871. mod = torch.nn.Module()
  2872. mod.__setstate__(state)
  2873. return mod
  2874. @classmethod
  2875. def _unpickle_tensor(
  2876. cls,
  2877. meta_tensor: torch.Tensor,
  2878. device: torch.device,
  2879. pytype: type,
  2880. dispatch_keys_raw: int,
  2881. grad: torch.Tensor,
  2882. ) -> torch.Tensor:
  2883. fake_mode = torch._subclasses.FakeTensorMode()
  2884. tensor_converter = torch._subclasses.fake_tensor.FakeTensorConverter()
  2885. ret = tensor_converter.from_meta_and_device(
  2886. fake_mode,
  2887. meta_tensor,
  2888. device,
  2889. pytype,
  2890. torch._C.DispatchKeySet.from_raw_repr(dispatch_keys_raw),
  2891. )
  2892. ret.grad = grad
  2893. return ret
  2894. @classmethod
  2895. def _unpickle_traceable_wrapper_subclass(
  2896. cls,
  2897. meta_tensor: torch.Tensor,
  2898. device: torch.device,
  2899. pytype: type,
  2900. dispatch_keys_raw: int,
  2901. ctx: Any,
  2902. inner_data: list[tuple[str, Callable[..., Any], tuple[Any, ...]]],
  2903. ) -> torch.Tensor:
  2904. # Unpickle the inner tensor components. These could also be subclass instances.
  2905. inner_tensors = {}
  2906. for attr, unpickle_func, unpickle_func_args in inner_data:
  2907. inner_tensors[attr] = unpickle_func(*unpickle_func_args)
  2908. outer_size, outer_stride = meta_tensor.shape, meta_tensor.stride()
  2909. out = type(meta_tensor).__tensor_unflatten__( # type: ignore[attr-defined]
  2910. inner_tensors, ctx, outer_size, outer_stride
  2911. )
  2912. out.pytype = pytype
  2913. out.dispatch_keys = torch._C.DispatchKeySet.from_raw_repr(dispatch_keys_raw)
  2914. return out
  2915. @classmethod
  2916. def _unpickle_python_module(cls, alias: str) -> types.ModuleType:
  2917. return importlib.import_module(alias)
  2918. @classmethod
  2919. def _unpickle_dispatch_key_set(cls, raw_repr: int) -> torch._C.DispatchKeySet:
  2920. return torch._C.DispatchKeySet.from_raw_repr(raw_repr)
  2921. @classmethod
  2922. def _unpickle_functorch_interpreter(
  2923. cls, json: bytes
  2924. ) -> torch._C._functorch.CInterpreter:
  2925. return torch._C._functorch.CInterpreter.deserialize(json)
  2926. @classmethod
  2927. def _unpickle_mapping_proxy(
  2928. cls, d: dict[Any, Any]
  2929. ) -> types.MappingProxyType[Any, Any]:
  2930. return types.MappingProxyType(d)
  2931. @classmethod
  2932. def _unpickle_dict_keys(cls, elems: list[Any]) -> Any:
  2933. return dict.fromkeys(elems).keys()
  2934. @classmethod
  2935. def _unpickle_fsdp_module_type(
  2936. cls, original_type: type[torch.nn.Module]
  2937. ) -> type[torch.nn.Module]:
  2938. return torch.distributed.fsdp._fully_shard._fully_shard.get_cls_to_fsdp_cls()[
  2939. original_type
  2940. ]
  2941. @classmethod
  2942. def _unpickle_ddp_module(
  2943. cls, state: dict[str, Any]
  2944. ) -> torch.nn.parallel.DistributedDataParallel:
  2945. ty = torch.nn.parallel.DistributedDataParallel
  2946. ddp = ty.__new__(ty)
  2947. torch.nn.Module.__setstate__(ddp, state)
  2948. return ddp
  2949. @classmethod
  2950. def _unpickle_c_op(cls, name: str) -> Any:
  2951. return getattr(torch.ops._C, name)
  2952. @classmethod
  2953. def _unpickle_bound_method(cls, func: Any, base: Any) -> Any:
  2954. return types.MethodType(func, base)
  2955. @staticmethod
  2956. def _unpickle_sdp_backend(name: str) -> torch.nn.attention.SDPBackend:
  2957. # Reconstruct from the Python-facing enum namespace
  2958. return getattr(torch.nn.attention.SDPBackend, name)
  2959. @classmethod
  2960. def _unpickle_cell(cls, val: Any) -> Any:
  2961. def _() -> Any:
  2962. return val
  2963. assert _.__closure__ is not None
  2964. return _.__closure__[0]
  2965. # pyrefly: ignore [bad-override]
  2966. def reducer_override(
  2967. self, obj: Any
  2968. ) -> Union[tuple[Callable[..., Any], tuple[Any, ...]], Any]:
  2969. import sympy
  2970. if id(obj) in self.empty_values:
  2971. return type(obj).__new__, (type(obj),)
  2972. if id(obj) in self.missing_values:
  2973. return _Missing, ("missing values",)
  2974. if isinstance(obj, torch.Tensor) and obj.device.type != "meta":
  2975. from torch.utils._python_dispatch import is_traceable_wrapper_subclass
  2976. if id(obj) not in self.guard_tree_values:
  2977. return _Missing, ("tensor guard tree",)
  2978. if is_traceable_wrapper_subclass(obj):
  2979. # inner_data is a list of tuples of:
  2980. # (inner attr name, unpickle func, tuple of func inputs)
  2981. # This supports traceable wrapper subclass inner tensors.
  2982. inner_data = []
  2983. attrs, ctx = obj.__tensor_flatten__()
  2984. # recursively call for inner tensor components
  2985. for attr in attrs:
  2986. inner = getattr(obj, attr)
  2987. if isinstance(inner, torch.Tensor):
  2988. self.guard_tree_values[id(inner)] = inner
  2989. func, args_tuple = self.reducer_override(inner)
  2990. inner_data.append((attr, func, args_tuple))
  2991. return type(self)._unpickle_traceable_wrapper_subclass, (
  2992. torch.empty_like(obj, device="meta"),
  2993. obj.device,
  2994. type(obj),
  2995. torch._C._dispatch_keys(obj).raw_repr(),
  2996. ctx,
  2997. inner_data,
  2998. )
  2999. return type(self)._unpickle_tensor, (
  3000. torch.empty_like(obj, device="meta", requires_grad=obj.requires_grad),
  3001. obj.device,
  3002. type(obj),
  3003. torch._C._dispatch_keys(obj).raw_repr(),
  3004. obj.grad,
  3005. )
  3006. elif isinstance(obj, torch.nn.Module):
  3007. if id(obj) not in self.guard_tree_values:
  3008. return _Missing, ("module guard tree",)
  3009. # DDP module is a special case because it tries to restore unneeded
  3010. # data in custom __setstate__. We cannot skip ddp module because it
  3011. # is often a toplevel module.
  3012. if isinstance(obj, torch.nn.parallel.DistributedDataParallel):
  3013. return type(self)._unpickle_ddp_module, (obj.__getstate__(),)
  3014. if type(obj).__qualname__ == type(obj).__name__:
  3015. return NotImplemented
  3016. if obj.__class__.__getstate__ == torch.nn.Module.__getstate__:
  3017. return type(self)._unpickle_module, (obj.__getstate__(),)
  3018. elif inspect.ismodule(obj):
  3019. return type(self)._unpickle_python_module, (obj.__name__,)
  3020. elif isinstance(obj, torch._C.DispatchKeySet):
  3021. return type(self)._unpickle_dispatch_key_set, (obj.raw_repr(),)
  3022. elif isinstance(obj, torch._C._functorch.CInterpreter):
  3023. return type(self)._unpickle_functorch_interpreter, (obj.serialize(),)
  3024. elif (
  3025. inspect.isclass(obj)
  3026. and issubclass(obj, sympy.Function)
  3027. and hasattr(obj, "_torch_handler_name")
  3028. ):
  3029. assert hasattr(obj, "_torch_unpickler")
  3030. return obj._torch_unpickler, (obj._torch_handler_name,)
  3031. elif isinstance(obj, torch.SymInt):
  3032. raise RuntimeError(f"Cannot serialize SymInt {obj} (node: {obj.node})")
  3033. elif isinstance(obj, types.MappingProxyType):
  3034. return type(self)._unpickle_mapping_proxy, (obj.copy(),)
  3035. elif isinstance(obj, torch._dynamo.utils.dict_keys):
  3036. return type(self)._unpickle_dict_keys, (list(obj),)
  3037. elif isinstance(
  3038. obj, torch._ops.OpOverloadPacket
  3039. ) and obj._qualified_op_name.startswith("_C::"):
  3040. return type(self)._unpickle_c_op, (obj.__name__,)
  3041. elif (
  3042. obj.__class__.__module__ == "builtins"
  3043. and obj.__class__.__name__ == "PyCapsule"
  3044. ):
  3045. # Skipping PyCapsule since there isn't much to be guarded about them.
  3046. return _Missing, ("capsule",)
  3047. elif isinstance(obj, _get_unsupported_types()):
  3048. return _Missing, ("unsupported",)
  3049. elif inspect.isfunction(obj):
  3050. if obj.__code__.co_flags & inspect.CO_NESTED:
  3051. return _Missing, ("nested function",)
  3052. if obj.__module__ in sys.modules:
  3053. f = sys.modules[obj.__module__]
  3054. for name in obj.__qualname__.split("."):
  3055. f = getattr(f, name, None) # type: ignore[assignment]
  3056. if f is not obj:
  3057. return _Missing, ("fqn mismatch",)
  3058. elif inspect.ismethod(obj):
  3059. func = obj.__func__
  3060. method_self = obj.__self__
  3061. inner_func = getattr(method_self, func.__name__)
  3062. if inspect.ismethod(inner_func):
  3063. inner_func = inner_func.__func__
  3064. if func is not inner_func:
  3065. return type(self)._unpickle_bound_method, (func, method_self)
  3066. elif isinstance(obj, type((lambda x: lambda: x)(0).__closure__[0])): # type: ignore[index] # noqa: PLC3002
  3067. return type(self)._unpickle_cell, (obj.cell_contents,)
  3068. if hasattr(torch.distributed, "distributed_c10d") and isinstance(
  3069. obj, torch.distributed.distributed_c10d.Work
  3070. ):
  3071. if id(obj) not in self.guard_tree_values:
  3072. return _Missing, ("distributed_c10d.Work",)
  3073. if isinstance(obj, torch.nn.attention.SDPBackend):
  3074. return type(self)._unpickle_sdp_backend, (obj.name,)
  3075. if type(obj).__qualname__ != type(obj).__name__:
  3076. raise torch._dynamo.exc.PackageError(
  3077. f"Type {type(obj)} for object {obj} cannot be saved "
  3078. + "into torch.compile() package since it's defined in local scope. "
  3079. + "Please define the class at global scope (top level of a module)."
  3080. )
  3081. if (
  3082. inspect.isclass(obj)
  3083. and hasattr(torch.distributed, "fsdp")
  3084. and issubclass(obj, torch.distributed.fsdp._fully_shard.FSDPModule)
  3085. ):
  3086. if obj is not torch.distributed.fsdp._fully_shard.FSDPModule:
  3087. original_type = obj.__mro__[2]
  3088. assert issubclass(original_type, torch.nn.Module)
  3089. assert (
  3090. original_type
  3091. in torch.distributed.fsdp._fully_shard._fully_shard.get_cls_to_fsdp_cls()
  3092. )
  3093. return type(self)._unpickle_fsdp_module_type, (original_type,)
  3094. return NotImplemented
  3095. def pickle_guards_state(state: GuardsState, guard_tree_values: dict[int, Any]) -> bytes:
  3096. buf = io.BytesIO()
  3097. empty_values = {}
  3098. missing_values = {}
  3099. leaves = pytree.tree_leaves(state.output_graph.local_scope)
  3100. for leaf in leaves:
  3101. if inspect.ismethod(leaf) and hasattr(leaf, "__self__"):
  3102. base = leaf.__self__
  3103. if id(base) not in guard_tree_values:
  3104. try:
  3105. type(base).__new__(type(base))
  3106. empty_values[id(base)] = base
  3107. except: # noqa: E722, B001
  3108. pass
  3109. elif id(leaf) not in guard_tree_values:
  3110. # TODO See if we have lift this branch as the first one.
  3111. # Prune more objects in pytree hierarchy.
  3112. missing_values[id(leaf)] = leaf
  3113. pickler = GuardsStatePickler(guard_tree_values, empty_values, missing_values, buf)
  3114. try:
  3115. pickler.dump(state)
  3116. except AttributeError as e:
  3117. raise torch._dynamo.exc.PackageError(str(e)) from e
  3118. return buf.getvalue()
  3119. # NB: Naively, you'd expect this to only be a function that produces
  3120. # the callable that constitutes the guard. However, there is some
  3121. # delicate handling for invalidating this check function when the
  3122. # locals/globals get invalidated, so there's some extra state
  3123. # we have to hold in this manager class.
  3124. class CheckFunctionManager:
  3125. def __init__(
  3126. self,
  3127. f_code: types.CodeType,
  3128. output_graph: OutputGraphCommon,
  3129. cache_entry: Optional[CacheEntry] = None,
  3130. guard_fail_fn: Optional[Callable[[GuardFail], None]] = None,
  3131. guard_filter_fn: Optional[
  3132. Callable[[list[GuardFilterEntry]], list[bool]]
  3133. ] = None,
  3134. shape_code_parts: Optional[ShapeCodeParts] = None,
  3135. runtime_global_scope: Optional[dict[str, Any]] = None,
  3136. save_guards: bool = False,
  3137. strict_error: bool = False,
  3138. source_get_cache: Optional[dict[str, Any]] = None,
  3139. ):
  3140. guards = output_graph.guards if output_graph else None
  3141. self._weakrefs: dict[int, ReferenceType[object]] = {}
  3142. existing_diff_guard_sources = (
  3143. update_diff_guard_managers_for_existing_cache_entries(cache_entry)
  3144. )
  3145. self.output_graph: Optional[OutputGraphCommon] = output_graph
  3146. assert self.output_graph is not None
  3147. # Only used for serialization.
  3148. self.shape_code_parts = shape_code_parts
  3149. # NB: Until we trace device contexts, we need to use the stack recorded at the beginning of tracing
  3150. # in case a set default device call was made in the graph.
  3151. self.torch_function_mode_stack = (
  3152. output_graph.torch_function_mode_stack if output_graph else None
  3153. )
  3154. self.used_builtin_vars: OrderedSet[str] = OrderedSet()
  3155. self.additional_used_local_vars: OrderedSet[str] = OrderedSet()
  3156. self.additional_used_global_vars: OrderedSet[str] = OrderedSet()
  3157. self.runtime_global_scope = runtime_global_scope
  3158. self.global_state: Optional[torch._C._dynamo.guards.GlobalStateGuard] = None
  3159. self.torch_function_mode_stack_check_fn: Optional[Callable[[], bool]] = None
  3160. if not justknobs_check("pytorch/compiler:guard_nn_modules"):
  3161. log.warning("guard_nn_modules is turned off using justknobs killswitch")
  3162. # TODO Be more explicit about the behavior for the users.
  3163. if torch._dynamo.config.caching_precompile:
  3164. _guard_filter_fn = guard_filter_fn or (lambda gs: [True for g in gs])
  3165. def guard_filter_fn(guards: list[GuardFilterEntry]) -> list[bool]:
  3166. ret = []
  3167. for keep, g in zip(_guard_filter_fn(guards), guards):
  3168. if not keep:
  3169. ret.append(False)
  3170. elif (
  3171. g.guard_type
  3172. in (
  3173. "ID_MATCH",
  3174. "CLOSURE_MATCH",
  3175. "WEAKREF_ALIVE",
  3176. "DICT_VERSION",
  3177. )
  3178. or "ID_MATCH" in g.derived_guard_types
  3179. or "DICT_VERSION" in g.derived_guard_types
  3180. ):
  3181. log.warning(
  3182. "%s guard on %s is dropped with caching_precompile=True.",
  3183. g.guard_type,
  3184. g.orig_guard.name,
  3185. )
  3186. ret.append(False)
  3187. else:
  3188. ret.append(True)
  3189. return ret
  3190. sorted_guards = sorted(guards or (), key=Guard.sort_key)
  3191. if guard_filter_fn:
  3192. # If we're filtering guards, we need to build it an extra time first
  3193. # because filtering depends on the builder/guard_manager results
  3194. builder, guard_manager = self.build_guards(
  3195. sorted_guards,
  3196. existing_diff_guard_sources,
  3197. f_code,
  3198. output_graph,
  3199. False,
  3200. source_get_cache=source_get_cache,
  3201. )
  3202. def make_guard_filter_entry(guard: Guard) -> GuardFilterEntry:
  3203. MISSING = object()
  3204. name = strip_local_scope(guard.name)
  3205. if name == "":
  3206. has_value = False
  3207. value = MISSING
  3208. else:
  3209. try:
  3210. # Guard evaluation is expected to fail when we guard on
  3211. # things like "not hasattr(x, 'foo')". In cases like this,
  3212. # we don't have a well defined value because such thing
  3213. # doesn't exist.
  3214. value = builder.get(guard)
  3215. has_value = True
  3216. except: # noqa: B001,E722
  3217. value = MISSING
  3218. has_value = False
  3219. is_global = get_global_source_name(guard.originating_source) is not None
  3220. return GuardFilterEntry(
  3221. name=name,
  3222. has_value=has_value,
  3223. value=value,
  3224. guard_type=guard.create_fn_name(),
  3225. derived_guard_types=(
  3226. tuple(guard.guard_types) if guard.guard_types else ()
  3227. ),
  3228. is_global=is_global,
  3229. orig_guard=guard,
  3230. )
  3231. filter_results = guard_filter_fn(
  3232. [make_guard_filter_entry(guard) for guard in sorted_guards]
  3233. )
  3234. assert len(filter_results) == len(sorted_guards)
  3235. assert all(type(x) is bool for x in filter_results)
  3236. sorted_guards = [
  3237. guard for i, guard in enumerate(sorted_guards) if filter_results[i]
  3238. ]
  3239. # Redo the guards because filtering relies on the results from the last guard builder.
  3240. builder, guard_manager = self.build_guards(
  3241. sorted_guards,
  3242. existing_diff_guard_sources,
  3243. f_code,
  3244. output_graph,
  3245. save_guards,
  3246. source_get_cache=source_get_cache,
  3247. )
  3248. self.guard_manager = guard_manager
  3249. self.compile_check_fn(builder, sorted_guards, guard_fail_fn)
  3250. # Keep track of weak references of objects with ID_MATCH guard. This
  3251. # info is stored alongside optimized_code and guard_manager and is used to
  3252. # limit the number of cache entries with same ID_MATCH'd object.
  3253. # TODO(anijain2305) - Currently this information is stored as an attr on
  3254. # the guard_manager itself to avoid changing CacheEntry data structure in
  3255. # eval_frame.c. In future, we should probably replace guard_manager with a
  3256. # queryable data structure such that this information is already present
  3257. # in some form.
  3258. self.guard_manager.id_matched_objs = builder.id_matched_objs
  3259. guards_log.debug("%s", self.guard_manager)
  3260. self.guard_manager.id_matched_objs = builder.id_matched_objs
  3261. # Check that the guard returns True. False means that we will always
  3262. # recompile.
  3263. # TODO(anijain2305, ydwu4) - Skipping export because of following test
  3264. # python -s test/dynamo/test_export.py -k test_export_with_symbool_inputs
  3265. latency = 0.0
  3266. if not output_graph.skip_guards_check and not output_graph.export:
  3267. if not self.guard_manager.check(output_graph.local_scope):
  3268. reasons = get_guard_fail_reason_helper(
  3269. self.guard_manager,
  3270. output_graph.local_scope,
  3271. CompileContext.current_compile_id(),
  3272. backend=None, # no need to set this because we are trying to find the offending guard entry
  3273. )
  3274. raise AssertionError(
  3275. "Guard failed on the same frame it was created. This is a bug - please create an issue."
  3276. f"Guard fail reason: {reasons}"
  3277. )
  3278. if guard_manager_testing_hook_fn is not None:
  3279. guard_manager_testing_hook_fn(
  3280. self.guard_manager, output_graph.local_scope, builder
  3281. )
  3282. # NB for developers: n_iters is chosen to be 1 to prevent excessive
  3283. # increase in compile time. We first do a cache flush to measure the
  3284. # guard latency more accurately. This cache flush is expensive.
  3285. # Note - If you are working on a guard optimization, it might be a
  3286. # good idea to increase this number for more stability during
  3287. # development.
  3288. latency = profile_guard_manager(
  3289. self.guard_manager.root, output_graph.local_scope, 1
  3290. )
  3291. guards_log.debug("Guard eval latency = %s us", f"{latency:.2f}")
  3292. # Note: We use `increment_toplevel` instead of `compilation_metric`
  3293. # here. This is because, in scenarios where `torch._dynamo.reset`
  3294. # is invoked, the same frame ID and compile ID may be reused during
  3295. # a new compilation cycle. This behavior causes issues with
  3296. # `compilation_metric`, as it expects the metric field to be empty.
  3297. # Ideally, we would overwrite the existing entry in such cases, but
  3298. # we currently lack an API to support overwriting metrics. However,
  3299. # since these situations are rare and typically impractical to
  3300. # account for, we simply increment at the toplevel instead.
  3301. CompileEventLogger.increment_toplevel("guard_latency_us", int(latency))
  3302. self.guards_state: Optional[bytes] = None
  3303. if save_guards:
  3304. from torch._dynamo.output_graph import OutputGraphCommon
  3305. assert isinstance(self.output_graph, OutputGraphCommon)
  3306. try:
  3307. self.guards_state = self.serialize_guards(
  3308. builder, sorted_guards, self.output_graph
  3309. )
  3310. except exc.PackageError as e:
  3311. if torch._dynamo.config.strict_precompile or strict_error:
  3312. raise e
  3313. self.output_graph.bypass_package(
  3314. f"Guard evaluation failed: {str(e)}",
  3315. traceback=traceback.format_exc().split("\n"),
  3316. )
  3317. # TODO: don't do the string rep, do something more structured here
  3318. torch._logging.trace_structured(
  3319. "dynamo_cpp_guards_str",
  3320. payload_fn=lambda: f"{self.guard_manager}\nGuard latency = {latency:.2f} us",
  3321. )
  3322. # NB - We have to very careful of cleaning up here. Because of the
  3323. # invalidate function, we can create a weakref finalizer that keeps
  3324. # `self` alive for very long. Sometimes by mistake, we can run
  3325. # invalidate for a type/object (check id_ref method) that Python can
  3326. # leak by design, preventing us from calling the finalizer. In that
  3327. # case, the `self` will be alive even though the cache entry will be
  3328. # deleted (check invalidate method), which can cause a memory leak,
  3329. # e.g., not setting output_graph = None can keep hold of nn_modules.
  3330. self._weakrefs.clear()
  3331. self.output_graph = None
  3332. UNSUPPORTED_SERIALIZATION_GUARD_TYPES: tuple[LiteralString, ...] = (
  3333. "DICT_VERSION",
  3334. "NN_MODULE",
  3335. "ID_MATCH",
  3336. "FUNCTION_MATCH",
  3337. "CLASS_MATCH",
  3338. "MODULE_MATCH",
  3339. "CLOSURE_MATCH",
  3340. "WEAKREF_ALIVE",
  3341. )
  3342. def serialize_guards(
  3343. self,
  3344. builder: GuardBuilder,
  3345. sorted_guards: list[Guard],
  3346. output_graph: OutputGraphCommon,
  3347. ) -> bytes:
  3348. # We check whether our list of guards are serializable here
  3349. for guard in sorted_guards:
  3350. guard_type = guard.create_fn_name()
  3351. derived_guard_types = tuple(guard.guard_types) if guard.guard_types else ()
  3352. # BUILTIN_MATCH calls TYPE_MATCH sometimes, so we need to check both for
  3353. # a chance that the guard is unserializable
  3354. if guard_type in ("TYPE_MATCH", "BUILTIN_MATCH"):
  3355. if guard._unserializable:
  3356. # Only call builder.get again if we know we're going to throw
  3357. obj = builder.get(guard)
  3358. raise_local_type_error(obj)
  3359. elif (
  3360. guard_type in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES
  3361. ):
  3362. raise torch._dynamo.exc.PackageError(
  3363. f"{guard_type} guard cannot be serialized."
  3364. )
  3365. elif failed := next(
  3366. (
  3367. i
  3368. for i in derived_guard_types
  3369. if i in CheckFunctionManager.UNSUPPORTED_SERIALIZATION_GUARD_TYPES
  3370. ),
  3371. None,
  3372. ):
  3373. # Just raise the first failed guard name
  3374. raise torch._dynamo.exc.PackageError(
  3375. f"{failed} guard cannot be serialized."
  3376. )
  3377. builtins_dict_name = output_graph.name_of_builtins_dict_key_in_fglobals or ""
  3378. used_global_vars = set()
  3379. used_local_vars = set()
  3380. def prune_variable(source: Source) -> None:
  3381. if name := get_global_source_name(source):
  3382. assert isinstance(name, str)
  3383. # Leave out the builtins dict key, as we will special handle
  3384. # it later because the guarded code rarely use the entire
  3385. # builtin dict in the common case.
  3386. if name != builtins_dict_name:
  3387. used_global_vars.add(name)
  3388. elif name := get_local_source_name(source):
  3389. assert isinstance(name, str)
  3390. used_local_vars.add(name)
  3391. output_graph_guards_state = output_graph.dump_guards_state()
  3392. # Only serialize the global variables that are actually used in guards.
  3393. for guard in sorted_guards:
  3394. if isinstance(guard.originating_source, ShapeEnvSource):
  3395. assert self.shape_code_parts
  3396. for source in self.shape_code_parts.shape_env_sources:
  3397. prune_variable(source)
  3398. else:
  3399. prune_variable(guard.originating_source)
  3400. for source in output_graph.guard_on_key_order:
  3401. prune_variable(source)
  3402. def normalize_create_fn(x: Callable[..., None]) -> Callable[..., None]:
  3403. if isinstance(x, functools.partial):
  3404. def _ref(x: Any) -> Any:
  3405. if isinstance(x, (TensorWeakRef, weakref.ref)):
  3406. return x()
  3407. return x
  3408. new_args = tuple(_ref(a) for a in x.args)
  3409. new_keywords = {k: _ref(v) for k, v in x.keywords.items()}
  3410. return functools.partial(x.func, *new_args, **new_keywords)
  3411. return x
  3412. global_scope_state = {
  3413. k: v
  3414. for k, v in output_graph_guards_state.global_scope.items()
  3415. if k in used_global_vars or k in self.additional_used_global_vars
  3416. }
  3417. global_scope_state[builtins_dict_name] = {
  3418. k: v
  3419. for k, v in output_graph_guards_state.global_scope[
  3420. builtins_dict_name
  3421. ].items() # type: ignore[attr-defined]
  3422. if k in self.used_builtin_vars
  3423. }
  3424. output_graph_guards_state = dataclasses.replace(
  3425. output_graph_guards_state,
  3426. local_scope={
  3427. k: v
  3428. for k, v in output_graph_guards_state.local_scope.items()
  3429. if k in used_local_vars or k in self.additional_used_local_vars
  3430. },
  3431. global_scope=global_scope_state,
  3432. _guards=torch._guards.GuardsSet(
  3433. OrderedSet(
  3434. dataclasses.replace(
  3435. guard,
  3436. obj_weakref=None,
  3437. guarded_class_weakref=None,
  3438. create_fn=normalize_create_fn(guard.create_fn),
  3439. )
  3440. for guard in sorted_guards
  3441. )
  3442. ),
  3443. input_source_to_sizes_strides=pytree.tree_map(
  3444. convert_int_to_concrete_values,
  3445. output_graph_guards_state.input_source_to_sizes_strides,
  3446. ),
  3447. skip_guards_check=True,
  3448. )
  3449. guards_state = GuardsState(
  3450. output_graph=output_graph_guards_state,
  3451. shape_code_parts=self.shape_code_parts,
  3452. source_get_cache=builder.source_get_cache,
  3453. )
  3454. return pickle_guards_state(guards_state, builder.guard_tree_values)
  3455. def build_guards(
  3456. self,
  3457. sorted_guards: list[Guard],
  3458. existing_diff_guard_sources: OrderedSet[str],
  3459. f_code: types.CodeType,
  3460. output_graph: OutputGraphGuardsState,
  3461. save_guards: bool,
  3462. source_get_cache: Optional[dict[str, Any]] = None,
  3463. ) -> tuple[GuardBuilder, GuardManagerWrapper]:
  3464. guard_manager = GuardManagerWrapper()
  3465. guard_manager.diff_guard_sources = existing_diff_guard_sources
  3466. w_builder = None
  3467. def source_ref(source: Source) -> str:
  3468. guard_source = source.guard_source
  3469. if guard_source is GuardSource.CONSTANT:
  3470. # No need to track constants
  3471. return source.name
  3472. assert w_builder
  3473. r_builder = w_builder()
  3474. assert r_builder is not None
  3475. return r_builder.arg_ref(source.name)
  3476. builder = GuardBuilder(
  3477. f_code,
  3478. self.id_ref,
  3479. source_ref,
  3480. self.lookup_weakrefs,
  3481. output_graph.local_scope,
  3482. output_graph.global_scope,
  3483. guard_manager,
  3484. self,
  3485. save_guards,
  3486. runtime_global_scope=self.runtime_global_scope,
  3487. source_get_cache=source_get_cache,
  3488. )
  3489. # Break retain cycle. See test_release_scope_memory
  3490. def cleanup_builder(weak_b: weakref.ref[GuardBuilder]) -> None:
  3491. b = weak_b()
  3492. if b:
  3493. b.scope = None # type: ignore[assignment]
  3494. # Break retain cycle. See test_release_input_memory
  3495. w_builder = weakref.ref(builder, cleanup_builder)
  3496. guard_on_nn_modules = config.guard_nn_modules and justknobs_check(
  3497. "pytorch/compiler:guard_nn_modules"
  3498. )
  3499. for guard in sorted_guards:
  3500. if (
  3501. not guard_on_nn_modules
  3502. and guard.is_specialized_nn_module()
  3503. # Default func args must be guarded on.
  3504. # TODO: we could make use of 'DefaultsSource' and offer a .guard.is_defaults() API
  3505. and "__defaults__" not in guard.name
  3506. and "__kwdefaults__" not in guard.name
  3507. and (config.skip_nnmodule_hook_guards or "hooks" not in guard.name)
  3508. ):
  3509. continue
  3510. guard.create(builder)
  3511. return builder, guard_manager
  3512. def compile_check_fn(
  3513. self,
  3514. builder: GuardBuilder,
  3515. guards_out: list[Guard],
  3516. guard_fail_fn: Optional[Callable[[GuardFail], None]],
  3517. ) -> None:
  3518. # see parallel handling of ".0" / "___implicit0" in _eval_frame.c
  3519. largs = builder.argnames
  3520. largs += ["**___kwargs_ignored"]
  3521. guards_log.debug("GUARDS:")
  3522. code_parts = []
  3523. verbose_code_parts = []
  3524. structured_guard_fns: list[Callable[[], dict[str, Any]]] = []
  3525. # Add compile id info in the guard manager for debugging purpose
  3526. self.guard_manager.root.attach_compile_id(
  3527. str(CompileContext.current_compile_id())
  3528. )
  3529. # Clear references to torch_function modes held in the list
  3530. self.torch_function_mode_stack = None
  3531. def add_code_part(
  3532. code_part: str, guard: Optional[Guard], log_only: bool = False
  3533. ) -> None:
  3534. verbose_code_part = get_verbose_code_part(code_part, guard)
  3535. guards_log.debug("%s", verbose_code_part)
  3536. structured_guard_fns.append(
  3537. lambda: {
  3538. "code": code_part,
  3539. "stack": (
  3540. structured.from_traceback(guard.stack.summary())
  3541. if guard and guard.stack
  3542. else None
  3543. ),
  3544. "user_stack": (
  3545. structured.from_traceback(guard.user_stack)
  3546. if guard and guard.user_stack
  3547. else None
  3548. ),
  3549. }
  3550. )
  3551. if verbose_guards_log.isEnabledFor(logging.DEBUG):
  3552. maybe_stack = ""
  3553. maybe_user_stack = ""
  3554. if guard is not None:
  3555. if guard.stack:
  3556. maybe_stack = f"\nStack:\n{''.join(guard.stack.format())}"
  3557. if guard.user_stack:
  3558. maybe_user_stack = (
  3559. f"\nUser stack:\n{''.join(guard.user_stack.format())}"
  3560. )
  3561. verbose_guards_log.debug(
  3562. "Guard: %s%s%s",
  3563. code_part,
  3564. maybe_stack,
  3565. maybe_user_stack,
  3566. )
  3567. if not log_only:
  3568. code_parts.append(code_part)
  3569. verbose_code_parts.append(verbose_code_part)
  3570. seen = set()
  3571. for gcl in builder.code:
  3572. for code in gcl.code_list:
  3573. if code not in seen:
  3574. # If Cpp guard manager is enabled, we don't need to add to
  3575. # code_parts.
  3576. add_code_part(code, gcl.guard, True)
  3577. seen.add(code)
  3578. no_tensor_aliasing_names = builder.no_tensor_aliasing_names
  3579. check_tensors_fn = None
  3580. check_tensors_verbose_fn = None
  3581. if len(no_tensor_aliasing_names) > 1:
  3582. # Install tensor aliasing guard. TENSOR_MATCH guards are already
  3583. # installed for cpp guard manager.
  3584. install_no_tensor_aliasing_guard(
  3585. builder.no_tensor_aliasing_guard_managers,
  3586. no_tensor_aliasing_names,
  3587. ["check_no_aliasing(" + ", ".join(no_tensor_aliasing_names) + ")"],
  3588. )
  3589. # Note - On Lambda guarding of object aliasing
  3590. # We previously installed object-aliasing guards as relational guards,
  3591. # but that undermined the recursive-dict guard optimization: placing the
  3592. # aliasing guard at a leaf prevented the parent dict node from
  3593. # qualifying as a recursive-dict guard root. Because aliasing guards are
  3594. # rare, we now emit them as epilogue guards via a small Python lambda.
  3595. # This repeats the access in Python—adding a bit of work—but the
  3596. # overhead is outweighed by the gains from enabling recursive-dict guard
  3597. # optimization.
  3598. if (
  3599. config.use_lamba_guard_for_object_aliasing
  3600. and builder.object_aliasing_guard_codes
  3601. ):
  3602. aliasing_code_parts, aliasing_verbose_code_parts = map(
  3603. list, zip(*builder.object_aliasing_guard_codes)
  3604. )
  3605. builder.add_python_lambda_leaf_guard_to_root(
  3606. aliasing_code_parts, aliasing_verbose_code_parts
  3607. )
  3608. aotautograd_guards: list[GuardEnvExpr] = (
  3609. self.output_graph.aotautograd_guards if self.output_graph else []
  3610. )
  3611. # TODO(anijain2305) - There is a duplicate logic in Dynamo to find
  3612. # aliased input tensors. So most probably we don't need this here.
  3613. # Revisit.
  3614. for guard in aotautograd_guards:
  3615. if isinstance(guard, DuplicateInputs):
  3616. source_a = guard.input_source_a
  3617. source_b = guard.input_source_b
  3618. code_part = f"{source_a.name} is {source_b.name}"
  3619. install_object_aliasing_guard(
  3620. builder.get_guard_manager_from_source(source_a),
  3621. builder.get_guard_manager_from_source(source_b),
  3622. [code_part],
  3623. )
  3624. add_code_part(code_part, None, True)
  3625. elif isinstance(guard, StorageOverlap):
  3626. overlapping_guard_managers = [
  3627. builder.get_guard_manager_from_source(s)
  3628. for s in guard.overlapping_sources
  3629. ]
  3630. non_overlapping_guard_managers = [
  3631. builder.get_guard_manager_from_source(s)
  3632. for s in guard.non_overlapping_sources
  3633. ]
  3634. code_part = (
  3635. """check_overlapping("""
  3636. f"""overlapping=[{", ".join(s.name for s in guard.overlapping_sources)}], """
  3637. f"""non_overlapping=[{", ".join(s.name for s in guard.non_overlapping_sources)}])"""
  3638. )
  3639. install_storage_overlapping_guard(
  3640. overlapping_guard_managers,
  3641. non_overlapping_guard_managers,
  3642. [code_part],
  3643. )
  3644. add_code_part(code_part, None, True)
  3645. else:
  3646. raise RuntimeError(f"Unknown GuardEnvExpr: {guard}")
  3647. # TODO: the "guard" here is actually just the top level SHAPE_ENV
  3648. # which is useless. Get ShapeEnv to pass in more provenance.
  3649. for gcl in builder.shape_env_code:
  3650. for code in gcl.code_list:
  3651. # Shape env guards are already added for CPP guard manager in
  3652. # SHAPE_ENV implementation.
  3653. add_code_part(code, gcl.guard, True)
  3654. # OK, all done generating guards
  3655. if structured_guard_fns:
  3656. torch._logging.trace_structured(
  3657. "dynamo_guards", payload_fn=lambda: [f() for f in structured_guard_fns]
  3658. )
  3659. if convert_frame.initial_global_state is None:
  3660. # we should only hit this case in NopTests()
  3661. check_global_state = convert_frame.GlobalStateGuard().check
  3662. else:
  3663. check_global_state = getattr(self.global_state, "check", None)
  3664. closure_vars = {
  3665. "___check_tensors": check_tensors_fn,
  3666. "___check_tensors_verbose": check_tensors_verbose_fn,
  3667. "___check_global_state": check_global_state,
  3668. "___check_torch_function_mode_stack": self.torch_function_mode_stack_check_fn,
  3669. **SYMPY_INTERP,
  3670. **_get_closure_vars(),
  3671. }
  3672. self.guard_manager.finalize()
  3673. globals_for_guard_fn = {"G": builder.scope["G"]}
  3674. # Guard manager construction is complete. Ensure we did not miss to
  3675. # insert a guard in cpp guard manager.
  3676. assert len(code_parts) == 0
  3677. self.guard_manager.closure_vars = closure_vars
  3678. self.guard_manager.args = largs
  3679. self.guard_manager.populate_code_parts_for_debugging()
  3680. self.guard_manager.verbose_code_parts = verbose_code_parts
  3681. # Grab only G, but preserve "G" because guards access it as "G"
  3682. self.guard_manager.global_scope = globals_for_guard_fn
  3683. self.guard_manager.guard_fail_fn = guard_fail_fn
  3684. # will be populated by a non-owning reference to CacheEntry/ExtraState
  3685. # when the CacheEntry is constructed
  3686. self.guard_manager.cache_entry = None
  3687. self.guard_manager.extra_state = None
  3688. self.guard_manager.no_tensor_aliasing_sources = no_tensor_aliasing_names
  3689. def invalidate(self, obj_str: str) -> None:
  3690. # Some tests reveal that CheckFunctionManager has no attribute
  3691. # guard_manager, but this case should not be of any concern.
  3692. # This case doesn't seem easy to repro.
  3693. if (
  3694. hasattr(self, "guard_manager")
  3695. and not isinstance(self.guard_manager, DeletedGuardManagerWrapper)
  3696. and (cache_entry := self.guard_manager.cache_entry) is not None
  3697. and (extra_state := self.guard_manager.extra_state) is not None
  3698. ):
  3699. assert isinstance(cache_entry, CacheEntry)
  3700. assert isinstance(extra_state, ExtraState)
  3701. reason = f"Cache line invalidated because {obj_str} got deallocated"
  3702. deleted_guard_manager = DeletedGuardManagerWrapper(reason)
  3703. extra_state.invalidate(cache_entry, deleted_guard_manager)
  3704. self.guard_manager = deleted_guard_manager
  3705. def id_ref(self, obj: object, obj_str: str) -> int:
  3706. """add a weakref, return the id"""
  3707. try:
  3708. if id(obj) not in self._weakrefs:
  3709. # We will clear the _weakrefs dict at the end of __init__
  3710. # function, which will delete the callbacks as well. Therefore,
  3711. # we are using a finalizer which is kept alive.
  3712. self._weakrefs[id(obj)] = weakref.ref(obj)
  3713. weakref.finalize(
  3714. obj, functools.partial(self.invalidate, obj_str=obj_str)
  3715. )
  3716. except TypeError:
  3717. pass # cannot weakref bool object
  3718. return id(obj)
  3719. def lookup_weakrefs(self, obj: object) -> Optional[weakref.ref[object]]:
  3720. """Lookup the _weakrefs created in id_ref function for ID_MATCH'd objects"""
  3721. if id(obj) in self._weakrefs:
  3722. return self._weakrefs[id(obj)]
  3723. return None
  3724. def build_guard_function(code_parts: list[str], closure_args: str) -> tuple[str, str]:
  3725. from torch._inductor.utils import IndentedBuffer
  3726. csepass = PyExprCSEPass()
  3727. try:
  3728. csepass.count(code_parts)
  3729. def replace(expr: str) -> tuple[list[str], str]:
  3730. return csepass.replace(expr)
  3731. except RecursionError:
  3732. # If we hit recursion limits during CSE analysis, fall back to a no-op replace function
  3733. # This can happen with extremely complex guard expressions
  3734. def replace(expr: str) -> tuple[list[str], str]:
  3735. return [], expr
  3736. # Generate the inner body of the guard function.
  3737. # i.e. if-chain of the guard expressions.
  3738. guard_body = IndentedBuffer()
  3739. for expr in code_parts:
  3740. preface, expr = replace(expr)
  3741. guard_body.writelines(preface)
  3742. guard_body.writeline(f"if not ({expr}):")
  3743. with guard_body.indent():
  3744. guard_body.writeline("return False")
  3745. # Wrap the inner body into the actual guard function.
  3746. guard = IndentedBuffer()
  3747. guard.writeline("def guard(L):")
  3748. with guard.indent():
  3749. guard.splice(guard_body)
  3750. guard.writeline("return True")
  3751. # Wrap the whole guard function into another function
  3752. # with the closure variables.
  3753. make_guard_fn = IndentedBuffer()
  3754. make_guard_fn.writeline(f"def ___make_guard_fn({closure_args}):")
  3755. with make_guard_fn.indent():
  3756. make_guard_fn.splice(guard)
  3757. make_guard_fn.writeline("return guard")
  3758. return guard_body.getvalue(), make_guard_fn.getvalue()
  3759. def is_recompiles_enabled() -> bool:
  3760. return torch._logging._internal.log_state.is_artifact_enabled("recompiles")
  3761. def is_recompiles_verbose_enabled() -> bool:
  3762. return torch._logging._internal.log_state.is_artifact_enabled("recompiles_verbose")
  3763. # this will only be used if cpp guards are disabled
  3764. def make_torch_function_mode_stack_guard(
  3765. initial_stack: list[torch.overrides.TorchFunctionMode],
  3766. ) -> Callable[[], bool]:
  3767. types = [type(x) for x in initial_stack]
  3768. def check_torch_function_mode_stack() -> bool:
  3769. cur_stack = get_torch_function_mode_stack()
  3770. if len(cur_stack) != len(types):
  3771. return False
  3772. for ty, mode in zip(types, cur_stack):
  3773. if ty is not type(mode):
  3774. return False
  3775. return True
  3776. return check_torch_function_mode_stack
  3777. Scope = TypeAliasType("Scope", dict[str, object])
  3778. def recompilation_reason_for_no_tensor_aliasing_guard(
  3779. guard_manager: GuardManagerWrapper, scope: Scope
  3780. ) -> list[str]:
  3781. assert guard_manager.global_scope is not None
  3782. global_scope = dict(guard_manager.global_scope)
  3783. ids_to_source = collections.defaultdict(list)
  3784. for tensor_source in guard_manager.no_tensor_aliasing_sources:
  3785. global_scope["__compile_source__"] = tensor_source
  3786. tensor_id = id(eval(tensor_source, global_scope, scope))
  3787. ids_to_source[tensor_id].append(tensor_source)
  3788. duplicate_tensors = [
  3789. f"{ids_to_source[key]}" for key in ids_to_source if len(ids_to_source[key]) > 1
  3790. ]
  3791. reason = ", ".join(duplicate_tensors)
  3792. return [f"Duplicate tensors found: {reason}"]
  3793. def strip_local_scope(s: str) -> str:
  3794. """
  3795. Replace occurrences of L[...] with just the inner content.
  3796. Handles both single and double quotes.
  3797. This is to generate user friendly recompilation messages.
  3798. """
  3799. import re
  3800. pattern = r"L\[\s*['\"](.*?)['\"]\s*\]"
  3801. return re.sub(pattern, r"\1", s)
  3802. def get_guard_fail_reason_helper(
  3803. guard_manager: GuardManagerWrapper,
  3804. f_locals: dict[str, object],
  3805. compile_id: Optional[CompileId],
  3806. backend: Optional[Callable],
  3807. ) -> str:
  3808. """
  3809. Return the reason why `guard_manager` failed.
  3810. Updates `guard_failures` with the generated reason.
  3811. Only the first failed check of guard_manager is reported.
  3812. """
  3813. assert guard_manager.global_scope is not None
  3814. assert guard_manager.closure_vars is not None
  3815. scope = {"L": f_locals, "G": guard_manager.global_scope["G"]}
  3816. scope.update(guard_manager.closure_vars)
  3817. reasons: list[str] = []
  3818. cache_entry_backend = None
  3819. if guard_manager.cache_entry:
  3820. cache_entry_backend = guard_manager.cache_entry.backend
  3821. no_tensor_aliasing_check_failed = False
  3822. verbose_code_parts: list[str] = []
  3823. guard_debug_info = guard_manager.check_verbose(f_locals)
  3824. # For test_export_with_map_cond, the check_verbose fail even without the
  3825. # C++ guard manager. We need to fix the issue to remove the comment.
  3826. # assert not guard_debug_info.result
  3827. if not guard_debug_info.result:
  3828. verbose_code_parts = guard_debug_info.verbose_code_parts
  3829. # verbose_code_parts is either the actual reason (e.g. in case of
  3830. # TENSOR_MATCH) or it could be a list of verbose_code_part that we
  3831. # passed to the leaf guard at construction time. If its a list, we
  3832. # walk through this list and find the guard that failed. This is
  3833. # very important for symbolic shape guards which are currently
  3834. # installed as a lambda guard and can encompass a long list of code_parts.
  3835. if len(verbose_code_parts) == 1:
  3836. if "Duplicate tensor found" in verbose_code_parts[0]:
  3837. no_tensor_aliasing_check_failed = True
  3838. else:
  3839. reasons = verbose_code_parts
  3840. verbose_code_parts = []
  3841. elif cache_entry_backend != backend:
  3842. # None of the guard entries failed - a backend match issue
  3843. reason = (
  3844. "BACKEND_MATCH failure: torch.compile detected different backend callables."
  3845. " If this is unexpected, wrap your backend in functools.partial (or reuse the"
  3846. " same cached backend) to avoid creating a new backend function each time."
  3847. " More details: https://github.com/pytorch/pytorch/issues/168373"
  3848. )
  3849. reasons.append(reason)
  3850. else:
  3851. # Unexpected recompilation - points to a bug
  3852. reason = (
  3853. "Unexpected recompilation: runtime guards failed even though they passed"
  3854. " during recompilation-reason analysis."
  3855. " Please open an issue with a minimal repro:"
  3856. " https://github.com/pytorch/pytorch"
  3857. )
  3858. reasons.append(reason)
  3859. if no_tensor_aliasing_check_failed:
  3860. reasons = recompilation_reason_for_no_tensor_aliasing_guard(
  3861. guard_manager, scope
  3862. )
  3863. else:
  3864. for part in verbose_code_parts:
  3865. global_scope = dict(guard_manager.global_scope)
  3866. global_scope["__compile_source__"] = part
  3867. with report_compile_source_on_error():
  3868. try:
  3869. fail_reason = eval(part, global_scope, scope)
  3870. except Exception:
  3871. if is_recompiles_verbose_enabled():
  3872. continue
  3873. else:
  3874. raise
  3875. # Only ___check_tensors knows how to return a fancy fail reason;
  3876. # for everything else we just report the code that failed
  3877. if isinstance(fail_reason, bool) and not fail_reason:
  3878. fail_reason = part
  3879. if isinstance(fail_reason, str):
  3880. reasons.append(fail_reason)
  3881. if not is_recompiles_verbose_enabled():
  3882. break
  3883. reason_str = f"{compile_id}: " + "; ".join(reasons)
  3884. return strip_local_scope(reason_str)
  3885. def get_guard_fail_reason(
  3886. guard_manager: GuardManagerWrapper,
  3887. code: types.CodeType,
  3888. f_locals: dict[str, object],
  3889. compile_id: CompileId,
  3890. backend: Callable,
  3891. skip_logging: bool = False,
  3892. ) -> str:
  3893. if isinstance(guard_manager, DeletedGuardManagerWrapper):
  3894. return f"{compile_id}: {guard_manager.invalidation_reason}"
  3895. reason_str = get_guard_fail_reason_helper(
  3896. guard_manager, f_locals, compile_id, backend
  3897. )
  3898. if skip_logging:
  3899. return reason_str
  3900. guard_failures[orig_code_map[code]].append(reason_str)
  3901. try:
  3902. if guard_manager.guard_fail_fn is not None:
  3903. guard_manager.guard_fail_fn(
  3904. GuardFail(reason_str or "unknown reason", orig_code_map[code])
  3905. )
  3906. except Exception:
  3907. log.exception(
  3908. "Failure in guard_fail_fn callback - raising here will cause a NULL Error on guard eval",
  3909. )
  3910. return reason_str
  3911. def get_and_maybe_log_recompilation_reasons(
  3912. cache_entry: Optional[CacheEntry],
  3913. frame: DynamoFrameType,
  3914. backend: Callable,
  3915. skip_logging: bool = False,
  3916. ) -> list[str]:
  3917. """
  3918. Return the list of guard failure reasons using cache_entry.
  3919. Logs the recompilation reason if `recompiles` logging is enabled.
  3920. Raises a RecompileError if `config.error_on_recompile` is enabled.
  3921. """
  3922. reasons = []
  3923. while cache_entry is not None:
  3924. reason = get_guard_fail_reason(
  3925. cache_entry.guard_manager,
  3926. cache_entry.code,
  3927. frame.f_locals,
  3928. cache_entry.compile_id,
  3929. backend,
  3930. skip_logging,
  3931. )
  3932. if reason:
  3933. reasons.append(reason)
  3934. cache_entry = cache_entry.next
  3935. code = frame.f_code
  3936. if skip_logging:
  3937. return reasons
  3938. # at least one of "recompiles" or "recompiles_verbose" is enabled
  3939. do_recompiles_log = is_recompiles_enabled() or is_recompiles_verbose_enabled()
  3940. if do_recompiles_log or config.error_on_recompile:
  3941. if is_recompiles_verbose_enabled():
  3942. failures = "\n\n".join(
  3943. f"guard {i} failures:\n" + textwrap.indent(reason, "- ")
  3944. for i, reason in enumerate(reasons)
  3945. )
  3946. else:
  3947. failures = textwrap.indent("\n".join(reasons), "- ")
  3948. guard_failure_details = (
  3949. f"triggered by the following guard failure(s):\n{failures}"
  3950. )
  3951. message = (
  3952. f"Recompiling function {code.co_name} in {code.co_filename}:{code.co_firstlineno}\n"
  3953. f"{textwrap.indent(guard_failure_details, ' ')}"
  3954. )
  3955. if do_recompiles_log:
  3956. if is_recompiles_verbose_enabled():
  3957. recompiles_verbose_log.debug(message)
  3958. else:
  3959. recompiles_log.debug(message)
  3960. if config.error_on_recompile:
  3961. raise exc.RecompileError(message)
  3962. torch._logging.trace_structured(
  3963. "artifact",
  3964. metadata_fn=lambda: {
  3965. "name": "recompile_reasons",
  3966. "encoding": "json",
  3967. },
  3968. payload_fn=lambda: reasons,
  3969. )
  3970. return reasons
  3971. def update_diff_guard_managers_for_existing_cache_entries(
  3972. cache_entry: Optional[CacheEntry],
  3973. ) -> OrderedSet[str]:
  3974. first_cache_entry = cache_entry
  3975. # On the first pass, go through the cache entries and accumulate the diff
  3976. # guard sources. Different guard managers can fail with different sources.
  3977. # So, we collect all of them first.
  3978. acc_diff_guard_sources: OrderedSet[str] = OrderedSet()
  3979. while cache_entry is not None:
  3980. acc_diff_guard_sources.update(
  3981. cache_entry.guard_manager.collect_diff_guard_sources()
  3982. )
  3983. cache_entry = cache_entry.next # type: ignore[assignment]
  3984. # On the second pass, set the diff_guard_sources for each cache line to the
  3985. # accumulated value. And the re-populate the diff guard manager.
  3986. cache_entry = first_cache_entry
  3987. while cache_entry is not None:
  3988. cache_entry.guard_manager.diff_guard_sources = acc_diff_guard_sources
  3989. cache_entry.guard_manager.populate_diff_guard_manager()
  3990. cache_entry = cache_entry.next # type: ignore[assignment]
  3991. # return the accumulated sources to set up the new cache line.
  3992. return acc_diff_guard_sources
  3993. def guard_error_hook(
  3994. guard_manager: GuardFn,
  3995. code: types.CodeType,
  3996. f_locals: dict[str, object],
  3997. index: int,
  3998. last: bool,
  3999. ) -> None:
  4000. print(
  4001. f"ERROR RUNNING GUARDS {code.co_name} {code.co_filename}:{code.co_firstlineno}"
  4002. )
  4003. print("lambda " + ", ".join(guard_manager.args) + ":")
  4004. print(" ", " and\n ".join(guard_manager.code_parts))
  4005. print(guard_manager)
  4006. local_scope = {"L": f_locals, **guard_manager.closure_vars}
  4007. for guard in guard_manager.code_parts:
  4008. try:
  4009. eval(guard, guard_manager.global_scope, local_scope)
  4010. except: # noqa: B001,E722
  4011. print(f"Malformed guard:\n{guard}")
  4012. set_guard_error_hook(guard_error_hook)
  4013. def unique(seq: Sequence[T]) -> Generator[T, None, None]:
  4014. seen = set()
  4015. for x in seq:
  4016. if x not in seen:
  4017. yield x
  4018. seen.add(x)
  4019. def make_dupe_guard(
  4020. obj_source: Source, dupe_source: Source
  4021. ) -> Optional[functools.partial[Any]]:
  4022. # Note - we may end up in a situation where we invoke something like
  4023. # def fn(x, y)
  4024. # with fn(x, x)
  4025. # Prior to the addition of tracking to all relevant objects, we would handle this just fine by
  4026. # eagerly re-entering VB and rewrapping inputs, correctly creating graphargs and placeholders. However,
  4027. # with tracking on inputs, duplicate inputs or aliased relationships may end up getting erased here -
  4028. # In the fn(x, x) example call above look like a graph with a single input.
  4029. # In order to ensure that we do not reuse fn(x, x) for fn(x, y), we create a duplicate input guard.
  4030. # Note - we may not have a source, that is fine, it just means we had an object that is safe to have
  4031. # leave unsourced - like a local list created and discharged entirely within a local scope.
  4032. if dupe_source and dupe_source != obj_source:
  4033. ser_source_is_local = is_from_local_source(dupe_source)
  4034. source_is_local = is_from_local_source(obj_source)
  4035. if is_from_flatten_script_object_source(
  4036. dupe_source
  4037. ) or is_from_flatten_script_object_source(obj_source):
  4038. raise exc.UnsafeScriptObjectError(
  4039. f"{obj_source.name} is aliasing {dupe_source.name}. This is not supported."
  4040. f" Please do a clone for corresponding input."
  4041. )
  4042. # Note - both must be local, or global, or we will run afoul of a lack of merging in how we currently
  4043. # reconcile guards builder scopes in compile_check_fn. This technically means we miss a guard here,
  4044. # so maybe we should do this refactor before we land this...
  4045. # TODO(voz): Combine local and global guard builders.
  4046. if ser_source_is_local == source_is_local:
  4047. # Note - this is a little aggressive - these being duplicate input does not always matter.
  4048. # However, this should always be a sound guard to add here.
  4049. return functools.partial(GuardBuilder.DUPLICATE_INPUT, source_b=dupe_source)
  4050. return None
  4051. def install_guard(*guards: Guard, skip: int = 0) -> None:
  4052. """
  4053. Add dynamo guards to the current tracing context.
  4054. Args:
  4055. guards: guard(s) to add
  4056. skip: number of stack frames to ignore for debug stack trace
  4057. """
  4058. from torch._guards import TracingContext
  4059. collect_debug_stack = guards_log.isEnabledFor(
  4060. logging.DEBUG
  4061. ) or verbose_guards_log.isEnabledFor(logging.DEBUG)
  4062. add = TracingContext.get().guards_context.dynamo_guards.add
  4063. for guard in guards:
  4064. assert isinstance(guard, Guard)
  4065. if is_from_skip_guard_source(guard.originating_source):
  4066. continue
  4067. add(guard, collect_debug_stack=collect_debug_stack, skip=skip + 1)