guards.py 107 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703
  1. # mypy: allow-untyped-defs
  2. from __future__ import annotations
  3. import ast
  4. import builtins
  5. import collections
  6. import dataclasses
  7. import enum
  8. import functools
  9. import importlib
  10. import inspect
  11. import itertools
  12. import logging
  13. import math
  14. import os
  15. import re
  16. import sys
  17. import textwrap
  18. import types
  19. import weakref
  20. from inspect import currentframe, getframeinfo
  21. from typing import (
  22. Any,
  23. Callable,
  24. Dict,
  25. List,
  26. Optional,
  27. Set,
  28. Tuple,
  29. Type,
  30. TYPE_CHECKING,
  31. Union,
  32. )
  33. from weakref import ReferenceType
  34. try:
  35. import numpy as np
  36. except ModuleNotFoundError:
  37. np = None # type: ignore[assignment]
  38. import torch
  39. import torch.utils._device
  40. from torch._dynamo.source import (
  41. is_from_flatten_script_object_source,
  42. is_from_local_source,
  43. is_from_optimizer_source,
  44. TensorProperty,
  45. TensorPropertySource,
  46. )
  47. from torch._guards import (
  48. DuplicateInputs,
  49. Guard,
  50. GuardBuilderBase,
  51. GuardEnvExpr,
  52. GuardSource,
  53. Source,
  54. )
  55. from torch._logging import structured
  56. from torch.fx.experimental.symbolic_shapes import (
  57. EqualityConstraint,
  58. is_symbolic,
  59. SYMPY_INTERP,
  60. )
  61. from torch.utils._traceback import format_frame, report_compile_source_on_error
  62. from torch.utils.weak import TensorWeakRef
  63. from . import config, convert_frame, exc, mutation_guard
  64. from .eval_frame import set_guard_error_hook
  65. from .source import (
  66. AttrSource,
  67. ChainedSource,
  68. ConstDictKeySource,
  69. DefaultsSource,
  70. FlattenScriptObjectSource,
  71. FSDPNNModuleSource,
  72. GetItemSource,
  73. GlobalSource,
  74. GlobalStateSource,
  75. GlobalWeakRefSource,
  76. GradSource,
  77. LocalSource,
  78. NNModuleSource,
  79. NotNNModuleSource,
  80. NumpyTensorSource,
  81. ODictGetItemSource,
  82. OptimizerSource,
  83. ScriptObjectQualifiedNameSource,
  84. ShapeEnvSource,
  85. TupleIteratorGetItemSource,
  86. TypeSource,
  87. )
  88. from .types import CacheEntry, ExtraState, GuardedCode, GuardFail, GuardFn # noqa: F401
  89. from .utils import (
  90. common_constant_types,
  91. dict_keys_repr,
  92. guard_failures,
  93. istype,
  94. key_is_id,
  95. key_to_id,
  96. orig_code_map,
  97. tensor_always_has_static_shape,
  98. tuple_iterator_getitem,
  99. tuple_iterator_len,
  100. )
  101. if TYPE_CHECKING:
  102. from sympy import Symbol
  103. log = logging.getLogger(__name__)
  104. guards_log = torch._logging.getArtifactLogger(__name__, "guards")
  105. recompiles_log = torch._logging.getArtifactLogger(__name__, "recompiles")
  106. recompiles_verbose_log = torch._logging.getArtifactLogger(
  107. __name__, "recompiles_verbose"
  108. )
  109. verbose_guards_log = torch._logging.getArtifactLogger(__name__, "verbose_guards")
  110. TensorGuards = torch._C._dynamo.guards.TensorGuards
  111. check_obj_id = torch._C._dynamo.guards.check_obj_id
  112. check_type_id = torch._C._dynamo.guards.check_type_id
  113. dict_version = torch._C._dynamo.guards.dict_version
  114. RootGuardManager = torch._C._dynamo.guards.RootGuardManager
  115. DictGuardManager = torch._C._dynamo.guards.DictGuardManager
  116. install_tensor_aliasing_guard = torch._C._dynamo.guards.install_tensor_aliasing_guard
  117. install_no_tensor_aliasing_guard = (
  118. torch._C._dynamo.guards.install_no_tensor_aliasing_guard
  119. )
  120. class GuardManager:
  121. """
  122. A helper class that contains the root guard manager. An instance of this
  123. class is stored in the Dynamo cache entry, so that the cache entry can
  124. access the RootGuardManager stored in the "root" attribute and directly call
  125. the check_nopybind from C++.
  126. """
  127. def __init__(self):
  128. self.root = RootGuardManager()
  129. self.closure_vars = None
  130. self.args = None
  131. self.code_parts = None
  132. self.verbose_code_parts = None
  133. self.global_scope = None
  134. self.guard_fail_fn = None
  135. self.cache_entry = None
  136. self.extra_state = None
  137. self.id_matched_objs = None
  138. self.no_tensor_aliasing_sources = []
  139. def get_guard_lines(self, guard):
  140. guard_name = guard.__class__.__name__
  141. parts = guard.verbose_code_parts()
  142. parts = [guard_name + ": " + part for part in parts]
  143. return parts
  144. def get_manager_line(self, guard_manager, accessor_str=None):
  145. source = guard_manager.get_source()
  146. t = guard_manager.__class__.__name__
  147. s = t + ": source=" + source
  148. if accessor_str:
  149. s += ", " + accessor_str
  150. return s
  151. def construct_dict_manager_string(self, mgr, body):
  152. for idx, (key_mgr, val_mgr) in sorted(mgr.get_key_value_managers().items()):
  153. body.writeline(f"KeyValueManager pair at index={idx}")
  154. with body.indent():
  155. if key_mgr:
  156. body.writeline(f"KeyManager: {self.get_manager_line(key_mgr)}")
  157. self.construct_manager_string(key_mgr, body)
  158. if val_mgr:
  159. body.writeline(f"ValueManager: {self.get_manager_line(val_mgr)}")
  160. self.construct_manager_string(val_mgr, body)
  161. def construct_manager_string(self, mgr, body):
  162. with body.indent():
  163. for guard in mgr.get_leaf_guards():
  164. body.writelines(self.get_guard_lines(guard))
  165. # This works for both DictGuardManager and SubclassedDictGuardManager
  166. if isinstance(mgr, DictGuardManager):
  167. self.construct_dict_manager_string(mgr, body)
  168. # General case of GuardManager/RootGuardManager
  169. for accessor, child_mgr in zip(
  170. mgr.get_accessors(), mgr.get_child_managers()
  171. ):
  172. body.writeline(
  173. self.get_manager_line(child_mgr, f"accessed_by={accessor.repr()}")
  174. )
  175. self.construct_manager_string(child_mgr, body)
  176. def __str__(self):
  177. from torch._inductor.utils import IndentedBuffer
  178. class IndentedBufferWithPrefix(IndentedBuffer):
  179. def prefix(self):
  180. return "| " * (self._indent * self.tabwidth)
  181. def writeline(self, line, skip_prefix=False):
  182. if skip_prefix:
  183. super().writeline(line)
  184. else:
  185. super().writeline("+- " + line)
  186. body = IndentedBufferWithPrefix()
  187. body.tabwidth = 1
  188. body.writeline("", skip_prefix=True)
  189. body.writeline("TREE_GUARD_MANAGER:", skip_prefix=True)
  190. body.writeline("RootGuardManager")
  191. self.construct_manager_string(self.root, body)
  192. for guard in self.root.get_epilogue_lambda_guards():
  193. body.writelines(self.get_guard_lines(guard))
  194. return body.getvalue()
  195. def check(self, x):
  196. # Only needed for debugging purposes.
  197. return self.root.check(x)
  198. def check_verbose(self, x):
  199. # Only needed for debugging purposes.
  200. return self.root.check_verbose(x)
  201. def from_numpy(a):
  202. # If not numpy array, piggy back on e.g. tensor guards to check type
  203. return torch.as_tensor(a) if isinstance(a, (np.generic, np.ndarray)) else a
  204. # For user stack printing
  205. @functools.lru_cache(None)
  206. def uninteresting_files():
  207. import torch._dynamo.external_utils
  208. mods = [
  209. torch._dynamo.external_utils,
  210. ]
  211. return {inspect.getfile(m) for m in mods}
  212. CLOSURE_VARS = {
  213. "___check_type_id": check_type_id,
  214. "___check_obj_id": check_obj_id,
  215. "___odict_getitem": collections.OrderedDict.__getitem__,
  216. "___key_to_id": key_to_id,
  217. "___dict_version": dict_version,
  218. "___dict_contains": lambda a, b: a in b,
  219. "___tuple_iterator_len": tuple_iterator_len,
  220. "___tuple_iterator_getitem": tuple_iterator_getitem,
  221. "__math_isnan": math.isnan,
  222. "__numpy_isnan": None if np is None else np.isnan,
  223. "inf": float("inf"),
  224. "__load_module": importlib.import_module,
  225. "utils_device": torch.utils._device,
  226. "device": torch.device,
  227. "___from_numpy": from_numpy,
  228. "___as_tensor": torch.as_tensor,
  229. "torch": torch,
  230. "inspect": inspect,
  231. }
  232. if sys.version_info[:2] <= (3, 8):
  233. # [Note: Python Version <= 3.8]
  234. # This branch should be dropped when we drop support for Python 3.8.
  235. # Reason: 'ast.unparse' function was introduced in Python 3.9.
  236. try:
  237. import astunparse # type: ignore[import]
  238. def _ast_unparse(node: ast.AST) -> str:
  239. return astunparse.unparse(node).replace("\n", "")
  240. HAS_UNPARSE_FUNCTIONS = True
  241. except ImportError:
  242. HAS_UNPARSE_FUNCTIONS = False
  243. pass
  244. else:
  245. HAS_UNPARSE_FUNCTIONS = True
  246. def _ast_unparse(node: ast.AST) -> str:
  247. return ast.unparse(node).replace("\n", "")
  248. def strip_function_call(name):
  249. """
  250. "___odict_getitem(a, 1)" => "a"
  251. "a.layers[slice(2)][0]._xyz" ==> "a"
  252. "getattr(a.layers[slice(2)][0]._abc, '0')" ==> "a"
  253. "getattr(getattr(a.x[3], '0'), '3')" ==> "a"
  254. "a.layers[slice(None, -1, None)][0]._xyz" ==> "a"
  255. """
  256. # recursively find valid object name in function
  257. valid_name = re.compile("[A-Za-z_].*")
  258. curr = ""
  259. for char in name:
  260. if char in " (":
  261. curr = ""
  262. elif char in "),[]":
  263. if curr and curr != "None" and valid_name.match(curr):
  264. return strip_function_call(curr)
  265. else:
  266. curr += char
  267. return strip_getattr_getitem(name)
  268. def strip_getattr_getitem(name):
  269. """
  270. "a[1]" => "a"
  271. "a.foo" => "a"
  272. """
  273. return re.split(r"[.\[]", name)[0]
  274. def get_verbose_code_part(code_part: str, guard: Guard) -> str:
  275. extra = ""
  276. if guard.user_stack:
  277. for fs in reversed(guard.user_stack):
  278. if fs.filename not in uninteresting_files():
  279. extra = f" # {format_frame(fs, line=True)}"
  280. break
  281. elif guard.stack:
  282. extra = f" # {format_frame(guard.stack.summary()[-1])}"
  283. return f"{code_part:<60}{extra}"
  284. def get_verbose_code_parts(
  285. code_parts: Union[str | List[str]], guard: Guard
  286. ) -> List[str]:
  287. if not isinstance(code_parts, list):
  288. code_parts = [code_parts]
  289. return [get_verbose_code_part(code_part, guard) for code_part in code_parts]
  290. def convert_to_concrete_values(size_or_stride):
  291. converted: List[Optional[int]] = []
  292. for dim in size_or_stride:
  293. if not is_symbolic(dim):
  294. converted.append(dim)
  295. else:
  296. assert isinstance(dim, torch.SymInt)
  297. converted.append(dim.node.maybe_as_int())
  298. return converted
  299. def get_tensor_guard_code_part(value, name, sizes, strides):
  300. pytype = type(value)
  301. dispatch_key = (
  302. torch._C._dispatch_keys(value) | torch._C._dispatch_tls_local_include_set()
  303. ) - torch._C._dispatch_tls_local_exclude_set()
  304. dtype = value.dtype
  305. device_index = value.device.index
  306. requires_grad = value.requires_grad
  307. guard_str = (
  308. f"check_tensor({name}, {pytype.__qualname__}, {dispatch_key}, {dtype}, "
  309. f"device={device_index}, requires_grad={requires_grad}, size={sizes}, stride={strides})"
  310. )
  311. return guard_str
  312. def get_key_index(dct, key):
  313. return list(dct.keys()).index(key)
  314. def get_key_index_source(source, index):
  315. return f"list({source}.keys())[{index}]"
  316. @dataclasses.dataclass(frozen=True)
  317. class NNModuleAttrAccessorInfo:
  318. # Represents where is the attr name is present in the nn module attribute
  319. # access
  320. # Tells that the attribute can be accessed via __dict__
  321. present_in_generic_dict: bool = False
  322. # Either the actual name or _parameters/_buffers/_modules
  323. l1_key: Optional[str] = None
  324. # Actual paramter/buffer/submodule name
  325. l2_key: Optional[str] = None
  326. def getitem_on_dict_manager(
  327. source, base_guard_manager, base_example_value, example_value, guard_manager_enum
  328. ):
  329. base_source_name = source.base.name()
  330. source_name = source.name()
  331. if isinstance(source.index, ConstDictKeySource):
  332. index = source.index.index
  333. else:
  334. assert isinstance(base_example_value, dict)
  335. index = get_key_index(base_example_value, source.index)
  336. key_source = get_key_index_source(base_source_name, index)
  337. key_example_value = list(base_example_value.keys())[index]
  338. if isinstance(key_example_value, (int, str)):
  339. value_source = f"{base_source_name}[{key_example_value!r}]"
  340. else:
  341. value_source = f"{base_source_name}[{key_source}]"
  342. if not isinstance(source.index, ConstDictKeySource):
  343. # We have to insert a key manager guard here
  344. # TODO - source debug string is probably wrong here.
  345. base_guard_manager.get_key_manager(
  346. index=index,
  347. source=key_source,
  348. example_value=source.index,
  349. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  350. ).add_equals_match_guard(
  351. source.index, [f"{key_source} == {key_example_value!r}"]
  352. )
  353. return base_guard_manager.get_value_manager(
  354. index=index,
  355. source=value_source,
  356. example_value=example_value,
  357. guard_manager_enum=guard_manager_enum,
  358. )
  359. def match_on_id_for_tensor(guard):
  360. source = guard.originating_source
  361. return source.is_dict_key() and not isinstance(source, GradSource)
  362. # The ready to eval generated code (possibly multiple parts) for a guard, plus
  363. # the original guard object that created it for provenance
  364. @dataclasses.dataclass
  365. class GuardCodeList:
  366. code_list: List[str]
  367. guard: Guard
  368. class GuardManagerType(enum.Enum):
  369. GUARD_MANAGER = 1
  370. DICT_GUARD_MANAGER = 2
  371. DICT_SUBCLASS_GUARD_MANAGER = 3
  372. class GuardBuilder(GuardBuilderBase):
  373. def __init__(
  374. self,
  375. id_ref: Callable[[Any], str],
  376. source_ref: Callable[[Source], str],
  377. lookup_weakrefs: Callable[[object], ReferenceType[object]],
  378. local_scope: Dict[str, object],
  379. global_scope: Dict[str, object],
  380. guard_manager: Optional[GuardManager],
  381. check_fn_manager: CheckFunctionManager,
  382. ):
  383. self.id_ref = id_ref
  384. self.source_ref = source_ref
  385. self.lookup_weakrefs = lookup_weakrefs
  386. self.scope: Dict[str, Dict[str, object]] = {"L": local_scope, "G": global_scope}
  387. self.scope["__builtins__"] = builtins.__dict__.copy()
  388. for (
  389. name,
  390. package_module,
  391. ) in torch.package.package_importer._package_imported_modules.items():
  392. name = name.replace(">", "_").replace("<", "_").replace(".", "_dot_")
  393. # Write the package module into the scope so that we can import it
  394. self.scope["__builtins__"][name] = package_module
  395. # Write the demangled name to the scope so that we can use it
  396. self.scope[name] = package_module
  397. self.guard_manager = guard_manager
  398. self.argnames: List[str] = []
  399. # Code is python expression strings generated for each guard
  400. self.code: List[GuardCodeList] = []
  401. # shape_env_code is only used by builder and is used for
  402. # shape env code. This exists only because we need to make sure
  403. # shape env guards get run after tensor match guards (since the
  404. # tensor match guards make sure we actually have tensors)
  405. self.shape_env_code: List[GuardCodeList] = []
  406. # [Note - On Eager Tensor Guards]
  407. # Most of the time, we generate Python code in a guard to directly
  408. # check various properties. However, tensors are a bit special;
  409. # it is too slow to check their properties one-by-one in Python.
  410. # Instead, there is a C++ function TensorGuards.check which takes
  411. # all of the tensor arguments and checks them all against compile-time
  412. # examples entirely in C++. Thus, every time we process a
  413. # TENSOR_MATCH guard, we just add another entry to
  414. # tensor_check_names/tensor_check_examples, saying "for this local,
  415. # check it against this example", and it all ends up getting
  416. # swept up into a single call to ___check_tensors. Invariant:
  417. # len(tensor_check_names) == len(tensor_check_examples).
  418. # TODO: something here
  419. self.tensor_check_names: List[str] = []
  420. self.tensor_check_examples: List[torch.Tensor] = []
  421. self.tensor_check_guards: List[Guard] = []
  422. self.tensor_check_guard_managers: List[GuardManager] = []
  423. self.check_fn_manager: CheckFunctionManager = check_fn_manager
  424. # Collect the ids of dicts which need key order guarding. source_name is
  425. # not sufficient because for nn modules, we can have different sources
  426. # to access the same object - self._module["param"] is same as
  427. # self.param.
  428. self.key_order_guarded_dict_ids = set()
  429. for source_name in self.check_fn_manager.output_graph.guard_on_key_order:
  430. self.key_order_guarded_dict_ids.add(id(self.get(source_name)))
  431. # Keep track of weak references of objects with ID_MATCH guard. This
  432. # info is stored alongside optimized_code and check_fn and is used to
  433. # limit the number of cache entries with same ID_MATCH'd object.
  434. self.id_matched_objs: Dict[str, ReferenceType[object]] = {}
  435. # Save the guard managers to avoid repeatedly traversing sources.
  436. self._cached_guard_managers: Dict[
  437. str, torch._C._dynamo.guards.GuardManager
  438. ] = {}
  439. def guard_on_dict_keys_and_ignore_order(self, example_value, guard):
  440. dict_mgr = self.get_guard_manager(guard)
  441. if isinstance(dict_mgr, DictGuardManager):
  442. raise NotImplementedError(
  443. "Not expecting a DictGuardManager. Seems like Dynamo incorrectly "
  444. f"added the dict to tx.output.guard_on_key_order for {guard.name}"
  445. )
  446. # Iterate over the dicts and install a dict_getitem_manager.
  447. dict_source = guard.originating_source.name()
  448. for key in example_value.keys():
  449. value = example_value[key]
  450. value_source = GetItemSource(guard.originating_source, index=key)
  451. guard_manager_enum = self.get_guard_manager_type(
  452. value_source, example_value
  453. )
  454. dict_mgr.dict_getitem_manager(
  455. key=key,
  456. source=f"{dict_source}[{key!r}]",
  457. example_value=value,
  458. guard_manager_enum=guard_manager_enum,
  459. )
  460. def guard_on_dict_keys_and_order(self, value, guard):
  461. # Add key managers for the DictGuardManager. Then add either an
  462. # ID_MATCH or EQUALS_MATCH guard on the key.
  463. dict_mgr = self.get_guard_manager(guard)
  464. if not isinstance(dict_mgr, DictGuardManager):
  465. raise NotImplementedError(
  466. "Expecting a DictGuardManager. Seems like Dynamo forgot "
  467. f"to set the right guard manager enum for {guard.name}"
  468. )
  469. assert isinstance(dict_mgr, DictGuardManager)
  470. for idx, key in enumerate(value.keys()):
  471. key_source = get_key_index_source(guard.name, idx)
  472. key_manager = dict_mgr.get_key_manager(
  473. index=idx,
  474. source=key_source,
  475. example_value=key,
  476. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  477. )
  478. if key_is_id(key):
  479. # Install ID_MATCH guard
  480. id_val = self.id_ref(key)
  481. key_manager.add_id_match_guard(
  482. id_val,
  483. get_verbose_code_parts(
  484. f"__check_obj_id({key_source}, {id_val})", guard
  485. ),
  486. )
  487. else:
  488. # Install EQUALS_MATCH guard
  489. key_manager.add_equals_match_guard(
  490. key, get_verbose_code_parts(f"{key_source} == {key!r}", guard)
  491. )
  492. def getattr_on_nn_module(
  493. self,
  494. source,
  495. base_guard_manager,
  496. base_example_value,
  497. example_value,
  498. base_source_name,
  499. source_name,
  500. guard_manager_enum,
  501. ):
  502. """
  503. This tries to avoid calling the expensive nn module custom getattr method by
  504. checking if the attribute is accessible via __dict__. For attributes that
  505. are not accessible via __dict__ (like descriptors), we fallback to
  506. PyObject_GetAttr.
  507. There are two cases that we optimize for
  508. 1) attributes present directly in __dict__, e.g training.
  509. 2) parameters/buffers/modules - they can be accessed via _parameters,
  510. _buffers, _modules keys in __dict__. For example, mod.linear can be
  511. accessed as mod.__dict__["_parameters"]["linear"]
  512. The most common and expensive case for nn module guards is of type
  513. mod.submod1.submod2.submod3.training. We avoid the python getattr of nn
  514. modules by going through the __dict__.
  515. """
  516. def getitem_on_dict_mgr(
  517. mgr, key, source_name, base_example_value, example_value, guard_manager_enum
  518. ):
  519. if isinstance(mgr, DictGuardManager):
  520. # Case where the user code relies on key order, e.g.,
  521. # named_parameters
  522. index = get_key_index(base_example_value, key)
  523. # Install the key manager and add equals match guard
  524. key_source = f"list({source_name}.keys())[{index!r}]"
  525. mgr.get_key_manager(
  526. index=index,
  527. source=key_source,
  528. example_value=key,
  529. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  530. ).add_equals_match_guard(l2_key, [f"{key_source} == {l2_key!r}"])
  531. # Install the value manager
  532. return mgr.get_value_manager(
  533. index=index,
  534. source=source_name,
  535. example_value=example_value,
  536. guard_manager_enum=guard_manager_enum,
  537. )
  538. else:
  539. return mgr.dict_getitem_manager(
  540. key=key,
  541. source=source_name,
  542. example_value=example_value,
  543. guard_manager_enum=guard_manager_enum,
  544. )
  545. attr_name = source.member
  546. mod_dict = base_example_value.__dict__
  547. all_class_attribute_names: Set[str] = set()
  548. for x in inspect.getmro(base_example_value.__class__):
  549. all_class_attribute_names.update(x.__dict__.keys())
  550. accessor_info = NNModuleAttrAccessorInfo(False, None, None)
  551. if attr_name in mod_dict:
  552. accessor_info = NNModuleAttrAccessorInfo(True, attr_name, None)
  553. elif "_parameters" in mod_dict and attr_name in mod_dict["_parameters"]:
  554. accessor_info = NNModuleAttrAccessorInfo(True, "_parameters", attr_name)
  555. elif "_buffers" in mod_dict and attr_name in mod_dict["_buffers"]:
  556. accessor_info = NNModuleAttrAccessorInfo(True, "_buffers", attr_name)
  557. elif (
  558. attr_name not in all_class_attribute_names
  559. and "_modules" in mod_dict
  560. and attr_name in mod_dict["_modules"]
  561. ):
  562. # Check test_attr_precedence test - instance attributes always take precedence unless its an nn.Module.
  563. accessor_info = NNModuleAttrAccessorInfo(True, "_modules", attr_name)
  564. if not accessor_info.present_in_generic_dict:
  565. # The attribute can be accessed by __getattribute__ call, so rely on
  566. # PyObject_GetAttr
  567. return base_guard_manager.getattr_manager(
  568. attr=source.member,
  569. source=source_name,
  570. example_value=example_value,
  571. guard_manager_enum=guard_manager_enum,
  572. )
  573. else:
  574. assert accessor_info.l1_key
  575. l1_key = accessor_info.l1_key
  576. l2_key = accessor_info.l2_key
  577. # Set source strings for debug info
  578. mod_dict_source = f"{base_source_name}.__dict__"
  579. l1_source_name = l2_source_name = None
  580. l1_value = l2_value = None
  581. l1_guard_manager_enum = l2_guard_manager_enum = None
  582. if l2_key:
  583. l1_source = AttrSource(source.base, l1_key)
  584. l1_source_name = l1_source.name()
  585. l1_value = mod_dict[l1_key]
  586. # do not guard on key order for _parameters etc unless the user code
  587. # actually needs the key order (e.g. calling named_parameters)
  588. l1_guard_manager_enum = self.get_guard_manager_type(l1_source, l1_value)
  589. l2_source_name = source_name
  590. l2_value = example_value
  591. l2_guard_manager_enum = self.get_guard_manager_type(
  592. source, example_value
  593. )
  594. else:
  595. l1_source_name = source_name
  596. l1_value = example_value
  597. l1_guard_manager_enum = self.get_guard_manager_type(
  598. source, example_value
  599. )
  600. # Get __dict__ accessor. No need to guard on dict key order, so use base
  601. # Guard Manager
  602. mod_generic_dict_manager = base_guard_manager.get_generic_dict_manager(
  603. source=mod_dict_source,
  604. example_value=mod_dict,
  605. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  606. )
  607. l1_mgr = getitem_on_dict_mgr(
  608. mgr=mod_generic_dict_manager,
  609. key=l1_key,
  610. source_name=l1_source_name,
  611. base_example_value=mod_dict,
  612. example_value=l1_value,
  613. guard_manager_enum=l1_guard_manager_enum,
  614. )
  615. if l2_key:
  616. return getitem_on_dict_mgr(
  617. mgr=l1_mgr,
  618. key=l2_key,
  619. source_name=l2_source_name,
  620. base_example_value=l1_value,
  621. example_value=l2_value,
  622. guard_manager_enum=l2_guard_manager_enum,
  623. )
  624. return l1_mgr
  625. def requires_key_order_guarding(self, source):
  626. source_name = source.name()
  627. if source_name == "":
  628. return False
  629. obj_id = id(self.get(source_name))
  630. return obj_id in self.key_order_guarded_dict_ids
  631. def get_guard_manager_type(self, source, example_value):
  632. guard_manager_enum = GuardManagerType.GUARD_MANAGER
  633. if self.requires_key_order_guarding(source):
  634. assert isinstance(example_value, dict)
  635. # If keys method is not overriden, we can use PyDict_Next to get key
  636. # orderings. Read more in guards.cpp
  637. if type(example_value).keys is type({}).keys:
  638. guard_manager_enum = GuardManagerType.DICT_GUARD_MANAGER
  639. else:
  640. guard_manager_enum = GuardManagerType.DICT_SUBCLASS_GUARD_MANAGER
  641. return guard_manager_enum
  642. def manager_guards_on_keys(self, mgr_enum):
  643. return (
  644. mgr_enum == GuardManagerType.DICT_GUARD_MANAGER
  645. or mgr_enum == GuardManagerType.DICT_SUBCLASS_GUARD_MANAGER
  646. )
  647. def get_global_guard_manager(self):
  648. assert self.guard_manager # to make mypy happy
  649. return self.guard_manager.root.globals_dict_manager(
  650. f_globals=self.scope["G"],
  651. source="G",
  652. example_value=self.scope["G"],
  653. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  654. )
  655. def get_guard_manager_from_source(self, source):
  656. assert self.guard_manager # to make mypy happy
  657. root_guard_manager = self.guard_manager.root
  658. example_value = None
  659. source_name = source.name()
  660. if source_name != "" and source_name in self._cached_guard_managers:
  661. return self._cached_guard_managers[source_name]
  662. if source_name != "":
  663. example_value = self.get(source_name)
  664. guard_manager_enum = self.get_guard_manager_type(source, example_value)
  665. # Get base manager related information
  666. base_source_name = None
  667. base_example_value = None
  668. base_guard_manager = None
  669. base_guard_manager_enum = GuardManagerType.GUARD_MANAGER
  670. if isinstance(source, ChainedSource):
  671. base_source_name = source.base.name()
  672. base_example_value = self.get(base_source_name)
  673. base_guard_manager = self.get_guard_manager_from_source(source.base)
  674. base_guard_manager_enum = self.get_guard_manager_type(
  675. source.base, base_example_value
  676. )
  677. # Use istype instead of isinstance to check for exact type of source.
  678. if istype(source, LocalSource):
  679. # RootGuardManager accepts a dict but still its not a
  680. # DictGuardManager because we will eventually move to
  681. # fastlocals.
  682. out = root_guard_manager.dict_getitem_manager(
  683. key=source.local_name,
  684. source=source_name,
  685. example_value=example_value,
  686. guard_manager_enum=guard_manager_enum,
  687. )
  688. elif istype(source, GlobalSource):
  689. # Global manager accepts a dict but it is not a DictGuardManager
  690. # because globals dict is big and we typically guard on a very
  691. # selected items on globals.
  692. out = self.get_global_guard_manager().dict_getitem_manager(
  693. key=source.global_name,
  694. source=source_name,
  695. example_value=example_value,
  696. guard_manager_enum=guard_manager_enum,
  697. )
  698. elif istype(source, GlobalWeakRefSource):
  699. out = self.get_global_guard_manager().global_weakref_manager(
  700. global_name=source.global_name,
  701. source=source_name,
  702. example_value=example_value,
  703. guard_manager_enum=guard_manager_enum,
  704. )
  705. elif istype(source, GlobalStateSource):
  706. # Don't do anything here. We guard on global state completely in
  707. # C++. So just return the root mgr.
  708. return root_guard_manager
  709. elif istype(source, ShapeEnvSource):
  710. return root_guard_manager
  711. elif istype(source, TypeSource):
  712. assert base_guard_manager # to make mypy happy
  713. out = base_guard_manager.type_manager(
  714. source=source_name,
  715. example_value=example_value,
  716. guard_manager_enum=guard_manager_enum,
  717. )
  718. elif istype(
  719. source,
  720. (OptimizerSource, NNModuleSource, NotNNModuleSource, FSDPNNModuleSource),
  721. ):
  722. assert base_guard_manager # to make mypy happy
  723. out = base_guard_manager
  724. elif istype(source, GradSource):
  725. assert base_guard_manager # to make mypy happy
  726. out = base_guard_manager.grad_manager(
  727. source=source_name,
  728. example_value=example_value,
  729. guard_manager_enum=guard_manager_enum,
  730. )
  731. elif istype(source, AttrSource):
  732. assert base_guard_manager # to make mypy happy
  733. if isinstance(base_example_value, torch.nn.Module):
  734. out = self.getattr_on_nn_module(
  735. source,
  736. base_guard_manager,
  737. base_example_value,
  738. example_value,
  739. base_source_name,
  740. source_name,
  741. guard_manager_enum,
  742. )
  743. else:
  744. out = base_guard_manager.getattr_manager(
  745. attr=source.member,
  746. source=source_name,
  747. example_value=example_value,
  748. guard_manager_enum=guard_manager_enum,
  749. )
  750. elif istype(source, GetItemSource):
  751. assert base_guard_manager # to make mypy happy
  752. if isinstance(base_example_value, (dict, collections.OrderedDict)):
  753. # TODO(anijain2305) - Consider isolating GetItemSource and
  754. # DictGetItemSource (or maybe use ODictGetItemSource for
  755. # dicts) so that GetItemSource is only for non dict objects.
  756. if isinstance(base_guard_manager, DictGuardManager):
  757. assert self.manager_guards_on_keys(base_guard_manager_enum)
  758. out = getitem_on_dict_manager(
  759. source,
  760. base_guard_manager,
  761. base_example_value,
  762. example_value,
  763. guard_manager_enum,
  764. )
  765. else:
  766. if isinstance(source.index, ConstDictKeySource):
  767. raise RuntimeError(
  768. "Expecting clean index here. Likely Dynamo forgot to mark"
  769. " a dict as guard_on_key_order"
  770. )
  771. out = base_guard_manager.dict_getitem_manager(
  772. key=source.index,
  773. source=source_name,
  774. example_value=example_value,
  775. guard_manager_enum=guard_manager_enum,
  776. )
  777. elif isinstance(base_example_value, list) and not source.index_is_slice:
  778. out = base_guard_manager.list_getitem_manager(
  779. key=source.index,
  780. source=source_name,
  781. example_value=example_value,
  782. guard_manager_enum=guard_manager_enum,
  783. )
  784. elif isinstance(base_example_value, tuple) and not source.index_is_slice:
  785. out = base_guard_manager.tuple_getitem_manager(
  786. key=source.index,
  787. source=source_name,
  788. example_value=example_value,
  789. guard_manager_enum=guard_manager_enum,
  790. )
  791. else:
  792. index = source.index
  793. if source.index_is_slice:
  794. index = source.unpack_slice()
  795. out = base_guard_manager.getitem_manager(
  796. key=index,
  797. source=source_name,
  798. example_value=example_value,
  799. guard_manager_enum=guard_manager_enum,
  800. )
  801. elif istype(source, ODictGetItemSource):
  802. if isinstance(base_guard_manager, DictGuardManager):
  803. assert self.manager_guards_on_keys(base_guard_manager_enum)
  804. out = getitem_on_dict_manager(
  805. source,
  806. base_guard_manager,
  807. base_example_value,
  808. example_value,
  809. guard_manager_enum,
  810. )
  811. else:
  812. assert base_guard_manager # to make mypy happy
  813. out = base_guard_manager.dict_getitem_manager(
  814. key=source.index,
  815. source=source_name,
  816. example_value=example_value,
  817. guard_manager_enum=guard_manager_enum,
  818. )
  819. elif istype(source, DefaultsSource):
  820. assert base_guard_manager # to make mypy happy
  821. assert callable(base_example_value)
  822. if not source.is_kw:
  823. out = base_guard_manager.func_defaults_manager(
  824. source=base_source_name,
  825. example_value=base_example_value.__defaults__,
  826. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  827. ).getitem_manager(
  828. key=source.idx_key,
  829. source=source_name,
  830. example_value=example_value,
  831. guard_manager_enum=guard_manager_enum,
  832. )
  833. else:
  834. # kwdefauts is a dict, so use a DictGuardManager
  835. kwdefaults = base_example_value.__kwdefaults__
  836. assert base_source_name is not None
  837. kw_source = base_source_name + ".__kwdefaults__"
  838. # kwdefaults is a dict. No need to guard on dict order.
  839. dict_mgr = base_guard_manager.func_kwdefaults_manager(
  840. source=kw_source,
  841. example_value=kwdefaults,
  842. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  843. )
  844. assert not isinstance(dict_mgr, DictGuardManager)
  845. out = dict_mgr.dict_getitem_manager(
  846. key=source.idx_key,
  847. source=source_name,
  848. example_value=example_value,
  849. guard_manager_enum=guard_manager_enum,
  850. )
  851. elif istype(source, NumpyTensorSource):
  852. assert base_guard_manager # to make mypy happy
  853. out = base_guard_manager.lambda_manager(
  854. python_lambda=from_numpy,
  855. source=source_name,
  856. example_value=example_value,
  857. guard_manager_enum=guard_manager_enum,
  858. )
  859. elif istype(source, FlattenScriptObjectSource):
  860. assert base_guard_manager # to make mypy happy
  861. out = base_guard_manager.lambda_manager(
  862. python_lambda=lambda x: x.__obj_flatten__(),
  863. source=source_name,
  864. example_value=example_value,
  865. guard_manager_enum=guard_manager_enum,
  866. )
  867. elif istype(source, ScriptObjectQualifiedNameSource):
  868. assert base_guard_manager # to make mypy happy
  869. out = base_guard_manager.lambda_manager(
  870. python_lambda=lambda x: x._type().qualified_name(),
  871. source=source_name,
  872. example_value=example_value,
  873. guard_manager_enum=guard_manager_enum,
  874. )
  875. elif istype(source, TupleIteratorGetItemSource):
  876. assert base_guard_manager # to make mypy happy
  877. out = base_guard_manager.tuple_iterator_getitem_manager(
  878. index=source.index,
  879. source=source_name,
  880. example_value=example_value,
  881. guard_manager_enum=guard_manager_enum,
  882. )
  883. elif isinstance(source, ConstDictKeySource):
  884. if not isinstance(base_guard_manager, DictGuardManager):
  885. raise AssertionError(
  886. "ConstDictKeySource can only work on DictGuardManager"
  887. )
  888. out = base_guard_manager.get_key_manager(
  889. index=source.index,
  890. source=source_name,
  891. example_value=example_value,
  892. guard_manager_enum=guard_manager_enum,
  893. )
  894. else:
  895. raise AssertionError(
  896. f"missing guard manager builder {source} - {source.name()}"
  897. )
  898. self._cached_guard_managers[source.name()] = out
  899. return out
  900. def get_guard_manager(self, guard: Guard):
  901. return self.get_guard_manager_from_source(guard.originating_source)
  902. def add_python_lambda_leaf_guard_to_root(
  903. self,
  904. code_parts,
  905. verbose_code_parts,
  906. closure_vars=CLOSURE_VARS,
  907. is_epilogue=True,
  908. ):
  909. # Adds a lambda leaf guard to the root guard manager. It wraps the
  910. # code_parts in a function object which is then passed on to the leaf
  911. # guard.
  912. make_guard_fn_args = ", ".join(closure_vars.keys())
  913. guard_body, pycode = build_guard_function(code_parts, make_guard_fn_args)
  914. out: Dict[str, Any] = dict()
  915. globals_for_guard_fn = {"G": self.scope["G"]}
  916. exec(pycode, globals_for_guard_fn, out)
  917. guard_fn = out["___make_guard_fn"](*closure_vars.values())
  918. assert self.guard_manager # to make mypy happy
  919. if is_epilogue:
  920. # Epilogue guards are run after all the other guards have finished.
  921. # If epilogue guards contain a getattr or getitem access, one of the
  922. # other guards would fail preventing the epilogue guards to run.
  923. self.guard_manager.root.add_epilogue_lambda_guard(
  924. guard_fn, verbose_code_parts
  925. )
  926. else:
  927. self.guard_manager.root.add_lambda_guard(guard_fn, verbose_code_parts)
  928. # Warning: use this with care! This lets you access what the current
  929. # value of the value you are guarding on is. You probably don't want
  930. # to actually durably save this value though (because it's specific
  931. # to this frame!) Instead, you should be reading out some property
  932. # (like its type) which is what you permanently install into the
  933. # guard code.
  934. def get(self, name: str) -> Any:
  935. return eval(name, self.scope, CLOSURE_VARS)
  936. # Registers the usage of the source name referenced by the
  937. # string (or stored in the Guard) as being guarded upon. It's important
  938. # to call this before generating some code that makes use of 'guard',
  939. # because without this call, we won't actually bind the variable
  940. # you reference in the actual guard closure (oops!)
  941. def arg_ref(self, guard: Union[str, Guard]) -> str:
  942. name: str
  943. if isinstance(guard, str):
  944. name = guard
  945. else:
  946. name = guard.name
  947. base = strip_getattr_getitem(strip_function_call(name))
  948. if base not in self.argnames:
  949. if re.match(r"[a-zA-Z0-9_]+", base):
  950. if re.match(r"^\d+$", base):
  951. log.warning("invalid var name: %s", guard)
  952. self.argnames.append(base)
  953. return name
  954. def _guard_on_attribute(self, guard: Guard, attr_name: str, guard_fn):
  955. attr_source = AttrSource(guard.originating_source, attr_name)
  956. # Copy the stack info
  957. new_guard = Guard(
  958. attr_source, guard_fn, stack=guard.stack, user_stack=guard.user_stack
  959. )
  960. new_guard.create(self)
  961. # Note: the order of the guards in this file matters since we sort guards on the same object by lineno
  962. def HASATTR(self, guard: Guard):
  963. source = guard.originating_source
  964. if isinstance(source, NNModuleSource):
  965. source = source.base
  966. assert isinstance(source, AttrSource), f"invalid source {guard.name}"
  967. base_source = source.base
  968. base = base_source.name()
  969. attr = source.member
  970. ref = self.arg_ref(base)
  971. val = hasattr(self.get(base), attr)
  972. code = None
  973. if val:
  974. code = f"hasattr({ref}, {attr!r})"
  975. else:
  976. code = f"not hasattr({ref}, {attr!r})"
  977. self._set_guard_export_info(
  978. guard, [code], provided_guarded_object=self.get(base)
  979. )
  980. if config.enable_cpp_guard_manager:
  981. base_manager = self.get_guard_manager_from_source(base_source)
  982. if val:
  983. # Just install a getattr manager. GetAttrGuardAccessor itself
  984. # acts as hasattr guard.
  985. example_value = self.get(source.name())
  986. base_example_value = self.get(base)
  987. guard_manager_enum = self.get_guard_manager_type(source, example_value)
  988. # if the base value is nn.Module, check if we can speedup the
  989. # guard by going through __dict__ attrs.
  990. if isinstance(base_example_value, torch.nn.Module):
  991. return self.getattr_on_nn_module(
  992. source,
  993. base_manager,
  994. base_example_value,
  995. example_value,
  996. base,
  997. source.name(),
  998. guard_manager_enum,
  999. )
  1000. else:
  1001. base_manager.getattr_manager(
  1002. attr=attr,
  1003. source=guard.name,
  1004. example_value=example_value,
  1005. guard_manager_enum=guard_manager_enum,
  1006. )
  1007. else:
  1008. base_manager.add_no_hasattr_guard(
  1009. attr, get_verbose_code_parts(code, guard)
  1010. )
  1011. else:
  1012. self._produce_guard_code(guard, [code])
  1013. def NOT_PRESENT_IN_GENERIC_DICT(self, guard: Guard, attr=None) -> None:
  1014. assert attr is not None
  1015. ref = self.arg_ref(guard)
  1016. val = self.get(guard.name)
  1017. assert isinstance(val, torch.nn.Module)
  1018. base_manager = self.get_guard_manager(guard)
  1019. mod_dict_source = f"{guard.name}.__dict__"
  1020. mod_generic_dict_manager = base_manager.get_generic_dict_manager(
  1021. source=mod_dict_source,
  1022. example_value=val.__dict__,
  1023. guard_manager_enum=GuardManagerType.GUARD_MANAGER,
  1024. )
  1025. code = f"not ___dict_contains({attr!r}, {ref}.__dict__)"
  1026. mod_generic_dict_manager.add_dict_contains_guard(
  1027. False, attr, get_verbose_code_parts(code, guard)
  1028. )
  1029. def TYPE_MATCH(self, guard: Guard) -> None:
  1030. # ___check_type_id is same as `id(type(x)) == y`
  1031. t = type(self.get(guard.name))
  1032. obj_id = self.id_ref(t)
  1033. code = f"___check_type_id({self.arg_ref(guard)}, {obj_id})"
  1034. self._set_guard_export_info(guard, [code])
  1035. if config.enable_cpp_guard_manager:
  1036. self.get_guard_manager(guard).add_type_match_guard(
  1037. obj_id, get_verbose_code_parts(code, guard)
  1038. )
  1039. else:
  1040. self._produce_guard_code(guard, [code])
  1041. def DICT_VERSION(self, guard: Guard):
  1042. # ___check_dict_version is same as `dict_version(x) == y`
  1043. ref = self.arg_ref(guard)
  1044. val = self.get(guard.name)
  1045. version = dict_version(self.get(guard.name))
  1046. code = f"___dict_version({ref}) == {version}"
  1047. self._set_guard_export_info(guard, [code])
  1048. if config.enable_cpp_guard_manager:
  1049. # TODO(anijain2305) - Delete this when DictGuardManager uses tags
  1050. # for dicts.
  1051. self.get_guard_manager(guard).add_dict_version_guard(
  1052. val, get_verbose_code_parts(code, guard)
  1053. )
  1054. else:
  1055. self._produce_guard_code(guard, [code])
  1056. def DICT_CONTAINS(self, guard: Guard, key: str, invert: bool):
  1057. dict_ref = self.arg_ref(guard)
  1058. maybe_not = "not " if invert else ""
  1059. code = f"{maybe_not}___dict_contains({key!r}, {dict_ref})"
  1060. self._set_guard_export_info(guard, [code])
  1061. if config.enable_cpp_guard_manager:
  1062. self.get_guard_manager(guard).add_dict_contains_guard(
  1063. not invert, key, get_verbose_code_parts(code, guard)
  1064. )
  1065. else:
  1066. self._produce_guard_code(guard, [code])
  1067. def BOOL_FALSE(self, guard: Guard):
  1068. # Guard on the runtime value being 'False',
  1069. # can be faster than seemingly equivalent checks like DICT_KEYS for empty dict
  1070. #
  1071. # WARNING: this guard is not safe to use generally. It only works if the runtime
  1072. # value is of a type that supports bool(), and some types e.g. Tensor do not.
  1073. # Only use this guard in cases you can guarantee the runtime type will be friendly.
  1074. # (e.g. Specialized NNModule with mutation protection via setattr)
  1075. #
  1076. # Why not simply check the runtime type inside this guard? It's slow enough to defeat
  1077. # the purpose of using this guard, which itself is supposed to be a faster alternative
  1078. # to DICT_KEYS.
  1079. ref = self.arg_ref(guard)
  1080. code = f"not {ref}"
  1081. self._set_guard_export_info(guard, [code])
  1082. if config.enable_cpp_guard_manager:
  1083. # BOOL_FALSE is a weird guard. It is used to effectively check
  1084. # len(dict) == 0. Since it is used only and only for dicts, we don't
  1085. # have to anything here. DictGuardManager internally stores the size
  1086. # of the dict, and checks its size on every invocation. PyDict_Size
  1087. # is very fast, so we don't need BOOL_FALSE optimization. Just
  1088. # construct the dict guard manager to install a DictGuardManager.
  1089. self.get_guard_manager(guard)
  1090. else:
  1091. self._produce_guard_code(guard, [code])
  1092. def ID_MATCH(self, guard: Guard):
  1093. # ___check_obj_id is same as `id(x) == y`
  1094. if isinstance(guard.originating_source, TypeSource):
  1095. # optional optimization to produce cleaner/faster guard code
  1096. return self.TYPE_MATCH(
  1097. Guard(guard.originating_source.base, GuardBuilder.TYPE_MATCH) # type: ignore[arg-type]
  1098. )
  1099. ref = self.arg_ref(guard)
  1100. val = self.get(guard.name)
  1101. id_val = self.id_ref(val)
  1102. code = f"___check_obj_id({ref}, {id_val})"
  1103. self._set_guard_export_info(guard, [code])
  1104. if config.enable_cpp_guard_manager:
  1105. self.get_guard_manager(guard).add_id_match_guard(
  1106. id_val, get_verbose_code_parts(code, guard)
  1107. )
  1108. else:
  1109. self._produce_guard_code(guard, [code])
  1110. # Keep track of ID_MATCH'd objects. This will be used to modify the
  1111. # cache size logic
  1112. if isinstance(guard.originating_source, LocalSource):
  1113. # TODO(anijain2305) - This is currently restricted to nn.Module objects
  1114. # because many other ID_MATCH'd objects fail - like DeviceMesh.
  1115. # Increase the scope of ID_MATCH'd objects.
  1116. if isinstance(val, torch.nn.Module):
  1117. local_name = guard.originating_source.local_name
  1118. weak_id = self.lookup_weakrefs(val)
  1119. if weak_id is not None:
  1120. self.id_matched_objs[local_name] = weak_id
  1121. def NOT_NONE_MATCH(self, guard: Guard, value=None):
  1122. ref = self.arg_ref(guard)
  1123. val = self.get(guard.name)
  1124. assert isinstance(val, torch.Tensor)
  1125. code = f"{ref} is not None"
  1126. self._set_guard_export_info(guard, [code])
  1127. if config.enable_cpp_guard_manager:
  1128. self.get_guard_manager(guard).add_not_none_guard(
  1129. get_verbose_code_parts(code, guard)
  1130. )
  1131. else:
  1132. self._produce_guard_code(guard, [code])
  1133. def NAME_MATCH(self, guard: Guard):
  1134. self._guard_on_attribute(guard, "__name__", GuardBuilder.EQUALS_MATCH)
  1135. def DATA_PTR_MATCH(self, guard: Guard):
  1136. # Add a type check. C++ guard has the type check internally, so only
  1137. # enable it for Python guards.
  1138. if not config.enable_cpp_guard_manager:
  1139. self.TYPE_MATCH(guard)
  1140. obj = self.get(guard.name)
  1141. code = f"{self.arg_ref(guard)}.data_ptr() == {obj.data_ptr()}"
  1142. self._set_guard_export_info(guard, [code])
  1143. if config.enable_cpp_guard_manager:
  1144. self.get_guard_manager(guard).add_data_ptr_guard(
  1145. obj, get_verbose_code_parts(code, guard)
  1146. )
  1147. else:
  1148. self._produce_guard_code(guard, [code])
  1149. def DUAL_LEVEL(self, guard: Guard):
  1150. # Invalidate dual level if current dual level is different than the one
  1151. # in the fx graph
  1152. dual_level = torch.autograd.forward_ad._current_level
  1153. code = [f"torch.autograd.forward_ad._current_level == {dual_level}"]
  1154. self._set_guard_export_info(guard, [code])
  1155. if config.enable_cpp_guard_manager:
  1156. # TODO(anijain2305) - Consider this moving this guard to C++
  1157. forward_ad = torch.autograd.forward_ad
  1158. def fn(x):
  1159. return forward_ad._current_level == dual_level
  1160. assert self.guard_manager # to make mypy happy
  1161. self.guard_manager.root.add_lambda_guard(
  1162. fn, get_verbose_code_parts(code, guard)
  1163. )
  1164. else:
  1165. self._produce_guard_code(guard, code)
  1166. def FUNCTORCH_STACK_MATCH(self, guard: Guard):
  1167. # Invalidate functorch code if current level is different than
  1168. # the one when FX graph was generated
  1169. cis = torch._functorch.pyfunctorch.retrieve_all_functorch_interpreters()
  1170. states = [ci.get_state() for ci in cis]
  1171. code = [f"torch._functorch.pyfunctorch.compare_functorch_state({states})"]
  1172. self._set_guard_export_info(guard, code)
  1173. if config.enable_cpp_guard_manager:
  1174. # TODO(anijain2305) - Consider this moving this guard to C++
  1175. compare_fn = torch._functorch.pyfunctorch.compare_functorch_state
  1176. def fn(x):
  1177. return compare_fn(states)
  1178. assert self.guard_manager # to make mypy happy
  1179. self.guard_manager.root.add_lambda_guard(
  1180. fn, get_verbose_code_parts(code, guard)
  1181. )
  1182. else:
  1183. self._produce_guard_code(guard, code)
  1184. def EQUALS_MATCH(self, guard: Guard):
  1185. ref = self.arg_ref(guard)
  1186. val = self.get(guard.name)
  1187. t = type(val)
  1188. if np:
  1189. np_types: Tuple[Type[Any], ...] = (
  1190. np.int8,
  1191. np.int16,
  1192. np.int32,
  1193. np.int64,
  1194. np.uint8,
  1195. np.uint16,
  1196. np.uint32,
  1197. np.uint64,
  1198. np.float16,
  1199. np.float32,
  1200. np.float64,
  1201. )
  1202. else:
  1203. np_types = ()
  1204. ok_types = tuple(
  1205. common_constant_types
  1206. | {
  1207. type,
  1208. list,
  1209. tuple,
  1210. set,
  1211. frozenset,
  1212. slice,
  1213. range,
  1214. torch.Size,
  1215. *np_types,
  1216. }
  1217. )
  1218. if istype(val, dict):
  1219. assert all(
  1220. istype(x, ok_types) for x in itertools.chain(val.keys(), val.values())
  1221. )
  1222. else:
  1223. assert istype(
  1224. val,
  1225. ok_types,
  1226. ), f"Unexpected type {type(val)}, not in {ok_types}"
  1227. # Special case for nan because float("nan") == float("nan") evaluates to False
  1228. if istype(val, float) and math.isnan(val):
  1229. self.TYPE_MATCH(guard)
  1230. code = list()
  1231. code.append(f"__math_isnan({ref})")
  1232. self._set_guard_export_info(guard, code)
  1233. if config.enable_cpp_guard_manager:
  1234. self.get_guard_manager(guard).add_lambda_guard(
  1235. CLOSURE_VARS["__math_isnan"], get_verbose_code_parts(code, guard)
  1236. )
  1237. else:
  1238. self._produce_guard_code(guard, code)
  1239. return
  1240. # Python math library doesn't support complex nan, so we need to use numpy
  1241. if istype(val, complex) and np.isnan(val):
  1242. self.TYPE_MATCH(guard)
  1243. code = list()
  1244. code.append(f"__numpy_isnan({ref})")
  1245. self._set_guard_export_info(guard, code)
  1246. if config.enable_cpp_guard_manager:
  1247. self.get_guard_manager(guard).add_lambda_guard(
  1248. CLOSURE_VARS["__numpy_isnan"], get_verbose_code_parts(code, guard)
  1249. )
  1250. else:
  1251. self._produce_guard_code(guard, code)
  1252. return
  1253. if config.enable_cpp_guard_manager:
  1254. # Construct a debug string to put into the c++ equals match guard.
  1255. code = [f"{ref} == {val!r}"]
  1256. self.get_guard_manager(guard).add_equals_match_guard(
  1257. val, get_verbose_code_parts(code, guard)
  1258. )
  1259. self._set_guard_export_info(guard, code)
  1260. return
  1261. code = list()
  1262. # If matching equality against list/tuple, we must also check that
  1263. # the internal types match. (TODO: what about nested lists?)
  1264. if istype(val, (list, tuple)):
  1265. # NB: SEQUENCE_LENGTH takes care of the outer __check_type_id test
  1266. self.SEQUENCE_LENGTH(guard)
  1267. for idx, elem in enumerate(val):
  1268. code.append(
  1269. f"___check_type_id({ref}[{idx}], {self.id_ref(type(elem))})"
  1270. )
  1271. else:
  1272. # Add type check to prevent equality check between tensor and non-tensor.
  1273. self.TYPE_MATCH(guard)
  1274. if istype(val, torch.Size):
  1275. val = tuple(val)
  1276. # Code object can not be compared against their string representation
  1277. # I.e `eval(f"{compile('2+2','','exec')!r}")` raises SyntaxError
  1278. assert not istype(val, types.CodeType)
  1279. # TODO: It feels like it would be better to just implement our own
  1280. # equality test in C that handles all of the necessary type checking
  1281. # and NaN tests
  1282. code.append(f"{ref} == {val!r}")
  1283. self._produce_guard_code(guard, code)
  1284. self._set_guard_export_info(guard, code)
  1285. def CONSTANT_MATCH(self, guard: Guard):
  1286. val = self.get(guard.name)
  1287. if istype(val, (bool, type(None), types.CodeType)):
  1288. self.ID_MATCH(guard)
  1289. else:
  1290. self.EQUALS_MATCH(guard)
  1291. def NN_MODULE(self, guard: Guard):
  1292. self.ID_MATCH(guard)
  1293. val = self.get(guard.name)
  1294. if hasattr(val, "training"):
  1295. assert istype(val.training, bool)
  1296. self._guard_on_attribute(guard, "training", GuardBuilder.CONSTANT_MATCH)
  1297. else:
  1298. exc.unimplemented(f"Guard setup for uninitialized class {type(val)}")
  1299. def FUNCTION_MATCH(self, guard: Guard):
  1300. """things like torch.add and user defined functions"""
  1301. return self.ID_MATCH(guard)
  1302. def CLOSURE_MATCH(self, guard: Guard):
  1303. """matches a closure by __code__ id."""
  1304. val = self.get(guard.name)
  1305. # Strictly only want user-defined functions
  1306. if type(val) == types.FunctionType and hasattr(val, "__code__"):
  1307. self._guard_on_attribute(guard, "__code__", GuardBuilder.HASATTR)
  1308. self._guard_on_attribute(guard, "__code__", GuardBuilder.FUNCTION_MATCH)
  1309. else:
  1310. self.FUNCTION_MATCH(guard)
  1311. def BUILTIN_MATCH(self, guard: Guard):
  1312. return self.FUNCTION_MATCH(guard)
  1313. def PYMODULE_MATCH(self, guard: Guard):
  1314. return self.FUNCTION_MATCH(guard)
  1315. def SEQUENCE_LENGTH(self, guard):
  1316. # This guard is used to check lenght of PySequence objects like list,
  1317. # tuple, collections.deque etc
  1318. ref = self.arg_ref(guard)
  1319. value = self.get(guard.name)
  1320. t = type(value)
  1321. self.TYPE_MATCH(guard)
  1322. code = list()
  1323. if len(value) == 0:
  1324. code.append(f"not {ref}")
  1325. else:
  1326. code.append(f"len({ref}) == {len(value)}")
  1327. self._set_guard_export_info(guard, code)
  1328. if config.enable_cpp_guard_manager:
  1329. if isinstance(value, dict):
  1330. self.get_guard_manager(guard).add_dict_length_check_guard(
  1331. len(value), get_verbose_code_parts(code, guard)
  1332. )
  1333. else:
  1334. self.get_guard_manager(guard).add_length_check_guard(
  1335. len(value), get_verbose_code_parts(code, guard)
  1336. )
  1337. else:
  1338. self._produce_guard_code(guard, code)
  1339. def TUPLE_ITERATOR_LEN(self, guard):
  1340. ref = self.arg_ref(guard)
  1341. value = self.get(guard.name)
  1342. t = type(value)
  1343. if not config.enable_cpp_guard_manager:
  1344. # C++ guard already checks the type
  1345. self.TYPE_MATCH(guard)
  1346. code = list()
  1347. code.append(f"___tuple_iterator_len({ref}) == {tuple_iterator_len(value)}")
  1348. self._set_guard_export_info(guard, code)
  1349. if config.enable_cpp_guard_manager:
  1350. t = type(value)
  1351. obj_id = self.id_ref(t)
  1352. self.get_guard_manager(guard).add_tuple_iterator_length_guard(
  1353. tuple_iterator_len(value), obj_id, get_verbose_code_parts(code, guard)
  1354. )
  1355. else:
  1356. self._produce_guard_code(guard, code)
  1357. # TODO(voz): Deduplicate w/ AOTAutograd dupe input guards
  1358. def DUPLICATE_INPUT(self, guard, source_b):
  1359. ref_a = self.arg_ref(guard)
  1360. ref_b = self.arg_ref(source_b.name())
  1361. if is_from_optimizer_source(
  1362. guard.originating_source
  1363. ) or is_from_optimizer_source(source_b):
  1364. return
  1365. code = [f"{ref_b} is {ref_a}"]
  1366. self._set_guard_export_info(guard, code)
  1367. if config.enable_cpp_guard_manager:
  1368. install_tensor_aliasing_guard(
  1369. self.get_guard_manager(guard),
  1370. self.get_guard_manager_from_source(source_b),
  1371. get_verbose_code_parts(code, guard),
  1372. )
  1373. else:
  1374. self._produce_guard_code(guard, code)
  1375. def DICT_KEYS(self, guard):
  1376. # Guard on the keys and their order
  1377. ref = self.arg_ref(guard)
  1378. value = self.get(guard.name)
  1379. t = type(value)
  1380. self.TYPE_MATCH(guard)
  1381. code = list()
  1382. any_key_is_id = any(key_is_id(k) for k in value.keys())
  1383. const_keys_repr = dict_keys_repr(
  1384. key_to_id(value),
  1385. local=is_from_local_source(guard.originating_source),
  1386. )
  1387. if any_key_is_id:
  1388. code.append(f"___key_to_id({ref}) == {const_keys_repr}")
  1389. else:
  1390. code.append(f"list({ref}.keys()) == {const_keys_repr}")
  1391. self._set_guard_export_info(guard, code)
  1392. if config.enable_cpp_guard_manager:
  1393. if self.requires_key_order_guarding(guard.originating_source):
  1394. self.guard_on_dict_keys_and_order(value, guard)
  1395. else:
  1396. self.guard_on_dict_keys_and_ignore_order(value, guard)
  1397. else:
  1398. self._produce_guard_code(guard, code)
  1399. def WEAKREF_ALIVE(self, guard):
  1400. code = [f"{self.arg_ref(guard)} is not None"]
  1401. self._set_guard_export_info(guard, code)
  1402. if config.enable_cpp_guard_manager:
  1403. self.get_guard_manager(guard).add_not_none_guard(
  1404. get_verbose_code_parts(code, guard)
  1405. )
  1406. else:
  1407. self._produce_guard_code(guard, code)
  1408. def NN_MODULE_PARAM_NAMES(self, guard):
  1409. ref = self.arg_ref(guard)
  1410. value = self.get(guard.name)
  1411. t = type(value)
  1412. keys = {k for k, v in value.named_parameters()}
  1413. self.TYPE_MATCH(guard)
  1414. code = list()
  1415. code.append(f"{{k for k, v in {ref}.named_parameters()}} == {keys!r}")
  1416. self._set_guard_export_info(guard, code)
  1417. if config.enable_cpp_guard_manager:
  1418. # TODO(anijain2305) - Consider moving this guard to C++. anijain2305
  1419. # tried but unable to come up with a testcase that installs this
  1420. # guard.
  1421. def fn(x):
  1422. return {k for k, v in x.named_parameters()} == keys
  1423. self.get_guard_manager(guard).add_lambda_guard(
  1424. fn, get_verbose_code_parts(code, guard)
  1425. )
  1426. else:
  1427. self._produce_guard_code(guard, code)
  1428. def DICT_CONST_KEYS(self, guard):
  1429. """Constant keys match"""
  1430. ref = self.arg_ref(guard)
  1431. value = self.get(guard.name)
  1432. t = type(value)
  1433. if not config.enable_cpp_guard_manager:
  1434. # DictGuardManager supports TYPE_MATCH internally
  1435. self.TYPE_MATCH(guard)
  1436. code = list()
  1437. code.append(f"list({ref}.keys()) == {list(value.keys())!r}")
  1438. self._set_guard_export_info(guard, code)
  1439. if config.enable_cpp_guard_manager:
  1440. if self.requires_key_order_guarding(guard.originating_source):
  1441. self.guard_on_dict_keys_and_order(value, guard)
  1442. else:
  1443. self.guard_on_dict_keys_and_ignore_order(value, guard)
  1444. else:
  1445. self._produce_guard_code(guard, code)
  1446. def OBJECT_MUTATION(self, guard: Guard):
  1447. mutation_guard.watch(self.get(guard.name), self.check_fn_manager)
  1448. def GRAD_MODE(self, guard: Guard):
  1449. pass # we always guard on this via GlobalStateGuard()
  1450. def DETERMINISTIC_ALGORITHMS(self, guard: Guard):
  1451. pass # we always guard on this via GlobalStateGuard()
  1452. def TORCH_FUNCTION_STATE(self, guard: Guard):
  1453. pass # we always guard on this via GlobalStateGuard()
  1454. def DEFAULT_DEVICE(self, guard: Guard):
  1455. """Guard on CURRENT_DEVICE per torch.utils._device"""
  1456. assert guard.source is GuardSource.GLOBAL
  1457. import torch.utils._device as m
  1458. code = [f"utils_device.CURRENT_DEVICE == {m.CURRENT_DEVICE!r}"]
  1459. self._set_guard_export_info(guard, code)
  1460. if config.enable_cpp_guard_manager:
  1461. self.get_guard_manager(guard).add_default_device_guard(
  1462. get_verbose_code_parts(code, guard)
  1463. )
  1464. else:
  1465. self._produce_guard_code(guard, code)
  1466. def SHAPE_ENV(self, guard: Guard):
  1467. # Let's handle ShapeEnv guards. To do this, we will resolve
  1468. # shape variables to sources from tracked_fakes. This must happen after
  1469. # tensor checks.
  1470. assert guard.name == ""
  1471. output_graph = self.check_fn_manager.output_graph
  1472. # NB: self.output_graph can be None in the debug_nops tests
  1473. fs = output_graph.tracked_fakes
  1474. input_contexts = [a.symbolic_context for a in fs]
  1475. def get_sources(t_id, dim):
  1476. # Looks up base sources mapped to a tensor id and uses them to create
  1477. # sources for the corresponding tensor dimension.
  1478. return [
  1479. TensorPropertySource(source, TensorProperty.SIZE, dim)
  1480. for source in output_graph.tracked_fakes_id_to_source[t_id]
  1481. ]
  1482. if output_graph.export_constraints:
  1483. source_pairs: List[Tuple[Source, Source]] = []
  1484. derived_equalities: List[ # type: ignore[type-arg]
  1485. Tuple[Source, Union[Source, Symbol], Callable]
  1486. ] = []
  1487. phantom_symbols: Dict[str, Symbol] = {}
  1488. for constraint in output_graph.export_constraints:
  1489. if constraint.t_id in output_graph.tracked_fakes_id_to_source:
  1490. torch.export.dynamic_shapes._process_equalities(
  1491. constraint,
  1492. get_sources,
  1493. output_graph.shape_env,
  1494. source_pairs,
  1495. derived_equalities,
  1496. phantom_symbols,
  1497. )
  1498. else:
  1499. log.warning("Untracked tensor used in export constraints")
  1500. equalities_inputs = EqualityConstraint(
  1501. source_pairs=source_pairs,
  1502. derived_equalities=derived_equalities,
  1503. phantom_symbols=list(phantom_symbols.values()),
  1504. warn_only=False,
  1505. )
  1506. else:
  1507. equalities_inputs = None
  1508. guards = output_graph.shape_env.produce_guards(
  1509. [a.fake for a in fs],
  1510. [a.source for a in fs],
  1511. input_contexts=input_contexts,
  1512. equalities_inputs=equalities_inputs,
  1513. source_ref=self.source_ref,
  1514. # Export keeps static.
  1515. ignore_static=(not self.check_fn_manager.output_graph.export),
  1516. )
  1517. # When exporting, we may work with the shape constraints some more in
  1518. # postprocessing, so don't freeze yet
  1519. if not self.check_fn_manager.output_graph.export:
  1520. output_graph.shape_env.freeze()
  1521. for shape_guard in guards:
  1522. self._set_guard_export_info(guard, [shape_guard])
  1523. if config.enable_cpp_guard_manager:
  1524. # Install all the symbolic guards in one lambda guard. These are run
  1525. # at the very end of the RootGuardManager via epilogue guards.
  1526. # TODO(anijain2305,williamwen42) - Consider moving this to C++.
  1527. code_parts = guards
  1528. self.add_python_lambda_leaf_guard_to_root(
  1529. code_parts,
  1530. get_verbose_code_parts(code_parts, guard),
  1531. closure_vars={**SYMPY_INTERP, **CLOSURE_VARS},
  1532. )
  1533. else:
  1534. for shape_guard in guards:
  1535. self._produce_guard_code(guard, [shape_guard], shape_env=True)
  1536. def TENSOR_MATCH(self, guard: Guard, value=None):
  1537. # For tensors that are part of the Dynamo extracted Fx graph module, an
  1538. # ID_MATCH suffices. Once we turn on inline_inbuilt_nn_modules, these
  1539. # will be lifted as inputs and have a TENSOR_MATCH guard.
  1540. # For FSDP modules, we must use TENSOR_MATCH because FSDP module is
  1541. # traced using UnspecializedNNModuleVariable and therefore lifts the
  1542. # params as inputs.
  1543. # For numpy tensors, always use TENSOR_MATCH because __from_numpy leads
  1544. # to a new tensor everytime and therefore id differs.
  1545. if (
  1546. guard.is_nn_module()
  1547. and not guard.is_fsdp_module()
  1548. and not isinstance(guard.originating_source, NumpyTensorSource)
  1549. ) or match_on_id_for_tensor(guard):
  1550. self.ID_MATCH(guard)
  1551. else:
  1552. if isinstance(value, TensorWeakRef):
  1553. value = value()
  1554. value = value if value is not None else self.get(guard.name)
  1555. assert isinstance(value, torch.Tensor)
  1556. tensor_name = self.arg_ref(guard)
  1557. # [Note - On Export Tensor Guards]
  1558. #
  1559. # In eager mode, tensor guards are evaluated through C++, in guards.cpp
  1560. # see [Note - On Eager Tensor Guards] for more info.
  1561. #
  1562. # In export mode, we instead maintain parallel logic between C++ and python
  1563. # here, with an exception of checking the dispatch key - with the idea that a dispatch key
  1564. # is an entirely runtime notion that would make no sense to keep in an exported graph.
  1565. #
  1566. # Now, this idea is okay, but to paraphrase @ezyang, this mental model is sufficient for now, although
  1567. # not entirely true.
  1568. # For example, suppose one of the input tensors had the negative dispatch key.
  1569. # You should end up with a graph that is specialized for tensors that have a negative dispatch key.
  1570. # If you allow a Tensor that does NOT have this bit set, you will accidentally run it "as if" it were negated.
  1571. # Now, negative key only shows up for complex numbers, and most likely, the exported to target doesn't
  1572. # support this feature at all, but the point stands that :some: tensor state only shows up on dispatch key.
  1573. # TODO(voz): Either populate a dispatch_key check into the guards, or error on users passing in an unsupported
  1574. # subset of keys during export.
  1575. #
  1576. # The list of tensor fields and calls we care about can be found in `terms` below.
  1577. # TODO(voz): We are missing storage offset in all our tensor guards?
  1578. code: List[str] = list()
  1579. if self.check_fn_manager.output_graph.export:
  1580. self.TYPE_MATCH(guard)
  1581. terms = [
  1582. "dtype",
  1583. "device",
  1584. "requires_grad",
  1585. "ndimension()",
  1586. ]
  1587. for term in terms:
  1588. real_value = self.get(tensor_name + "." + term)
  1589. if istype(real_value, (torch.device, torch.dtype)):
  1590. # copy pasted from EQUALS_MATCH
  1591. code.append(f"str({tensor_name}.{term}) == {str(real_value)!r}")
  1592. else:
  1593. code.append(f"{tensor_name}.{term} == {real_value}")
  1594. else:
  1595. self.tensor_check_examples.append(value)
  1596. self.tensor_check_names.append(tensor_name)
  1597. self.tensor_check_guards.append(guard)
  1598. if config.enable_cpp_guard_manager:
  1599. guard_manager = self.get_guard_manager(guard)
  1600. # Keep track of all the tensor guard managers to insert
  1601. # NoAliasing check at the end.
  1602. self.tensor_check_guard_managers.append(guard_manager)
  1603. output_graph = self.check_fn_manager.output_graph
  1604. metadata = output_graph.input_source_to_sizes_strides[
  1605. guard.originating_source
  1606. ]
  1607. size = convert_to_concrete_values(metadata["size"])
  1608. stride = convert_to_concrete_values(metadata["stride"])
  1609. verbose_code_parts = get_verbose_code_parts(
  1610. get_tensor_guard_code_part(value, tensor_name, size, stride),
  1611. guard,
  1612. )
  1613. guard_manager.add_tensor_match_guard(
  1614. value,
  1615. size,
  1616. stride,
  1617. tensor_name,
  1618. verbose_code_parts,
  1619. )
  1620. # A frame is valid for reuse with dynamic dimensions if the new
  1621. # (user-requested) dynamic dimensions are a subset of the old
  1622. # (already compiled) dynamic dimensions.
  1623. #
  1624. # It's a little non-obvious why you'd want this: in particular,
  1625. # if an already compiled frame matches all of the guards, why
  1626. # not just use it, why force a recompile?
  1627. #
  1628. # We force it for two reasons:
  1629. #
  1630. # - The user *required* us to compile with a new dynamic dimension,
  1631. # we should not ignore that and serve up the old, specialized
  1632. # frame. Listen to the user!
  1633. #
  1634. # - In fact, we are obligated to *raise an error* if we fail to
  1635. # make the requested dimension dynamic. If we don't
  1636. # recompile, we can't tell if that dimension can actually be
  1637. # made dynamic.
  1638. #
  1639. # If the new dynamic dims are a subset of the old, we already know
  1640. # we can make them dynamic (since we made them dynamic in old).
  1641. # This is slightly unsound, because maybe your input size is
  1642. # [s0, s0, s1] and so you can do it dynamic if you say dynamic
  1643. # dims {0, 1, 2} but you can't if you only do {0, 2} (because now
  1644. # the second s0 is specialized). But we're not entirely sure if
  1645. # this is a good idea anyway lol... (if you want to try removing
  1646. # this logic, be my guest! -- ezyang 2024)
  1647. #
  1648. assert guard.source is not None
  1649. static, reason = tensor_always_has_static_shape(
  1650. value, is_tensor=True, guard_source=guard.source
  1651. )
  1652. if not static:
  1653. if hasattr(value, "_dynamo_dynamic_indices"):
  1654. dynamic_indices = value._dynamo_dynamic_indices
  1655. code_part = f"(({tensor_name}._dynamo_dynamic_indices.issubset({dynamic_indices})) if hasattr({tensor_name}, '_dynamo_dynamic_indices') else True)" # noqa: B950
  1656. code.append(code_part)
  1657. if config.enable_cpp_guard_manager:
  1658. self.get_guard_manager(guard).add_dynamic_indices_guard(
  1659. dynamic_indices, get_verbose_code_parts(code_part, guard)
  1660. )
  1661. # In the case of us not having any dynamic dimension indices, we compiled the frame with no chance of
  1662. # raising for this specific tensor - and any inputs with more dynamic user directives specified must be recompiled.
  1663. else:
  1664. code_part = (
  1665. f"hasattr({tensor_name}, '_dynamo_dynamic_indices') == False"
  1666. )
  1667. code.append(code_part)
  1668. if config.enable_cpp_guard_manager:
  1669. self.get_guard_manager(guard).add_no_hasattr_guard(
  1670. "_dynamo_dynamic_indices",
  1671. get_verbose_code_parts(code_part, guard),
  1672. )
  1673. if len(code) > 0:
  1674. self._set_guard_export_info(guard, code)
  1675. if not config.enable_cpp_guard_manager:
  1676. self._produce_guard_code(guard, code)
  1677. # A util that appends guarded code
  1678. def _produce_guard_code(self, guard, code_list, shape_env=False):
  1679. assert not config.enable_cpp_guard_manager
  1680. if shape_env:
  1681. self.shape_env_code.append(GuardCodeList(code_list, guard))
  1682. else:
  1683. self.code.append(GuardCodeList(code_list, guard))
  1684. # A util that in the case of export, adds data onto guards
  1685. def _set_guard_export_info(self, guard, code_list, provided_guarded_object=None):
  1686. # WARNING: It is important that cur_frame/caller do NOT stay in
  1687. # the current frame, because they will keep things live longer
  1688. # than they should. See TestMisc.test_release_module_memory
  1689. cur_frame = currentframe()
  1690. assert cur_frame is not None
  1691. caller = cur_frame.f_back
  1692. del cur_frame
  1693. assert caller is not None
  1694. func_name = getframeinfo(caller)[2]
  1695. del caller
  1696. # We use func_name for export, so might as well get a nice defensive check out of it
  1697. assert func_name in dir(
  1698. self.__class__
  1699. ), f"_produce_guard_code must be called from inside GuardedCode. Called from {func_name}"
  1700. # Not all guards have names, some can be installed globally (see asserts on HAS_GRAD)
  1701. if provided_guarded_object is None:
  1702. name_valid = guard.name is not None and guard.name != ""
  1703. guarded_object = self.get(guard.name) if name_valid else None
  1704. else:
  1705. guarded_object = provided_guarded_object
  1706. guarded_object_type = (
  1707. weakref.ref(type(guarded_object)) if guarded_object is not None else None
  1708. )
  1709. obj_ref = None
  1710. # Not necessary to have weakref for Enum type, but there is a bug that
  1711. # makes hasattr(guarded_object.__class__, "__weakref__") return True.
  1712. if hasattr(guarded_object.__class__, "__weakref__") and not isinstance(
  1713. guarded_object, enum.Enum
  1714. ):
  1715. obj_ref = weakref.ref(guarded_object)
  1716. guard.set_export_info(
  1717. func_name,
  1718. guarded_object_type,
  1719. code_list,
  1720. obj_ref,
  1721. )
  1722. # Common Sub-Expression Elimination for Python expressions.
  1723. #
  1724. # There are 2 steps to this pass:
  1725. # 1. Count the frequency of each sub-expression (i.e. inner
  1726. # node in the AST tree)
  1727. #
  1728. # 2. Replace those that occur more than once by a fresh variable 'v'.
  1729. # 'v' will be defined in the 'preface' list (output argument to
  1730. # 'NodeTransformer')
  1731. #
  1732. # NB: the use of 'ast.unparse' while visiting the nodes makes this pass
  1733. # quadratic on the depth of the tree.
  1734. #
  1735. # NB: this pass creates a new variable for each AST node that is repeated
  1736. # more than 'USE_THRESHOLD'. e.g. if 'a.b.c.d' is used 10 times, 'a.b.c'
  1737. # and 'a.b' are also used 10 times. So, there will be a new variable for
  1738. # each of them.
  1739. class PyExprCSEPass:
  1740. # Maximum number of times a given expression can be used without being
  1741. # replaced by a fresh variable.
  1742. USE_THRESHOLD = 1
  1743. # Ad-Hoc: AST nodes this pass focuses on.
  1744. ALLOWED_NODE_TYPES = (ast.Attribute, ast.Call, ast.Subscript)
  1745. @dataclasses.dataclass
  1746. class Config:
  1747. expr_count: Dict[str, int]
  1748. expr_to_name: Dict[str, str]
  1749. class ExprCounter(ast.NodeVisitor):
  1750. def __init__(self, config: PyExprCSEPass.Config) -> None:
  1751. self._config = config
  1752. def visit(self, node: ast.AST) -> Any:
  1753. if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES):
  1754. self._config.expr_count[_ast_unparse(node)] += 1
  1755. super().visit(node)
  1756. class Replacer(ast.NodeTransformer):
  1757. def __init__(
  1758. self,
  1759. config: PyExprCSEPass.Config,
  1760. gen_name: Callable[[], str],
  1761. ) -> None:
  1762. super().__init__()
  1763. self._config = config
  1764. self._gen_name = gen_name
  1765. self.preface: List[str] = []
  1766. def visit(self, node: ast.AST) -> Any:
  1767. if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES):
  1768. expr = _ast_unparse(node)
  1769. # Replacement only occurs if a given expression is used more
  1770. # than once.
  1771. if self._config.expr_count[expr] > PyExprCSEPass.USE_THRESHOLD:
  1772. if expr not in self._config.expr_to_name:
  1773. # Parent 'visit' is called so that we CSE the inner expressions first.
  1774. #
  1775. # The resulting expression is used as right-hand-side of the variable
  1776. # assignment. i.e. we are CSE-ing the children before the parents.
  1777. #
  1778. # Indexing still uses the old 'node', since that's what was counted
  1779. # by the 'NodeVisitor'.
  1780. node_ = super().visit(node)
  1781. expr_ = _ast_unparse(node_)
  1782. var_name = self._gen_name()
  1783. self.preface.append(f"{var_name} = {expr_}")
  1784. self._config.expr_to_name[expr] = var_name
  1785. else:
  1786. var_name = self._config.expr_to_name[expr]
  1787. return ast.Name(var_name, ast.Load())
  1788. return super().visit(node)
  1789. def __init__(self) -> None:
  1790. self._counter = 0
  1791. self._config = self.Config(
  1792. expr_count=collections.defaultdict(lambda: 0), expr_to_name={}
  1793. )
  1794. def _new_var(self, prefix: str = "_var") -> str:
  1795. name = f"{prefix}{self._counter}"
  1796. self._counter += 1
  1797. return name
  1798. def count(self, exprs: List[str]) -> None:
  1799. counter = self.ExprCounter(self._config)
  1800. for e in exprs:
  1801. try:
  1802. counter.visit(ast.parse(e))
  1803. except SyntaxError as ex:
  1804. log.exception("Failed to visit expr at line %s.\n%s", ex.lineno, e)
  1805. raise
  1806. def replace(self, expr: str) -> Tuple[List[str], str]:
  1807. replacer = self.Replacer(self._config, self._new_var)
  1808. new_node = replacer.visit(ast.parse(expr))
  1809. return replacer.preface, _ast_unparse(new_node)
  1810. def must_add_nn_module_guards(guard):
  1811. # For config.guard_nn_modules=False, we can skip all the guards that
  1812. # originate from inside of nn module except for a few categories.
  1813. return (
  1814. # Guard for defaults
  1815. isinstance(guard.originating_source, DefaultsSource)
  1816. # Guard using dict tags if the config flag is set
  1817. or (
  1818. config.guard_nn_modules_using_dict_tags
  1819. and guard.create_fn is GuardBuilder.NN_MODULE
  1820. )
  1821. )
  1822. class DeletedGuardFn:
  1823. pass
  1824. # NB: Naively, you'd expect this to only be a function that produces
  1825. # the callable that constitutes the guard. However, there is some
  1826. # delicate handling for invalidating this check function when the
  1827. # locals/globals get invalidated, so there's some extra state
  1828. # we have to hold in this manager class.
  1829. class CheckFunctionManager:
  1830. def __init__(
  1831. self,
  1832. output_graph=None,
  1833. guard_fail_fn: Optional[Callable[[GuardFail], None]] = None,
  1834. ):
  1835. guards = output_graph.guards if output_graph else None
  1836. self._weakrefs: Dict[int, ReferenceType[object]] = {}
  1837. self.guard_manager = None
  1838. if config.enable_cpp_guard_manager:
  1839. self.guard_manager = GuardManager()
  1840. self.output_graph = output_graph
  1841. w_builder = None
  1842. def source_ref(source):
  1843. guard_source = source.guard_source()
  1844. if guard_source is GuardSource.CONSTANT:
  1845. # No need to track constants
  1846. return source.name()
  1847. assert w_builder
  1848. r_builder = w_builder()
  1849. assert r_builder is not None
  1850. return r_builder.arg_ref(source.name())
  1851. builder = GuardBuilder(
  1852. self.id_ref,
  1853. source_ref,
  1854. self.lookup_weakrefs,
  1855. output_graph.local_scope,
  1856. output_graph.global_scope,
  1857. self.guard_manager,
  1858. self,
  1859. )
  1860. # Break retain cycle. See test_release_scope_memory
  1861. def cleanup_builder(weak_b):
  1862. b = weak_b()
  1863. if b:
  1864. b.scope = None
  1865. # Break retain cycle. See test_release_input_memory
  1866. w_builder = weakref.ref(builder, cleanup_builder)
  1867. for guard in sorted(guards or [], key=Guard.sort_key):
  1868. if (
  1869. not config.guard_nn_modules
  1870. and guard.is_nn_module()
  1871. # Default func args must be guarded on.
  1872. # TODO: we could make use of 'DefaultsSource' and offer a .guard.is_defaults() API
  1873. and "__defaults__" not in guard.name
  1874. and "__kwdefaults__" not in guard.name
  1875. and (config.skip_nnmodule_hook_guards or "hooks" not in guard.name)
  1876. ):
  1877. continue
  1878. guard.create(builder)
  1879. self.check_fn = self.compile_check_fn(builder, guards, guard_fail_fn)
  1880. # Keep track of weak references of objects with ID_MATCH guard. This
  1881. # info is stored alongside optimized_code and check_fn and is used to
  1882. # limit the number of cache entries with same ID_MATCH'd object.
  1883. # TODO(anijain2305) - Currently this information is stored as an attr on
  1884. # the check_fn itself to avoid changing CacehEntry datastructure in
  1885. # eval_frame.c. In future, we should probably replace check_fn with a
  1886. # queryable data structure such that this information is already present
  1887. # in some form.
  1888. self.check_fn.id_matched_objs = builder.id_matched_objs
  1889. if config.enable_cpp_guard_manager:
  1890. # TODO: don't do the string rep, do something more structured here
  1891. torch._logging.trace_structured(
  1892. "dynamo_cpp_guards_str", payload_fn=lambda: str(self.guard_manager)
  1893. )
  1894. guards_log.debug("%s", self.guard_manager)
  1895. assert self.guard_manager # to make mypy happy
  1896. self.guard_manager.id_matched_objs = builder.id_matched_objs
  1897. self.check_fn = self.guard_manager
  1898. # NB - We have to very careful of cleaning up here. Because of the
  1899. # invalidate function, we can create a weakref finalizer that keeps
  1900. # `self` alive for very long. Sometimes by mistake, we can run
  1901. # invalidate for a type/object (check id_ref method) that Python can
  1902. # leak by design, preventing us from calling the finalizer. In that
  1903. # case, the `self` will be alive even though the cache entry will be
  1904. # deleted (check invalidate method), which can cause a memory leak,
  1905. # e.g., not setting output_graph = None can keep hold of nn_modules.
  1906. self._weakrefs.clear()
  1907. self.output_graph = None
  1908. def compile_check_fn(self, builder, guards_out, guard_fail_fn):
  1909. # see parallel handling of ".0" / "___implicit0" in _eval_frame.c
  1910. largs = builder.argnames
  1911. largs += ["**___kwargs_ignored"]
  1912. guards_log.debug("GUARDS:")
  1913. code_parts = []
  1914. verbose_code_parts = []
  1915. structured_guard_fns = []
  1916. if config.enable_cpp_guard_manager:
  1917. # Insert the global_state guard
  1918. assert self.guard_manager # to make mypy happy
  1919. self.guard_manager.root.add_global_state_guard(["___check_global_state()"])
  1920. else:
  1921. # Don't report this guard, it's always the same, useless!
  1922. global_guard = "___check_global_state()"
  1923. code_parts.append(global_guard)
  1924. verbose_code_parts.append(global_guard)
  1925. def add_code_part(code_part, guard, log_only=False):
  1926. verbose_code_part = get_verbose_code_part(code_part, guard)
  1927. guards_log.debug("%s", verbose_code_part)
  1928. structured_guard_fns.append(
  1929. lambda: {
  1930. "code": code_part,
  1931. "stack": structured.from_traceback(guard.stack.summary())
  1932. if guard.stack
  1933. else None,
  1934. "user_stack": structured.from_traceback(guard.user_stack)
  1935. if guard.user_stack
  1936. else None,
  1937. }
  1938. )
  1939. if verbose_guards_log.isEnabledFor(logging.DEBUG):
  1940. maybe_stack = ""
  1941. maybe_user_stack = ""
  1942. if guard is not None:
  1943. if guard.stack:
  1944. maybe_stack = f"\nStack:\n{''.join(guard.stack.format())}"
  1945. if guard.user_stack:
  1946. maybe_user_stack = (
  1947. f"\nUser stack:\n{''.join(guard.user_stack.format())}"
  1948. )
  1949. verbose_guards_log.debug(
  1950. "Guard: %s%s%s",
  1951. code_part,
  1952. maybe_stack,
  1953. maybe_user_stack,
  1954. )
  1955. if not log_only:
  1956. code_parts.append(code_part)
  1957. verbose_code_parts.append(verbose_code_part)
  1958. seen = set()
  1959. for gcl in builder.code:
  1960. for code in gcl.code_list:
  1961. if code not in seen:
  1962. # If Cpp guard manager is enabled, we don't need to add to
  1963. # code_parts.
  1964. add_code_part(code, gcl.guard, config.enable_cpp_guard_manager)
  1965. seen.add(code)
  1966. tensor_check_names = builder.tensor_check_names
  1967. check_tensors_fn = None
  1968. check_tensors_verbose_fn = None
  1969. if tensor_check_names and not config.enable_cpp_guard_manager:
  1970. tensor_check_guards = builder.tensor_check_guards
  1971. assert (
  1972. not self.output_graph.export
  1973. ), "Illegal to set tensor_check_names in export."
  1974. tensor_check_examples = builder.tensor_check_examples
  1975. dynamic_dims_sizes = []
  1976. dynamic_dims_strides = []
  1977. for t, g in zip(tensor_check_examples, tensor_check_guards):
  1978. metadata = self.output_graph.input_source_to_sizes_strides[
  1979. g.originating_source
  1980. ]
  1981. dynamic_dims_sizes.append(convert_to_concrete_values(metadata["size"]))
  1982. dynamic_dims_strides.append(
  1983. convert_to_concrete_values(metadata["stride"])
  1984. )
  1985. tensor_guards = TensorGuards(
  1986. *tensor_check_examples,
  1987. dynamic_dims_sizes=dynamic_dims_sizes,
  1988. dynamic_dims_strides=dynamic_dims_strides,
  1989. )
  1990. check_tensors_fn = tensor_guards.check
  1991. check_tensors_verbose_fn = tensor_guards.check_verbose
  1992. tensor_check_args = ", ".join(
  1993. tensor_check_names + ["tensor_check_names=tensor_check_names"]
  1994. )
  1995. # Do this manually, to un-stagger the guards in log message
  1996. code_parts.append(f"___check_tensors({tensor_check_args})")
  1997. verbose_code_parts.append(f"___check_tensors({tensor_check_args})")
  1998. for i, name in enumerate(tensor_check_names):
  1999. # This is a copy of what guards.cpp checks against
  2000. # Keep this in sync with TensorCheck constructor
  2001. t = tensor_check_examples[i]
  2002. sizes = dynamic_dims_sizes[i]
  2003. strides = dynamic_dims_strides[i]
  2004. code_part = get_tensor_guard_code_part(t, name, sizes, strides)
  2005. add_code_part(code_part, tensor_check_guards[i], log_only=True)
  2006. if len(tensor_check_names) > 1 and config.enable_cpp_guard_manager:
  2007. # Install tensor aliasing guard. TENSOR_MATCH guards are already
  2008. # installed for cpp guard manager.
  2009. install_no_tensor_aliasing_guard(
  2010. builder.tensor_check_guard_managers,
  2011. tensor_check_names,
  2012. ["check_no_aliasing(" + ", ".join(tensor_check_names) + ")"],
  2013. )
  2014. aotautograd_guards: List[GuardEnvExpr] = (
  2015. self.output_graph.tracing_context.guards_context.aotautograd_guards
  2016. if self.output_graph
  2017. else []
  2018. )
  2019. # TODO(anijain2305) - There is a duplicate logic in Dynamo to find
  2020. # aliased input tensors. So most probably we don't need this here.
  2021. # Revisit.
  2022. for guard in aotautograd_guards:
  2023. if isinstance(guard, DuplicateInputs):
  2024. source_a = guard.input_source_a
  2025. source_b = guard.input_source_b
  2026. code_part = f"{source_a.name()} is {source_b.name()}"
  2027. if config.enable_cpp_guard_manager:
  2028. install_tensor_aliasing_guard(
  2029. builder.get_guard_manager_from_source(source_a),
  2030. builder.get_guard_manager_from_source(source_b),
  2031. [code_part],
  2032. )
  2033. add_code_part(code_part, None, config.enable_cpp_guard_manager)
  2034. else:
  2035. raise RuntimeError(f"Unknown GuardEnvExpr: {guard}")
  2036. # TODO: the "guard" here is actually just the top level SHAPE_ENV
  2037. # which is useless. Get ShapeEnv to pass in more provenance.
  2038. for gcl in builder.shape_env_code:
  2039. for code in gcl.code_list:
  2040. # Shape env guards are already added for CPP guard manager in
  2041. # SHAPE_ENV implementation.
  2042. add_code_part(code, gcl.guard, config.enable_cpp_guard_manager)
  2043. # OK, all done generating guards
  2044. torch._logging.trace_structured(
  2045. "dynamo_guards", payload_fn=lambda: [f() for f in structured_guard_fns]
  2046. )
  2047. global_state = convert_frame.initial_global_state
  2048. if global_state is None:
  2049. # we should only hit this case in NopTests()
  2050. global_state = convert_frame.GlobalStateGuard()
  2051. closure_vars = {
  2052. "___check_tensors": check_tensors_fn,
  2053. "___check_tensors_verbose": check_tensors_verbose_fn,
  2054. "___check_global_state": global_state.check,
  2055. "tensor_check_names": tensor_check_names,
  2056. **SYMPY_INTERP,
  2057. **CLOSURE_VARS,
  2058. }
  2059. globals_for_guard_fn = {"G": builder.scope["G"]}
  2060. if config.enable_cpp_guard_manager:
  2061. # Guard manager construction is complete
  2062. assert self.guard_manager # to make mypy happy
  2063. # TODO (anijain2305) - When enable_cpp_guard_manager is ON by
  2064. # default, change the guard_fn name to be guard_manager everywhere
  2065. # to avoid confusion.
  2066. guard_fn = self.guard_manager
  2067. # Ensure we did not miss to insert a guard in cpp guard manager.
  2068. assert len(code_parts) == 0
  2069. else:
  2070. unique_code_parts = list(unique(code_parts))
  2071. make_guard_fn_args = ", ".join(closure_vars.keys())
  2072. guard_body, pycode = build_guard_function(
  2073. unique_code_parts, make_guard_fn_args
  2074. )
  2075. if os.environ.get("TORCHDYNAMO_PRINT_GUARDS", None) == "1":
  2076. print("GUARDS\n", guard_body)
  2077. out: Dict[str, Any] = dict()
  2078. # We don't put builder.scope as the globals in exec call because
  2079. # guard_fn.__globals__ becomes equal to builder.scope. This causes
  2080. # guard_fn to hold a referece to f_locals sitting in builder.scope["L"]
  2081. try:
  2082. exec(pycode, globals_for_guard_fn, out)
  2083. except SyntaxError as ex:
  2084. log.exception("Failed to exec guard at line %s.\n%s", ex.lineno, pycode)
  2085. raise
  2086. guard_fn = out["___make_guard_fn"](*closure_vars.values())
  2087. guard_fn.closure_vars = closure_vars
  2088. # TODO(whc) maybe '.code_parts' was only kept around for the guard callback? so we don't need both
  2089. guard_fn.args = largs
  2090. guard_fn.code_parts = code_parts
  2091. guard_fn.verbose_code_parts = verbose_code_parts
  2092. # Grab only G, but preserve "G" because guards access it as "G"
  2093. guard_fn.global_scope = globals_for_guard_fn
  2094. guard_fn.guard_fail_fn = guard_fail_fn
  2095. # will be populated by a non-owning reference to CacheEntry/ExtraState
  2096. # when the CacheEntry is constructed
  2097. guard_fn.cache_entry = None
  2098. guard_fn.extra_state = None
  2099. guard_fn.no_tensor_aliasing_sources = tensor_check_names
  2100. return guard_fn
  2101. def invalidate(self):
  2102. # Some tests reveal that CheckFunctionManager has no attribute
  2103. # check_fn, but this case should not be of any concern.
  2104. # This case doesn't seem easy to repro.
  2105. if (
  2106. hasattr(self, "check_fn")
  2107. and self.check_fn is not DeletedGuardFn
  2108. and (cache_entry := self.check_fn.cache_entry) is not None
  2109. and (extra_state := self.check_fn.extra_state) is not None
  2110. ):
  2111. assert isinstance(cache_entry, CacheEntry)
  2112. assert isinstance(extra_state, ExtraState)
  2113. extra_state.invalidate(cache_entry)
  2114. self.check_fn.cache_entry = None
  2115. self.check_fn.extra_state = None
  2116. self.check_fn = DeletedGuardFn
  2117. def id_ref(self, obj):
  2118. """add a weakref, return the id"""
  2119. try:
  2120. if id(obj) not in self._weakrefs:
  2121. # We will clear the _weakrefs dict at the end of __init__
  2122. # function, which will delete the callbacks as well. Therefore,
  2123. # we are using a finalizer which is kept alive.
  2124. self._weakrefs[id(obj)] = weakref.ref(obj)
  2125. weakref.finalize(obj, self.invalidate)
  2126. except TypeError:
  2127. pass # cannot weakref bool object
  2128. return id(obj)
  2129. def lookup_weakrefs(self, obj):
  2130. """Lookup the _weakrefs created in id_ref function for ID_MATCH'd objects"""
  2131. if id(obj) in self._weakrefs:
  2132. return self._weakrefs[id(obj)]
  2133. return None
  2134. def build_guard_function(code_parts, closure_args) -> Tuple[str, str]:
  2135. from torch._inductor.utils import IndentedBuffer
  2136. if HAS_UNPARSE_FUNCTIONS:
  2137. csepass = PyExprCSEPass()
  2138. csepass.count(code_parts)
  2139. def replace(expr: str) -> Tuple[List[str], str]:
  2140. return csepass.replace(expr)
  2141. else:
  2142. def replace(expr: str) -> Tuple[List[str], str]:
  2143. return [], expr
  2144. # Generate the inner body of the guard function.
  2145. # i.e. if-chain of the guard expressions.
  2146. guard_body = IndentedBuffer()
  2147. for expr in code_parts:
  2148. preface, expr = replace(expr)
  2149. guard_body.writelines(preface)
  2150. guard_body.writeline(f"if not ({expr}):")
  2151. with guard_body.indent():
  2152. guard_body.writeline("return False")
  2153. # Wrap the inner body into the actual guard function.
  2154. guard = IndentedBuffer()
  2155. guard.writeline("def guard(L):")
  2156. with guard.indent():
  2157. guard.splice(guard_body)
  2158. guard.writeline("return True")
  2159. # Wrap the whole guard function into another function
  2160. # with the closure variables.
  2161. make_guard_fn = IndentedBuffer()
  2162. make_guard_fn.writeline(f"def ___make_guard_fn({closure_args}):")
  2163. with make_guard_fn.indent():
  2164. make_guard_fn.splice(guard)
  2165. make_guard_fn.writeline("return guard")
  2166. return guard_body.getvalue(), make_guard_fn.getvalue()
  2167. def is_recompiles_enabled():
  2168. return torch._logging._internal.log_state.is_artifact_enabled("recompiles")
  2169. def is_recompiles_verbose_enabled():
  2170. return torch._logging._internal.log_state.is_artifact_enabled("recompiles_verbose")
  2171. def recompilation_reason_for_no_tensor_aliasing_guard(guard_manager, scope):
  2172. duplicate_tensors = []
  2173. global_scope = dict(guard_manager.global_scope)
  2174. ids_to_source = collections.defaultdict(list)
  2175. for tensor_source in guard_manager.no_tensor_aliasing_sources: # type: ignore[attr-defined]
  2176. global_scope["__compile_source__"] = tensor_source
  2177. tensor_id = id(eval(tensor_source, global_scope, scope))
  2178. ids_to_source[tensor_id].append(tensor_source)
  2179. for key in ids_to_source:
  2180. if len(ids_to_source[key]) > 1:
  2181. duplicate_tensors.append(f"{ids_to_source[key]}")
  2182. reason = ", ".join(duplicate_tensors)
  2183. return [f"Duplicate tensors found: {reason}"]
  2184. def get_guard_fail_reason(
  2185. guard_fn: GuardFn,
  2186. code: types.CodeType,
  2187. f_locals: Dict[str, object],
  2188. ) -> str:
  2189. """
  2190. Return the reason why `guard_fn` failed.
  2191. Updates `guard_failures` with the generated reason.
  2192. Only the first failed check of guard_fn is reported.
  2193. """
  2194. scope = {"L": f_locals, "G": guard_fn.global_scope["G"]}
  2195. scope.update(guard_fn.closure_vars)
  2196. reasons: List[str] = []
  2197. no_tensor_aliasing_check_failed = False
  2198. verbose_code_parts: List[str] = []
  2199. if config.enable_cpp_guard_manager:
  2200. guard_manager = guard_fn
  2201. guard_debug_info = guard_manager.check_verbose(f_locals) # type: ignore[attr-defined]
  2202. # For test_export_with_map_cond, the check_verbose fail even without the
  2203. # C++ guard manager. We need to fix the issue to remove the comment.
  2204. # assert not guard_debug_info.result
  2205. if not guard_debug_info.result:
  2206. verbose_code_parts = guard_debug_info.verbose_code_parts
  2207. # verbose_code_parts is either the actual reason (e.g. in case of
  2208. # TENSOR_MATCH) or it could be a list of verbose_code_part that we
  2209. # passed to the leaf guard at construction time. If its a list, we
  2210. # walk through this list and find the guard that failed. This is
  2211. # very important for symbolic shape guards which are currently
  2212. # installed as a lambda guard and can encompass a long list of code_parts.
  2213. if len(verbose_code_parts) == 1:
  2214. if "Duplicate tensor found" in verbose_code_parts[0]:
  2215. no_tensor_aliasing_check_failed = True
  2216. else:
  2217. reasons = verbose_code_parts
  2218. verbose_code_parts = []
  2219. else:
  2220. verbose_code_parts = guard_fn.verbose_code_parts
  2221. # This is not needed for CPP guard because the verbose check is already
  2222. # run in C++.
  2223. scope["___check_tensors"] = scope["___check_tensors_verbose"]
  2224. if no_tensor_aliasing_check_failed:
  2225. reasons = recompilation_reason_for_no_tensor_aliasing_guard(guard_fn, scope)
  2226. else:
  2227. for part in verbose_code_parts:
  2228. global_scope = dict(guard_fn.global_scope)
  2229. global_scope["__compile_source__"] = part
  2230. with report_compile_source_on_error():
  2231. try:
  2232. fail_reason = eval(part, global_scope, scope)
  2233. except Exception as e:
  2234. if is_recompiles_verbose_enabled():
  2235. continue
  2236. else:
  2237. raise
  2238. # Only ___check_tensors knows how to return a fancy fail reason;
  2239. # for everything else we just report the code that failed
  2240. if isinstance(fail_reason, bool) and not fail_reason:
  2241. fail_reason = part
  2242. if isinstance(fail_reason, str):
  2243. reasons.append(fail_reason)
  2244. if not is_recompiles_verbose_enabled():
  2245. break
  2246. reason_str = "\n".join(reasons)
  2247. guard_failures[orig_code_map[code]].append(reason_str)
  2248. try:
  2249. if guard_fn.guard_fail_fn is not None:
  2250. guard_fn.guard_fail_fn(
  2251. GuardFail(reason_str or "unknown reason", orig_code_map[code])
  2252. )
  2253. except Exception as e:
  2254. log.exception(
  2255. "Failure in guard_fail_fn callback - raising here will cause a NULL Error on guard eval",
  2256. )
  2257. return reason_str
  2258. def get_and_maybe_log_recompilation_reason(
  2259. cache_entry, frame: types.FrameType
  2260. ) -> List[str]:
  2261. """
  2262. Return the list of guard failure reasons using cache_entry.
  2263. Logs the recompilation reason if `recompiles` logging is enabled.
  2264. Raises a RecompileError if `config.error_on_recompile` is enabled.
  2265. """
  2266. reasons = []
  2267. while cache_entry is not None:
  2268. reason = get_guard_fail_reason(
  2269. cache_entry.check_fn, cache_entry.code, frame.f_locals
  2270. )
  2271. if reason:
  2272. reasons.append(reason)
  2273. cache_entry = cache_entry.next
  2274. code = frame.f_code
  2275. # at least one of "recompiles" or "recompiles_verbose" is enabled
  2276. do_recompiles_log = is_recompiles_enabled() or is_recompiles_verbose_enabled()
  2277. if do_recompiles_log or config.error_on_recompile:
  2278. if is_recompiles_verbose_enabled():
  2279. failures = "\n\n".join(
  2280. f"guard {i} failures:\n" + textwrap.indent(reason, "- ")
  2281. for i, reason in enumerate(reasons)
  2282. )
  2283. else:
  2284. failures = textwrap.indent("\n".join(reasons), "- ")
  2285. guard_failure_details = (
  2286. f"triggered by the following guard failure(s):\n{failures}"
  2287. )
  2288. message = (
  2289. f"Recompiling function {code.co_name} in {code.co_filename}:{code.co_firstlineno}\n"
  2290. f"{textwrap.indent(guard_failure_details, ' ')}"
  2291. )
  2292. if do_recompiles_log:
  2293. if is_recompiles_verbose_enabled():
  2294. recompiles_verbose_log.debug(message)
  2295. else:
  2296. recompiles_log.debug(message)
  2297. if config.error_on_recompile:
  2298. raise exc.RecompileError(message)
  2299. return reasons
  2300. def guard_error_hook(
  2301. guard_fn: GuardFn,
  2302. code: types.CodeType,
  2303. f_locals: Dict[str, object],
  2304. index: int,
  2305. last: bool,
  2306. ):
  2307. print(
  2308. f"ERROR RUNNING GUARDS {code.co_name} {code.co_filename}:{code.co_firstlineno}"
  2309. )
  2310. print("lambda " + ", ".join(guard_fn.args) + ":")
  2311. print(" ", " and\n ".join(guard_fn.code_parts))
  2312. if config.enable_cpp_guard_manager:
  2313. print(guard_fn)
  2314. local_scope = {"L": f_locals, **guard_fn.closure_vars}
  2315. for guard in guard_fn.code_parts:
  2316. try:
  2317. eval(guard, guard_fn.global_scope, local_scope)
  2318. except: # noqa: B001,E722
  2319. print(f"Malformed guard:\n{guard}")
  2320. set_guard_error_hook(guard_error_hook)
  2321. def unique(seq):
  2322. seen = set()
  2323. for x in seq:
  2324. if x not in seen:
  2325. yield x
  2326. seen.add(x)
  2327. def make_dupe_guard(obj_source, dupe_source):
  2328. # Note - we may end up in a situation where we invoke something like
  2329. # def fn(x, y)
  2330. # with fn(x, x)
  2331. # Prior to the addition of tracking to all relevant objects, we would handle this just fine by
  2332. # eagerly re-entering VB and rewrapping inputs, correctly creating graphargs and placeholders. However,
  2333. # with tracking on inputs, duplicate inputs or aliased relationships may end up getting erased here -
  2334. # In the fn(x, x) example call above look like a graph with a single input.
  2335. # In order to ensure that we do not reuse fn(x, x) for fn(x, y), we create a duplicate input guard.
  2336. # Note - we may not have a source, that is fine, it just means we had an object that is safe to have
  2337. # leave unsourced - like a local list created and discharged entirely within a local scope.
  2338. if dupe_source and dupe_source != obj_source:
  2339. ser_source_is_local = is_from_local_source(dupe_source)
  2340. source_is_local = is_from_local_source(obj_source)
  2341. if is_from_flatten_script_object_source(
  2342. dupe_source
  2343. ) or is_from_flatten_script_object_source(obj_source):
  2344. raise exc.UnsafeScriptObjectError(
  2345. f"{obj_source.name()} is alising {dupe_source.name()}. This is not supported."
  2346. f" Please do a clone for corresponding input."
  2347. )
  2348. # Note - both must be local, or global, or we will run afoul of a lack of merging in how we currently
  2349. # reconcile guards builder scopes in compile_check_fn. This technically means we miss a guard here,
  2350. # so maybe we should do this refactor before we land this...
  2351. # TODO(voz): Combine local and global guard builders.
  2352. if ser_source_is_local == source_is_local:
  2353. # Note - this is a little aggressive - these being duplicate input does not always matter.
  2354. # However, this should always be a sound guard to add here.
  2355. return functools.partial(GuardBuilder.DUPLICATE_INPUT, source_b=dupe_source)
  2356. return None
  2357. def install_guard(*guards, skip=0):
  2358. """
  2359. Add dynamo guards to the current tracing context.
  2360. Args:
  2361. guards: guard(s) to add
  2362. skip: number of stack frames to ignore for debug stack trace
  2363. """
  2364. from torch._guards import TracingContext
  2365. collect_debug_stack = guards_log.isEnabledFor(
  2366. logging.DEBUG
  2367. ) or verbose_guards_log.isEnabledFor(logging.DEBUG)
  2368. add = TracingContext.get().guards_context.dynamo_guards.add
  2369. for guard in guards:
  2370. assert isinstance(guard, Guard)
  2371. add(guard, collect_debug_stack=collect_debug_stack, skip=skip + 1)