_guards.py 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353
  1. from __future__ import annotations
  2. import contextlib
  3. import dataclasses
  4. import enum
  5. import functools
  6. import logging
  7. import re
  8. import threading
  9. import traceback
  10. import unittest.mock
  11. import weakref
  12. from abc import abstractmethod
  13. from collections import defaultdict
  14. from contextlib import contextmanager
  15. from dataclasses import dataclass
  16. from typing import Any, Generic, NamedTuple, Optional, overload, TYPE_CHECKING, TypeVar
  17. from typing_extensions import dataclass_transform
  18. import torch
  19. from torch.utils import _pytree as pytree
  20. from torch.utils._ordered_set import OrderedSet
  21. from torch.utils._python_dispatch import is_traceable_wrapper_subclass
  22. from torch.utils._traceback import CapturedTraceback, format_frame
  23. from torch.utils.weak import WeakTensorKeyDictionary
  24. log = logging.getLogger(__name__)
  25. if TYPE_CHECKING:
  26. from collections.abc import Callable, Generator, Iterator
  27. from types import CodeType
  28. import sympy
  29. from torch._dynamo.backends.distributed import DDPOptimizerContext
  30. from torch._dynamo.codegen import PyCodegen
  31. from torch._functorch._aot_autograd.schemas import ViewAndMutationMeta
  32. from torch._subclasses.fake_tensor import FakeTensorMode
  33. """
  34. torch._guards is the definitional source of truth for general purpose guard structures.
  35. An important thing to keep in mind here is the preservation of layering. There should be no dynamo notions,
  36. and no guard installation notions here.
  37. """
  38. COMPILE_ID_PATTERN = re.compile(r"^(?P<frame_id>\d+)/(?P<frame_compile_id>\d+)$")
  39. CA_COMPILE_ID_PATTERN = re.compile(
  40. r"^!(?P<compiled_autograd_id>\d+)(?:/(?P<frame_id>\d+)/(?P<frame_compile_id>\d+))?$"
  41. )
  42. # [Note: Updating CompiledId]
  43. #
  44. # CompiledId represents a unique program-level identifier, and we want to keep that
  45. # property as the codebase evolves. This property is relied on even outside of the pytorch
  46. # repo, e.g. tlparse or other internal tooling. The in-memory format can be freely changed,
  47. # as those dependencies only consume the string serialization.
  48. #
  49. # The string form should be:
  50. # 1. Program-level uid: CompileId can uniquely identify a compiled graph.
  51. # 2. Storage efficient: This object is logged in nearly every entry. We should elide symbols when possible.
  52. # 3. Compact: The string form is directly displayed by some tools. Special symbols are okay.
  53. @dataclass(frozen=True, kw_only=True, slots=True)
  54. class CompileId:
  55. frame_id: int | None
  56. # This id is per-frame, and counts how many times we've compiled this
  57. # frame. This could have been a global id but having this be per-frame
  58. # gives you a better intuitive sense for how many recompiles have occurred
  59. # so far.
  60. frame_compile_id: int | None
  61. # torch.compiling a compiled autograd graph
  62. compiled_autograd_id: int | None = None
  63. # TODO: consider also tracking the recompilation count
  64. # See Note: Updating CompileId
  65. def __str__(self) -> str:
  66. # NOTE: Keep this in sync with both from_string and the tlparse repo
  67. if self.compiled_autograd_id is not None:
  68. if (self.frame_id is None) != (self.frame_compile_id is None):
  69. raise AssertionError(
  70. f"frame_id and frame_compile_id must both be None or both be set, "
  71. f"got frame_id={self.frame_id}, frame_compile_id={self.frame_compile_id}"
  72. )
  73. frame_str = ""
  74. if self.frame_id is not None:
  75. frame_str = f"/{self.frame_id}/{self.frame_compile_id}"
  76. return f"!{self.compiled_autograd_id}{frame_str}"
  77. else:
  78. if self.frame_id is None or self.frame_compile_id is None:
  79. raise AssertionError(
  80. f"frame_id and frame_compile_id must not be None, "
  81. f"got frame_id={self.frame_id}, frame_compile_id={self.frame_compile_id}"
  82. )
  83. return f"{self.frame_id}/{self.frame_compile_id}"
  84. @classmethod
  85. def from_string(cls, compile_id: str | None) -> CompileId | None:
  86. """
  87. Factory method that creates a CompileId from its string representation.
  88. Keep this in sync with the __str__ method.
  89. """
  90. if compile_id is None:
  91. return None
  92. try:
  93. for pattern in (COMPILE_ID_PATTERN, CA_COMPILE_ID_PATTERN):
  94. if match := pattern.match(compile_id):
  95. groups = match.groupdict()
  96. for k, v in groups.items():
  97. if v is not None:
  98. groups[k] = int(v)
  99. return cls(**groups) # type: ignore[arg-type]
  100. else:
  101. raise ValueError
  102. except Exception as e:
  103. raise ValueError(f"Invalid compile_id '{compile_id}'") from e
  104. class TraceId(NamedTuple):
  105. compile_id: CompileId
  106. # This starts off as 0, and every time we restart analysis it goes
  107. # up by one
  108. attempt: int
  109. def __str__(self) -> str:
  110. # Keep this in sync with tlparse repo
  111. if self.attempt == 0:
  112. return str(self.compile_id)
  113. else:
  114. return f"{self.compile_id}_{self.attempt}"
  115. class GuardSource(enum.Enum):
  116. LOCAL = 0
  117. GLOBAL = 1
  118. LOCAL_SPECIALIZED_NN_MODULE = 2
  119. GLOBAL_SPECIALIZED_NN_MODULE = 3
  120. CONSTANT = 4
  121. RANDOM_VALUE = 5
  122. SHAPE_ENV = 6
  123. LOCAL_FSDP_MODULE = 7
  124. GLOBAL_FSDP_MODULE = 8
  125. BACKWARD_STATE = 9
  126. EPHEMERAL = 10
  127. SYNTHETIC_LOCAL = 11
  128. LOCAL_UNSPECIALIZED_NN_MODULE = 12
  129. GLOBAL_UNSPECIALIZED_NN_MODULE = 13
  130. LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 14
  131. GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE = 15
  132. TEMP_LOCAL = 16
  133. def is_fsdp_module(self) -> bool:
  134. return self in (GuardSource.GLOBAL_FSDP_MODULE, GuardSource.LOCAL_FSDP_MODULE)
  135. def is_specialized_nn_module(self) -> bool:
  136. import torch._dynamo.config as config
  137. if config._unsafe_skip_fsdp_module_guards:
  138. return (
  139. self
  140. in (
  141. GuardSource.GLOBAL_SPECIALIZED_NN_MODULE,
  142. GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
  143. )
  144. or self.is_fsdp_module()
  145. )
  146. return self in (
  147. GuardSource.GLOBAL_SPECIALIZED_NN_MODULE,
  148. GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
  149. )
  150. def is_unspecialized_nn_module(self) -> bool:
  151. return self in (
  152. GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE,
  153. GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE,
  154. GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  155. GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  156. )
  157. def is_unspecialized_builtin_nn_module(self) -> bool:
  158. return self in (
  159. GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  160. GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  161. )
  162. def is_local(self) -> bool:
  163. return self in (
  164. GuardSource.LOCAL,
  165. GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
  166. GuardSource.LOCAL_FSDP_MODULE,
  167. GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE,
  168. GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  169. )
  170. """
  171. Base class for a "GuardBuilder" role.
  172. The GuardBuilderBase role is to represent a scope within which to build a guard. The name is a little
  173. confusing, as its not a builder, but for the sake of avoiding a lot of renames and keeping the original reference
  174. to torchdynamo's GuardBuilder.
  175. Note: create_fn is invoked with a GuardBuilderBase and a Guard. A GuardBuilder is chosen based
  176. on GuardSource's select function.
  177. There is value in keeping this GuardBuilderBase empty to keep layering clean.
  178. """
  179. class GuardBuilderBase:
  180. pass
  181. @dataclasses.dataclass(frozen=True)
  182. class SLoc:
  183. framework_loc: traceback.FrameSummary | str | None
  184. maybe_user_loc: str | None
  185. def __str__(self) -> str:
  186. floc = (
  187. self.framework_loc
  188. if isinstance(self.framework_loc, str)
  189. else format_frame(self.framework_loc)
  190. )
  191. if self.maybe_user_loc is not None:
  192. return f"{self.maybe_user_loc} ({floc})"
  193. else:
  194. return f"({floc})"
  195. class ShapeGuard(NamedTuple):
  196. expr: sympy.logic.boolalg.Boolean
  197. sloc: SLoc
  198. size_oblivious: bool
  199. @dataclasses.dataclass(slots=True)
  200. class Guard:
  201. # originating_source is the source that called the make_guard method to
  202. # construct this guard object. The property name specifies what exactly it
  203. # is the guard is guarding on. The meaning of the name is dependent on the
  204. # create_fn; you must look at the use-site inside create_fn to know what
  205. # name means.
  206. #
  207. # That being said, although you might think this is just a "name", name is
  208. # usually an arbitrary Python expression that will be evaluated with all
  209. # globals (and locals, if you create a LOCAL guard) to extract the Python
  210. # object that we want to perform guard tests on. This evaluation
  211. # typically happens in GuardBuilder.eval. In these cases, name is
  212. # typically produced by originating_source.name (not to be confused with
  213. # GuardSource - the property source).
  214. #
  215. # Occasionally, name is not a valid Python expression; sometimes
  216. # it is meaningless. Example create_fns that are like this include
  217. # GRAD_MODE and SHAPE_ENV.
  218. originating_source: Source
  219. create_fn: Callable[[GuardBuilderBase, Guard], None]
  220. # Export only. These values are written to at time of guard check_fn creation.
  221. guard_types: list[str] | None = None
  222. code_list: list[str] | None = None
  223. obj_weakref: object | None = None
  224. guarded_class_weakref: weakref.ReferenceType[Any] | None = None
  225. stack: CapturedTraceback | None = None
  226. user_stack: traceback.StackSummary | None = None
  227. _hash: int | None = None
  228. _unserializable: bool = False
  229. def __hash__(self) -> int:
  230. if self._hash is None:
  231. self._hash = hash((self.name, self.source, id(self.create_fn)))
  232. return self._hash
  233. def sort_key(self) -> tuple[bool, int, int, str, int]:
  234. # Put the duplicate input guards at the end. The duplicate guards have
  235. # two sources while guard.name only considers one source.
  236. is_duplicate_input = (
  237. isinstance(self.create_fn, functools.partial)
  238. and self.create_fn.func is torch._dynamo.guards.GuardBuilder.DUPLICATE_INPUT
  239. )
  240. return (
  241. is_duplicate_input,
  242. self.source.value if self.source else -1,
  243. len(self.name),
  244. self.name,
  245. self.inner_create_fn().__code__.co_firstlineno,
  246. )
  247. def __lt__(self, other: Guard) -> bool:
  248. return self.sort_key() < other.sort_key()
  249. def inner_create_fn(self) -> Callable[[GuardBuilderBase, Guard], Any]:
  250. if isinstance(self.create_fn, functools.partial):
  251. return self.create_fn.func
  252. else:
  253. return self.create_fn
  254. @property
  255. def name(self) -> str:
  256. return self.originating_source.name
  257. @property
  258. def source(self) -> GuardSource:
  259. return self.originating_source.guard_source
  260. @staticmethod
  261. def weakref_to_str(obj_weakref: object) -> str:
  262. """
  263. This is a workaround of a Python weakref bug.
  264. `obj_weakref` is instance returned by `weakref.ref`,
  265. `str(obj_weakref)` is buggy if the original obj overrides __getattr__, e.g:
  266. class MyConfig(dict):
  267. def __getattr__(self, x):
  268. return self[x]
  269. obj = MyConfig(offset=5)
  270. obj_weakref = weakref.ref(obj)
  271. str(obj_weakref) # raise error: KeyError: '__name__'
  272. """
  273. if isinstance(obj_weakref, weakref.ReferenceType):
  274. obj = obj_weakref()
  275. if obj is not None:
  276. return f"<weakref at {hex(id(obj_weakref))}; to '{obj.__class__.__name__}' at {hex(id(obj))}>"
  277. else:
  278. return f"<weakref at {hex(id(obj_weakref))}; dead>"
  279. else:
  280. return str(obj_weakref)
  281. def __repr__(self) -> str:
  282. s = f"""
  283. {self.source.name.lower() if self.source else ""} {repr(self.name)} {self.inner_create_fn().__name__}
  284. {{
  285. 'guard_types': {self.guard_types},
  286. 'code': {self.code_list},
  287. 'obj_weakref': {self.weakref_to_str(self.obj_weakref)}
  288. 'guarded_class': {self.guarded_class_weakref}
  289. }}
  290. """
  291. return s
  292. def __str__(self) -> str:
  293. output = f"Name: {repr(self.name)}\n"
  294. source = self.source.name.lower() if self.source else ""
  295. output += f" Source: {source}\n"
  296. output += f" Create Function: {self.inner_create_fn().__name__}\n"
  297. output += f" Guard Types: {self.guard_types}\n"
  298. output += f" Code List: {self.code_list}\n"
  299. output += f" Object Weakref: {self.weakref_to_str(self.obj_weakref)}\n"
  300. output += f" Guarded Class Weakref: {self.guarded_class_weakref}\n"
  301. return output
  302. def create(self, builder: GuardBuilderBase) -> Any:
  303. try:
  304. return self.create_fn(builder, self)
  305. except Exception:
  306. log.exception("Error while creating guard:\n%s", str(self).rstrip())
  307. if self.stack:
  308. log.error("Created at:\n%s", "".join(self.stack.format()[-4:]).rstrip())
  309. raise
  310. def is_specialized_nn_module(self) -> bool:
  311. return self.source.is_specialized_nn_module()
  312. def is_fsdp_module(self) -> bool:
  313. return self.source.is_fsdp_module()
  314. def is_local(self) -> bool:
  315. return self.source.is_local()
  316. def create_fn_name(self) -> str:
  317. if isinstance(self.create_fn, functools.partial):
  318. create_fn = self.create_fn.func # type: ignore[attr-defined]
  319. else:
  320. create_fn = self.create_fn
  321. return create_fn.__name__
  322. def set_export_info(
  323. self,
  324. guard_type: str,
  325. guarded_class: weakref.ReferenceType[Any] | None,
  326. code_list: list[str],
  327. obj_weakref: object,
  328. ) -> None:
  329. if not self.guard_types:
  330. self.guard_types = []
  331. self.guard_types.append(guard_type)
  332. if self.guarded_class_weakref not in (guarded_class, None):
  333. raise AssertionError(
  334. f"Guarded class id must be identical, or None, "
  335. f"got {self.guarded_class_weakref} vs {guarded_class}"
  336. )
  337. self.guarded_class_weakref = guarded_class
  338. if not self.code_list:
  339. self.code_list = code_list
  340. else:
  341. self.code_list.extend(code_list)
  342. # Some objects are ephemeral, e.g., list[slice(1, 2)]. If we have
  343. # multiple guards on the same object, the weakref can die between the
  344. # invocation of set_export_info calls. So a dead weakref is also
  345. # acceptable.
  346. is_valid = (
  347. self.obj_weakref in (obj_weakref, None)
  348. or callable(self.obj_weakref)
  349. and self.obj_weakref() is None
  350. )
  351. if not is_valid:
  352. raise AssertionError(
  353. f"Guarded object must be identical, None or ephemeral (dead weakref), "
  354. f"got {self.obj_weakref} vs {obj_weakref}"
  355. )
  356. self.obj_weakref = obj_weakref
  357. T = TypeVar("T")
  358. """
  359. Parent structure for guard env expressions.
  360. A GuardEnvExpr can have any subtype.
  361. Note: All subtypes must be handled exhaustively in
  362. torch._dynamo.guards._parse_guard_env_guards to avoid a RuntimeError.
  363. """
  364. @dataclasses.dataclass(frozen=True)
  365. class GuardEnvExpr:
  366. pass
  367. """
  368. A class representing a pair of duplicate inputs.
  369. input_pos_a and input_pos_b are input positions we have deduped.
  370. """
  371. @dataclasses.dataclass(frozen=True)
  372. class DuplicateInputs(GuardEnvExpr):
  373. input_source_a: Source
  374. input_source_b: Source
  375. def __post_init__(self) -> None:
  376. if self.input_source_a == self.input_source_b:
  377. raise AssertionError(
  378. f"input_source_a and input_source_b must be different, "
  379. f"got {self.input_source_a}"
  380. )
  381. """
  382. A class representing storage overlap relations among inputs that aliases the same storage.
  383. Given that a set of tensors alias the same storage, this guard checks whether they actually
  384. have overlapping storages.
  385. While non_overlapping_sources represent input tensors that definitely don't have any storage
  386. overlapping with any other input, overlapping_sources represent tensors that either:
  387. 1. Do overlap some other input tensor
  388. 2. Might not overlap some other input tensor, but we are not sure
  389. """
  390. @dataclasses.dataclass(frozen=True)
  391. class StorageOverlap(GuardEnvExpr):
  392. overlapping_sources: list[Source]
  393. non_overlapping_sources: list[Source]
  394. """
  395. Checkpointable is an interface for driving state snapshotting, left purposely vague for now.
  396. copy_graphstate() -> T, a somewhat legacy name, is expected to emit a snapshot of any type that
  397. can also be taken in at restore_graphstate(T) calls.
  398. When to snapshot, is, at the moment, an implementation detail of upstream callers. Checkpointable
  399. does not provide any guarantees around consistency, idempotency, or safety of calling its APIs, yet.
  400. In the future, it will have a closer coupling to a generic Checkpoint management system.
  401. """
  402. class Checkpointable(Generic[T]):
  403. @abstractmethod
  404. def copy_graphstate(self) -> T: ...
  405. @abstractmethod
  406. def restore_graphstate(self, state: T) -> None: ...
  407. class GuardsCheckpointState:
  408. """
  409. The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext
  410. """
  411. dynamo_guards: OrderedSet[Guard]
  412. def __init__(self, dynamo_guards: OrderedSet[Guard]) -> None:
  413. self.dynamo_guards = dynamo_guards
  414. def diff(self, other: GuardsCheckpointState) -> Optional[OrderedSet[Guard]]:
  415. """
  416. Produces a delta against another GuardsCheckpointState.
  417. Returns None if no delta is found, otherwise, return an OrderedSet() of mismatched
  418. Guard type objects.
  419. """
  420. r = self.dynamo_guards.difference(other.dynamo_guards)
  421. if len(r) == 0:
  422. return None
  423. return r
  424. def __eq__(self, other: object) -> bool:
  425. if not isinstance(other, GuardsCheckpointState):
  426. return False
  427. return self.diff(other) is None
  428. class ModuleContextCheckpointState:
  429. nn_modules: dict[str, torch.nn.Module] = {}
  430. def __init__(self, nn_modules: dict[str, torch.nn.Module]) -> None:
  431. self.nn_modules = nn_modules
  432. def diff(self, other: ModuleContextCheckpointState) -> set[str] | None:
  433. """
  434. Produces a delta against another ModuleContextCheckpointState.
  435. Returns None if no delta is found, otherwise, return a set() of mismatched
  436. module key names.
  437. """
  438. r = set(self.nn_modules.keys()).difference(set(other.nn_modules.keys()))
  439. if len(r) == 0:
  440. return None
  441. return r
  442. def __eq__(self, other: object) -> bool:
  443. if not isinstance(other, ModuleContextCheckpointState):
  444. return False
  445. return self.diff(other) is None
  446. class ModuleContext(Checkpointable[ModuleContextCheckpointState]):
  447. def __init__(self) -> None:
  448. self.nn_modules: dict[str, Any] = {}
  449. def copy_graphstate(self) -> ModuleContextCheckpointState:
  450. return ModuleContextCheckpointState(dict(self.nn_modules))
  451. def restore_graphstate(self, state: ModuleContextCheckpointState) -> None:
  452. if not isinstance(state, ModuleContextCheckpointState):
  453. raise AssertionError(
  454. f"expected ModuleContextCheckpointState, got {type(state)}"
  455. )
  456. self.nn_modules = state.nn_modules
  457. class GlobalContextCheckpointState:
  458. global_state: dict[str, tuple[Callable, Any]] = {}
  459. def __init__(self, global_states: dict[str, tuple[Callable, Any]]) -> None:
  460. self.global_state = global_states
  461. def diff(self, other: GlobalContextCheckpointState) -> set[str] | None:
  462. """
  463. Produces a delta against another GlobalContextCheckpointState.
  464. Returns None if no delta is found, otherwise, return a set() of mismatched
  465. global key names.
  466. """
  467. r = set(self.global_state.keys()).difference(set(other.global_state.keys()))
  468. if len(r) == 0:
  469. return None
  470. return r
  471. def __eq__(self, other: object) -> bool:
  472. if not isinstance(other, GlobalContextCheckpointState):
  473. return False
  474. return self.diff(other) is None
  475. class GlobalContext(Checkpointable[GlobalContextCheckpointState]):
  476. """
  477. This keeps track of the global torch state during tracing of a function.
  478. For example, torch.is_grad_enabled.
  479. """
  480. _supported_global_states = {
  481. "grad_enabled",
  482. "autocast_enabled",
  483. "autocast_cpu_enabled",
  484. "autocast_gpu_dtype",
  485. "autocast_cpu_dtype",
  486. "autocast_cache_enabled",
  487. }
  488. def __init__(self) -> None:
  489. self.global_state: dict[str, tuple[Callable, Any]] = {}
  490. def copy_graphstate(self) -> GlobalContextCheckpointState:
  491. return GlobalContextCheckpointState(self.global_state)
  492. def restore_graphstate(self, state: GlobalContextCheckpointState) -> None:
  493. if not isinstance(state, GlobalContextCheckpointState):
  494. raise AssertionError(
  495. f"expected GlobalContextCheckpointState, got {type(state)}"
  496. )
  497. self.global_state = state.global_state
  498. if not (
  499. len(self.global_state) == len(self._supported_global_states)
  500. and set(self.global_state.keys()) == self._supported_global_states
  501. ):
  502. raise AssertionError(
  503. f"Global state mismatch: got keys {set(self.global_state.keys())}, "
  504. f"expected {self._supported_global_states}"
  505. )
  506. for func, args in self.global_state.values():
  507. func(args)
  508. # Like a Set[Guard] but will record the user stack on all guards at the
  509. # time they were installed at their destination
  510. class GuardsSet:
  511. def __init__(self, inner: Optional[OrderedSet[Guard]] = None) -> None:
  512. if inner is None:
  513. self.inner: OrderedSet[Guard] = OrderedSet()
  514. else:
  515. self.inner = inner
  516. def __iter__(self) -> Iterator[Guard]:
  517. return iter(self.inner)
  518. def __len__(self) -> int:
  519. return len(self.inner)
  520. # Subtraction along with bool is typically used to determine the delta of
  521. # added guards between checkpoints for higher order ops
  522. def __sub__(self, other: GuardsSet) -> GuardsSet:
  523. return GuardsSet(self.inner - other.inner)
  524. def __bool__(self) -> bool:
  525. return bool(self.inner)
  526. def add(
  527. self, guard: Guard, *, collect_debug_stack: bool = True, skip: int = 0
  528. ) -> None:
  529. if guard in self.inner:
  530. return
  531. if collect_debug_stack:
  532. if guard.stack is None:
  533. guard.stack = CapturedTraceback.extract(skip=1 + skip)
  534. if guard.user_stack is None:
  535. guard.user_stack = TracingContext.extract_stack()
  536. self.inner.add(guard)
  537. def update(self, *others: set[Guard]) -> None:
  538. for o in others:
  539. for g in o:
  540. self.add(g, skip=1)
  541. def remove_guards_with_source(self, source: Source) -> None:
  542. """Delete all guards that contains a given source"""
  543. from ._dynamo.source import is_from_source
  544. self.inner = OrderedSet(
  545. g for g in self.inner if not is_from_source(g.originating_source, source)
  546. )
  547. """
  548. A GuardsContext is a checkpointable representation of all the guards in the current tracing
  549. context. It's lifecycle is bound 1:1 to the tracing context, and it should never be instantiated
  550. directly outside of it. For passing around internal state representations of this object,
  551. prefer to extract them with copy_graphstate to produce a GuardsCheckpointState.
  552. """
  553. class GuardsContext(Checkpointable[GuardsCheckpointState]):
  554. def __init__(self) -> None:
  555. self.dynamo_guards: GuardsSet = GuardsSet()
  556. self.aotautograd_guards: list[GuardEnvExpr] = []
  557. def copy_graphstate(self) -> GuardsCheckpointState:
  558. return GuardsCheckpointState(OrderedSet(self.dynamo_guards.inner))
  559. def restore_graphstate(self, state: GuardsCheckpointState) -> None:
  560. # NB: "steals" the passed in state
  561. if not isinstance(state, GuardsCheckpointState):
  562. raise AssertionError(f"expected GuardsCheckpointState, got {type(state)}")
  563. self.dynamo_guards = GuardsSet(state.dynamo_guards)
  564. class HopSubgraphCache:
  565. @abstractmethod
  566. def add_dynamo_installed_submodule(self, fn_id: int, identifier: str) -> None: ...
  567. @abstractmethod
  568. def get_dynamo_installed_submodules(self, fn_id: int) -> list[str]: ...
  569. @abstractmethod
  570. def add_autograd_key_entry(self, identifier: str, key: Callable) -> None: ...
  571. @abstractmethod
  572. def get_autograd_key_entry(self, identifier: str) -> Callable | None: ...
  573. @abstractmethod
  574. def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None: ...
  575. @abstractmethod
  576. def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None: ...
  577. @abstractmethod
  578. def add_lazy_bwd_entry(
  579. self,
  580. identifier: str,
  581. tangent_metadata: tuple[object],
  582. gmod: torch.fx.GraphModule,
  583. ) -> int: ...
  584. @abstractmethod
  585. def get_lazy_bwd_entry(
  586. self, identifier: str, tangent_metadata: tuple[object]
  587. ) -> tuple[torch.fx.GraphModule | None, int | None]: ...
  588. class InvokeSubgraphCache(HopSubgraphCache):
  589. def __init__(self) -> None:
  590. self.autograd_cache: dict[str, Callable] = {}
  591. self.proxy_dispatch_cache: dict[str, Callable] = {}
  592. self.dynamo_installed_submodules: dict[int, list[str]] = defaultdict(list)
  593. self.lazy_bwd_cache: dict[
  594. str, dict[tuple[object], tuple[torch.fx.GraphModule, int]]
  595. ] = defaultdict(dict)
  596. self.effects_cache: dict[
  597. str, set
  598. ] = {} # Maps identifier -> set of effect types
  599. def add_dynamo_installed_submodule(self, fn_id: int, identifier: str) -> None:
  600. self.dynamo_installed_submodules[fn_id].append(identifier)
  601. def get_dynamo_installed_submodules(self, fn_id: int) -> list[str]:
  602. return self.dynamo_installed_submodules.get(fn_id, [])
  603. def add_autograd_key_entry(self, identifier: str, key: Callable) -> None:
  604. self.autograd_cache[identifier] = key
  605. def get_autograd_key_entry(self, identifier: str) -> Callable | None:
  606. return self.autograd_cache.get(identifier, None)
  607. def add_proxy_dispatch_entry(self, identifier: str, key: Callable) -> None:
  608. self.proxy_dispatch_cache[identifier] = key
  609. def get_proxy_dispatch_entry(self, identifier: str) -> Callable | None:
  610. return self.proxy_dispatch_cache.get(identifier, None)
  611. def add_lazy_bwd_entry(
  612. self,
  613. identifier: str,
  614. tangent_metadata: tuple[object],
  615. gmod: torch.fx.GraphModule,
  616. ) -> int:
  617. # Save the number of existing graph modules in the dictionary to get the suffix
  618. num_gmods = len(self.lazy_bwd_cache[identifier])
  619. self.lazy_bwd_cache[identifier][tangent_metadata] = (gmod, num_gmods)
  620. return num_gmods
  621. def get_lazy_bwd_entry(
  622. self, identifier: str, tangent_metadata: tuple[object]
  623. ) -> tuple[torch.fx.GraphModule | None, int | None]:
  624. if identifier not in self.lazy_bwd_cache:
  625. return (None, None)
  626. return self.lazy_bwd_cache[identifier].get(tangent_metadata, (None, None))
  627. def add_effects(self, identifier: str, effects: set) -> None:
  628. """Store the effect types for a given invoke_subgraph identifier."""
  629. if prev_effects := self.effects_cache.get(identifier, None):
  630. if effects != prev_effects:
  631. raise AssertionError(
  632. "Different number of effects were found for invoke_subgraph "
  633. f"call with identifier {identifier}. \n"
  634. f"Previously we had the following effects: {prev_effects}.\n"
  635. f"But now we have: {effects}."
  636. )
  637. self.effects_cache[identifier] = effects
  638. def get_effects(self, identifier: str) -> set | None:
  639. """Retrieve the effect types for a given invoke_subgraph identifier."""
  640. return self.effects_cache.get(identifier, None)
  641. class HopDispatchSetCache:
  642. def __init__(self) -> None:
  643. # Delayed import to avoid circular dependency
  644. from torch._higher_order_ops.invoke_subgraph import invoke_subgraph
  645. self.hop_cache_map = {invoke_subgraph: InvokeSubgraphCache()}
  646. def get_cache(self, op: torch._ops.HigherOrderOperator) -> HopSubgraphCache | None:
  647. if op not in self.hop_cache_map:
  648. return None
  649. return self.hop_cache_map[op] # type: ignore[index]
  650. _TLS = threading.local()
  651. """
  652. TracingContext is the source of truth for all currently accumulated information
  653. needed to trace. Its lifecycle is kept 1:1 when using TorchDynamo, but other systems
  654. are open to managing their own TracingContext with that in mind.
  655. The purpose of TracingContext is not to be a dumping ground, or god object, but rather to avoid
  656. having to plumb complex subsystems across multiple verticals.
  657. Ex: A common example is guard accumulation between dynamo, shape_env, aot_autograd, and inductor.
  658. Accessing the current tracing context via
  659. TracingContext.get() allows users to accumulate their own guards for processing, without needing to know how
  660. to plumb objects back up to where frame interpretation happened.
  661. Note that you can end up with multiple TracingContext for a single compilation
  662. of a frame, as we reset the TracingContext whenever we restart analysis.
  663. CompileContext is a more overarching context that encompasses multiple restarts.
  664. """
  665. class CompileContext:
  666. @staticmethod
  667. def get() -> CompileContext:
  668. if _TLS.compile_context is None:
  669. raise AssertionError("compile_context is not set")
  670. return _TLS.compile_context
  671. @staticmethod
  672. def try_get() -> CompileContext | None:
  673. return getattr(_TLS, "compile_context", None)
  674. def __init__(self, compile_id: CompileId | None) -> None:
  675. if compile_id is not None and not isinstance(compile_id, CompileId):
  676. raise AssertionError(
  677. f"compile_id must be None or CompileId, got {type(compile_id)}"
  678. )
  679. self.compile_id: CompileId | None = compile_id
  680. self.attempt = 0
  681. # Verbose ShapeEnv guards produced.
  682. self.shape_env_guards: list[str] = []
  683. @staticmethod
  684. def current_compile_id() -> CompileId | None:
  685. self = CompileContext.try_get()
  686. if self is None:
  687. return None
  688. return self.compile_id
  689. @staticmethod
  690. def current_trace_id() -> TraceId | None:
  691. self = CompileContext.try_get()
  692. if self is None:
  693. return None
  694. if self.compile_id is None:
  695. return None
  696. return TraceId(self.compile_id, self.attempt)
  697. @dataclass
  698. class InlinedCodeCache:
  699. """Cache for code-object-derived data used during inlining."""
  700. instructions: list[Any]
  701. indexof: dict[Any, int]
  702. code_options: dict[str, Any]
  703. class TracingContext:
  704. """
  705. Provides the currently installed TracingContext, or None.
  706. Note that it is a staticmethod, and invocations outside of `with tracing()` (see below), are valid but
  707. will return None.
  708. """
  709. @staticmethod
  710. def try_get() -> TracingContext | None:
  711. return getattr(_TLS, "tracing_context", None)
  712. @staticmethod
  713. def get() -> TracingContext:
  714. if ctx := TracingContext.try_get():
  715. return ctx
  716. raise RuntimeError(
  717. "TracingContext.get() must be called within an ongoing trace."
  718. )
  719. def __init__(self, fake_mode: FakeTensorMode | None) -> None:
  720. self.guards_context = GuardsContext()
  721. self.module_context = ModuleContext()
  722. self.global_context = GlobalContext()
  723. self.previously_inlined_functions: dict[Any, Any] = dict()
  724. self.previously_cleaned_instructions: dict[Any, Any] = dict()
  725. # Combined cache for inlined code data (instructions, indexof, code_options)
  726. self.inlined_code_cache: dict[Any, InlinedCodeCache] = dict()
  727. self.fake_mode: FakeTensorMode | None = fake_mode
  728. self.frame_summary_stack: list[traceback.FrameSummary] = []
  729. # This is morally part of frame_summary_stack, but it is kept separate
  730. # for clarity. As we process a frame, this variable gets updated
  731. # to keep track of what line we are in the function. We make a
  732. # function call, this gets cleared and the frame location is pushed
  733. # to frame_summary_stack (prepping this variable for the inner frame's
  734. # progress)
  735. self.loc_in_frame: tuple[str, int, str] | None = None
  736. # this is only set after aot_autograd
  737. self.fw_metadata: ViewAndMutationMeta | None = None
  738. # this is only set when the DDPOptimizer is used
  739. self.ddp_optimizer_ctx: DDPOptimizerContext | None = None
  740. # this is only set after aot_autograd
  741. self.aot_graph_name: list[str] | None = None
  742. self.params_flat: list[Any] | None = None
  743. self.params_flat_unwrap_subclasses: list[Any] | None = None
  744. self.params_unwrapped_to_flat_index: list[Any] | None = None
  745. # this is for extended return calling convention from backend
  746. # compiler to aot_autograd
  747. # Per output, what the compiler specified stride of the output is,
  748. # or None if no stride is known. This is always the HINT, it
  749. # is never a SymInt (it would be better if it was a SymInt, but
  750. # I can't conveniently get this from Inductor atm. Also, be
  751. # careful not to accidentally induce guards on the SymInt if
  752. # you ever do change this in aot_autograd.py; you should check
  753. # on permutations preferentially.)
  754. self.output_strides: list[tuple[int, ...] | None] | None = None
  755. # When this is True, whenever we encounter an int in Dynamo tracing,
  756. # we will (1) force unspec it and (2) force it as a size-like unbacked
  757. # integer. This is currently used when processing certain lists of
  758. # ints that are known to be size-like and may have 0/1 entries that we
  759. # must not specialize on.
  760. self.force_unspec_int_unbacked_size_like = False
  761. # See note [Tensor Fakification and Symbol Caching]
  762. self.tensor_to_context = WeakTensorKeyDictionary()
  763. # If this true, Aot Autograd will return output Fake Tensors with appropriate
  764. # meta on the first invocation
  765. # see note: [Returning Fake Tensors on First AOT Autograd Call]
  766. self.fakify_first_call = False
  767. self.hop_dispatch_set_cache = HopDispatchSetCache()
  768. # list of code objects for inlined functions
  769. self.traced_code: list[CodeType] = []
  770. def clear(self) -> None:
  771. # Look at the note in output_graph.py in function `save_global_state`
  772. # for the context on clearing global context.
  773. self.global_context.global_state = {}
  774. self.previously_inlined_functions.clear()
  775. self.previously_cleaned_instructions.clear()
  776. self.inlined_code_cache.clear()
  777. @staticmethod
  778. @contextmanager
  779. def patch(**kwargs: Any) -> Generator[None, None, None]:
  780. prior = {}
  781. ctx = TracingContext.get()
  782. for key in kwargs:
  783. # KeyError on invalid entry
  784. prior[key] = getattr(ctx, key)
  785. for key, val in kwargs.items():
  786. setattr(ctx, key, val)
  787. try:
  788. yield
  789. finally:
  790. for key, val in prior.items():
  791. setattr(ctx, key, val)
  792. @staticmethod
  793. def extract_stack() -> traceback.StackSummary:
  794. self = TracingContext.try_get()
  795. if self is None:
  796. return traceback.StackSummary()
  797. stack = self.frame_summary_stack
  798. if self.loc_in_frame is not None:
  799. stack = stack + [self._populate_loc_in_frame_summary()]
  800. return traceback.StackSummary.from_list(stack)
  801. def _populate_loc_in_frame_summary(self) -> traceback.FrameSummary:
  802. if self.loc_in_frame is None:
  803. raise AssertionError("loc_in_frame must not be None")
  804. filename, lineno, frame_name = self.loc_in_frame
  805. return traceback.FrameSummary(filename, lineno, frame_name, lookup_line=False)
  806. # Call this when you want to call into some code that isn't necessarily
  807. # associated with the current frame state
  808. @staticmethod
  809. @contextlib.contextmanager
  810. def clear_frame() -> Generator[None, None, None]:
  811. tc = TracingContext.get()
  812. with (
  813. unittest.mock.patch.object(tc, "frame_summary_stack", []),
  814. unittest.mock.patch.object(tc, "loc_in_frame", None),
  815. ):
  816. try:
  817. yield
  818. except Exception as e:
  819. # Prevent real_stack from getting attached
  820. #
  821. # The invariant is that if an Exception as real_stack, we've
  822. # appropriately attached a user stack and we no longer need to
  823. # attach anything. Because we cannot conveniently interpose
  824. # when an exception is thrown, we instead interpose everywhere
  825. # we set what the user stack is set (using the context
  826. # manager). However, our compiler stack does "tail calls"
  827. # (when it calls into user compiler), at which point the
  828. # parent exception frames would incorrectly attach an
  829. # incorrect frame.
  830. #
  831. # However, if, somehow, someone raised an exception with this
  832. # scope that had a stack (for example, because they are
  833. # restoring the user stack state appropriately as they process
  834. # node by node), we should respect it. Thus, we cannot
  835. # unconditionally set None.
  836. if not hasattr(e, "real_stack"):
  837. e.real_stack = None # type: ignore[attr-defined]
  838. raise
  839. @staticmethod
  840. @contextlib.contextmanager
  841. def current_frame(
  842. frame_summary: traceback.FrameSummary | None,
  843. ) -> Generator[None, None, None]:
  844. # frame_summary can be None to solely take advantage of real_stack
  845. # attachment to thrown exceptions
  846. tc = TracingContext.get()
  847. if frame_summary is not None:
  848. tc.frame_summary_stack.append(frame_summary)
  849. old = tc.loc_in_frame
  850. tc.loc_in_frame = None
  851. try:
  852. yield
  853. except Exception as e:
  854. if not hasattr(e, "real_stack"):
  855. e.real_stack = tc.extract_stack() # type: ignore[attr-defined]
  856. raise
  857. finally:
  858. if frame_summary is not None:
  859. tc.frame_summary_stack.pop()
  860. tc.loc_in_frame = old
  861. @staticmethod
  862. @contextlib.contextmanager
  863. def report_output_strides() -> Generator[
  864. list[tuple[int, ...] | None] | None, None, None
  865. ]:
  866. tc = TracingContext.try_get()
  867. if tc is None:
  868. yield None
  869. return
  870. old_output_strides = tc.output_strides
  871. tc.output_strides = []
  872. try:
  873. yield tc.output_strides
  874. finally:
  875. tc.output_strides = old_output_strides
  876. @staticmethod
  877. def set_current_loc(filename: str, lineno: int, frame_name: str) -> None:
  878. # Save the current location in the frame. Lazily generate the
  879. # framesummary.
  880. TracingContext.get().loc_in_frame = (filename, lineno, frame_name)
  881. @staticmethod
  882. def get_traced_code() -> list[CodeType] | None:
  883. tc = TracingContext.try_get()
  884. if tc is None:
  885. return None
  886. return tc.traced_code
  887. @contextmanager
  888. def compile_context(
  889. context: CompileContext | None,
  890. ) -> Generator[CompileContext | None, None, None]:
  891. old_context = getattr(_TLS, "compile_context", None)
  892. _TLS.compile_context = context
  893. try:
  894. yield context
  895. finally:
  896. _TLS.compile_context = old_context
  897. @contextmanager
  898. def tracing(
  899. context: TracingContext | None,
  900. ) -> Generator[TracingContext | None, None, None]:
  901. """
  902. This function installs the passed in tracing context as a dynamic scoped
  903. global variable.
  904. Calls to TracingContext.get() while not under a `with tracing()` context
  905. will return None.
  906. """
  907. old_context = getattr(_TLS, "tracing_context", None)
  908. _TLS.tracing_context = context
  909. try:
  910. yield context
  911. except Exception as e:
  912. if not hasattr(e, "real_stack") and context is not None:
  913. e.real_stack = context.extract_stack() # type: ignore[attr-defined]
  914. raise
  915. finally:
  916. if (
  917. context is not None
  918. and context.fake_mode is not None
  919. and context.fake_mode.shape_env is not None
  920. ):
  921. context.fake_mode.shape_env.cleanup()
  922. _TLS.tracing_context = old_context
  923. @overload
  924. def dataclass_with_cached_hash(cls: type[T], **kwargs: Any) -> type[T]: ...
  925. @overload
  926. def dataclass_with_cached_hash(
  927. cls: None = None, **kwargs: Any
  928. ) -> Callable[[type[T]], type[T]]: ...
  929. @dataclass_transform()
  930. def dataclass_with_cached_hash(
  931. cls: type[T] | None = None, **kwargs: Any
  932. ) -> type[T] | Callable[[type[T]], type[T]]:
  933. def wrap(cls_inner: type[T]) -> type[T]:
  934. new_cls = dataclasses.dataclass(cls_inner, **kwargs)
  935. old_hash = cls_inner.__hash__
  936. def __hash__(self) -> int:
  937. if not hasattr(self, "_hash"):
  938. object.__setattr__(self, "_hash", old_hash(self))
  939. return self._hash
  940. def __reduce__(self):
  941. # Exclude _hash from pickling to ensure deterministic cache keys.
  942. # The _hash is a cached value that can be nondeterministically computed
  943. # (e.g., based on id() of objects), so it should not affect pickling.
  944. fields = dataclasses.fields(self)
  945. field_values = tuple(getattr(self, f.name) for f in fields)
  946. return (self.__class__, field_values)
  947. new_cls.__hash__ = __hash__
  948. new_cls.__reduce__ = __reduce__
  949. return new_cls # type: ignore[return-value]
  950. if cls is None:
  951. return wrap
  952. return wrap(cls)
  953. # Subclasses can be found in torch/_dynamo/source.py
  954. # TODO(voz): Consider a toplevel torch/_source.py
  955. @dataclass_with_cached_hash(frozen=True)
  956. class Source:
  957. def is_dict_key(self) -> bool:
  958. return False
  959. def is_ephemeral(self) -> bool:
  960. return False
  961. def reconstruct(self, codegen: PyCodegen) -> None:
  962. raise NotImplementedError
  963. @functools.cached_property
  964. def guard_source(self) -> GuardSource:
  965. raise NotImplementedError
  966. @property
  967. def _name_template(self) -> str:
  968. """
  969. A template for the name of the source. Used to prevent code duplication between
  970. `name` and `get_value`.
  971. For non-ChainedSources, `name` and `get_value` use the returned string directly.
  972. For ChainedSources, `name` and `get_value` expect the return to be a format string
  973. with `{0}` present - `name` and `get_value` will apply different values to this function's
  974. returned format string.
  975. """
  976. raise NotImplementedError
  977. @functools.cached_property
  978. def name(self) -> str:
  979. return self._name_template
  980. def get_value(
  981. self,
  982. globals: dict[str, Any],
  983. locals: dict[str, Any],
  984. cache: weakref.WeakKeyDictionary[Source, Any],
  985. ) -> Any:
  986. if self in cache:
  987. return cache[self]
  988. value = eval(self._name_template, globals, locals)
  989. cache[self] = value
  990. return value
  991. def make_guard(self, fn: Callable[..., Any]) -> Guard:
  992. if self.guard_source is GuardSource.CONSTANT:
  993. raise NotImplementedError
  994. return Guard(self, fn)
  995. def is_specialized_nn_module(self) -> bool:
  996. return self.guard_source.is_specialized_nn_module()
  997. def subguards_allowed(self) -> bool:
  998. """True if you can guard on attributes of this"""
  999. return self.guard_source != GuardSource.SYNTHETIC_LOCAL
  1000. # Subclasses can be found in torch/_dynamo/source.py
  1001. @dataclass_with_cached_hash(frozen=True)
  1002. class ChainedSource(Source):
  1003. base: Source
  1004. def is_dict_key(self) -> bool:
  1005. # Recurse until you either hit a ConstDictKey or a Source
  1006. return self.base.is_dict_key()
  1007. def is_ephemeral(self) -> bool:
  1008. return self.base.is_ephemeral()
  1009. @functools.cached_property
  1010. def guard_source(self) -> GuardSource:
  1011. return self.base.guard_source
  1012. def get_base(self) -> Source:
  1013. current: Source = self
  1014. while isinstance(current, ChainedSource):
  1015. current = current.base
  1016. return current
  1017. @functools.cached_property
  1018. def name(self) -> str:
  1019. return self._name_template.format(self.base.name)
  1020. def get_value(
  1021. self,
  1022. globals: dict[str, Any],
  1023. locals: dict[str, Any],
  1024. cache: weakref.WeakKeyDictionary[Source, Any],
  1025. ) -> Any:
  1026. if self in cache:
  1027. return cache[self]
  1028. tmpvar = "tmp"
  1029. counter = 0
  1030. while tmpvar in locals:
  1031. tmpvar = f"tmp{counter}"
  1032. counter += 1
  1033. locals[tmpvar] = self.base.get_value(globals, locals, cache)
  1034. value = eval(self._name_template.format(tmpvar), globals, locals)
  1035. del locals[tmpvar]
  1036. cache[self] = value
  1037. return value
  1038. def detect_fake_mode(inputs: Any = None) -> FakeTensorMode | None:
  1039. """
  1040. Attempts to "detect" what the current fake mode is. If there is one ambiently
  1041. available from TracingContext, we preferentially use that. Otherwise, we
  1042. heuristically detect the fake mode via the following sources, in order of
  1043. priority:
  1044. - Currently active fake mode on stack
  1045. - Fake mode associated with passed in tensors (inputs does not
  1046. have to be flattened)
  1047. """
  1048. from torch._subclasses.fake_tensor import (
  1049. FakeTensor,
  1050. FakeTensorMode,
  1051. get_plain_tensors,
  1052. )
  1053. # If TracingContext has a fake_mode, use it authoritatively.
  1054. # This is the case when Dynamo is driving compilation - any fake tensors
  1055. # from other modes in the inputs will be refakified by the caller.
  1056. if context := TracingContext.try_get():
  1057. fake_mode = context.fake_mode
  1058. if fake_mode is not None:
  1059. return fake_mode
  1060. fake_modes = []
  1061. from torch.utils._python_dispatch import _get_current_dispatch_mode_stack
  1062. for i, m in enumerate(reversed(_get_current_dispatch_mode_stack())):
  1063. if isinstance(m, FakeTensorMode):
  1064. fake_modes.append((m, "active fake mode", i))
  1065. flat_inputs = pytree.tree_leaves(inputs)
  1066. for i, flat_input in enumerate(flat_inputs):
  1067. if isinstance(flat_input, FakeTensor):
  1068. fake_modes.append((flat_input.fake_mode, "fake tensor input", i))
  1069. if is_traceable_wrapper_subclass(flat_input):
  1070. out: list[torch.Tensor | int | torch.SymInt] = []
  1071. get_plain_tensors(flat_input, out=out) # type: ignore[arg-type]
  1072. fake_tensors: list[FakeTensor] = [
  1073. x for x in out if isinstance(x, FakeTensor)
  1074. ]
  1075. fake_modes.extend(
  1076. [
  1077. (tensor.fake_mode, f"subclass input {i}", ix)
  1078. for ix, tensor in enumerate(fake_tensors)
  1079. ]
  1080. )
  1081. if fake_modes:
  1082. fake_mode, desc1, i1 = fake_modes[0]
  1083. for m, desc2, i2 in fake_modes[1:]:
  1084. if fake_mode is not m:
  1085. raise AssertionError(
  1086. f"fake mode ({fake_mode}) from {desc1} {i1} doesn't match mode ({m}) from {desc2} {i2}\n\n"
  1087. f"fake mode from {desc1} {i1} allocated at:\n{fake_mode.stack}\n"
  1088. f"fake mode from {desc2} {i2} allocated at:\n{m.stack}"
  1089. )
  1090. return fake_mode
  1091. else:
  1092. return None
  1093. def active_fake_mode() -> FakeTensorMode | None:
  1094. """
  1095. Inspects the dispatch mode stack for an active fake mode and returns it.
  1096. Returns None if no fake mode is active.
  1097. """
  1098. from torch._subclasses.fake_tensor import FakeTensorMode
  1099. from torch.utils._python_dispatch import _get_current_dispatch_mode_stack
  1100. for _, m in enumerate(reversed(_get_current_dispatch_mode_stack())):
  1101. if isinstance(m, FakeTensorMode):
  1102. return m
  1103. return None