_guards.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import dataclasses
  2. import enum
  3. import logging
  4. import weakref
  5. from abc import ABC, abstractmethod
  6. from contextlib import contextmanager
  7. from typing import Callable, Generic, List, NamedTuple, Optional, Set, TypeVar
  8. log = logging.getLogger(__name__)
  9. # TODO(voz): Stolen pattern, not sure why this is the case,
  10. # but mypy complains.
  11. try:
  12. import sympy # type: ignore[import]
  13. except ImportError:
  14. log.warning("No sympy found")
  15. """
  16. torch._guards is the definitional source of truth for general purpose guard structures.
  17. An important thing to keep in mind here is the preservation of layering. There should be no dynamo notions,
  18. and no guard installation notions here.
  19. """
  20. class GuardSource(enum.Enum):
  21. LOCAL = 0
  22. GLOBAL = 1
  23. LOCAL_NN_MODULE = 2
  24. GLOBAL_NN_MODULE = 3
  25. CONSTANT = 4
  26. RANDOM_VALUE = 5
  27. SHAPE_ENV = 6
  28. def select(self, locals_, globals_):
  29. # SHAPE_ENV counts as locals, because the guard expressions
  30. # created by shape env can reference f_locals
  31. #
  32. # RANDOM_VALUE counts as locals, because what we do is we run
  33. # Python RNG and assign it to a temporary, and then perform
  34. # guard tests on that temporary
  35. if self in (
  36. GuardSource.LOCAL,
  37. GuardSource.LOCAL_NN_MODULE,
  38. GuardSource.SHAPE_ENV,
  39. GuardSource.RANDOM_VALUE,
  40. ):
  41. return locals_
  42. if self in (GuardSource.GLOBAL, GuardSource.GLOBAL_NN_MODULE):
  43. return globals_
  44. raise NotImplementedError(str(self))
  45. def is_nn_module(self) -> bool:
  46. return self in (GuardSource.GLOBAL_NN_MODULE, GuardSource.LOCAL_NN_MODULE)
  47. def is_local(self):
  48. return self in (GuardSource.LOCAL, GuardSource.LOCAL_NN_MODULE)
  49. """
  50. Base class for a "GuardBuilder" role.
  51. The GuardBuilderBase role is to represent a scope within which to build a guard. The name is a little
  52. confusing, as its not a builder, but for the sake of avoiding a lot of renames and keeping the original reference
  53. to torchdynamo's GuardBuilder.
  54. Note: create_fn is invoked with a GuardBuilderBase and a Guard. A GuardBuilder is chosen based
  55. on GuardSource's select function.
  56. There is value in keeping this GuardBuilderBase empty to keep layering clean.
  57. """
  58. class GuardBuilderBase:
  59. pass
  60. class ShapeGuard(NamedTuple):
  61. expr: sympy.Expr
  62. stack: str
  63. @dataclasses.dataclass
  64. class Guard:
  65. # The name of a Guard specifies what exactly it is the guard is guarding
  66. # on. The meaning of the name is dependent on the create_fn; you must
  67. # look at the use-site inside create_fn to know what name means.
  68. #
  69. # That being said, although you might think this is just a "name", name is
  70. # usually an arbitrary Python expression that will be evaluated with all
  71. # globals (and locals, if you create a LOCAL guard) to extract the Python
  72. # object that we want to perform guard tests on. This evaluation
  73. # typically happens in GuardBuilder.eval. In these cases, name is
  74. # typically produced by Source.name() (not to be confused with
  75. # GuardSource)--morally, we could have stored a Source here.
  76. #
  77. # Occasionally, name is not a valid Python expression; sometimes
  78. # it is meaningless. Example create_fns that are like this include
  79. # GRAD_MODE and SHAPE_ENV.
  80. name: str
  81. source: GuardSource
  82. create_fn: Callable[[GuardBuilderBase, "Guard"], None]
  83. is_volatile: bool = False
  84. # Export only. These values are written to at time of guard check_fn creation.
  85. guard_types: Optional[List[str]] = None
  86. code_list: Optional[List[str]] = None
  87. obj_weakref: Optional[object] = None
  88. guarded_class_weakref: Optional[type] = None
  89. def __hash__(self):
  90. return hash((self.name, self.source, id(self.create_fn)))
  91. def sort_key(self):
  92. return (
  93. self.source.value if self.source else -1,
  94. len(self.name),
  95. self.name,
  96. self.create_fn.__code__.co_firstlineno,
  97. )
  98. def __lt__(self, other):
  99. return self.sort_key() < other.sort_key()
  100. @staticmethod
  101. def weakref_to_str(obj_weakref):
  102. """
  103. This is a workaround of a Python weakref bug.
  104. `obj_weakref` is instance returned by `weakref.ref`,
  105. `str(obj_weakref)` is buggy if the original obj overrides __getattr__, e.g:
  106. class MyConfig(dict):
  107. def __getattr__(self, x):
  108. return self[x]
  109. obj = MyConfig(offset=5)
  110. obj_weakref = weakref.ref(obj)
  111. str(obj_weakref) # raise error: KeyError: '__name__'
  112. """
  113. if isinstance(obj_weakref, weakref.ReferenceType):
  114. obj = obj_weakref()
  115. if obj is not None:
  116. return f"<weakref at {hex(id(obj_weakref))}; to '{obj.__class__.__name__}' at {hex(id(obj))}>"
  117. else:
  118. return f"<weakref at {hex(id(obj_weakref))}; dead>"
  119. else:
  120. return str(obj_weakref)
  121. def __str__(self):
  122. s = f"""
  123. {self.source.name.lower() if self.source else ""} {repr(self.name)} {self.create_fn.__name__}
  124. {{
  125. 'guard_types': {self.guard_types},
  126. 'code': {self.code_list},
  127. 'obj_weakref': {self.weakref_to_str(self.obj_weakref)}
  128. 'guarded_class': {self.guarded_class_weakref}
  129. }}
  130. """
  131. return s
  132. def create(self, local_builder: GuardBuilderBase, global_builder: GuardBuilderBase):
  133. return self.create_fn(self.source.select(local_builder, global_builder), self)
  134. def is_nn_module(self):
  135. return self.source.is_nn_module()
  136. def is_local(self):
  137. return self.source.is_local()
  138. def set_export_info(self, guard_type, guarded_class, code_list, obj_weakref):
  139. if not self.guard_types:
  140. self.guard_types = list()
  141. self.guard_types.append(guard_type)
  142. assert self.guarded_class_weakref in (
  143. guarded_class,
  144. None,
  145. ), "Guarded class id must be identical, or None"
  146. self.guarded_class_weakref = guarded_class
  147. if not self.code_list:
  148. self.code_list = code_list
  149. else:
  150. self.code_list.extend(code_list)
  151. assert self.obj_weakref in (
  152. obj_weakref,
  153. None,
  154. ), "Guarded object must be identical, or None"
  155. self.obj_weakref = obj_weakref
  156. T = TypeVar("T")
  157. """
  158. Parent structure for guard env expressions.
  159. A GuardEnvExpr can have any subtype.
  160. Note: All subtypes must be handled exhaustively in
  161. torch._dynamo.guards._parse_guard_env_guards to avoid a RuntimeError.
  162. """
  163. @dataclasses.dataclass
  164. class GuardEnvExpr:
  165. pass
  166. """
  167. A class representing a pair of duplicate inputs.
  168. input_pos_a and input_pos_b are input positions we have deduped.
  169. """
  170. @dataclasses.dataclass
  171. class DuplicateInputs(GuardEnvExpr):
  172. input_pos_a: int
  173. input_pos_b: int
  174. def __post_init__(self):
  175. assert self.input_pos_a != self.input_pos_b
  176. """
  177. Checkpointable is an interface for driving state snapshotting, left purposely vague for now.
  178. copy_graphstate() -> T, a somewhat legacy name, is expected to emit a snapshot of any type that
  179. can also be taken in at restore_graphstate(T) calls.
  180. When to snapshot, is, at the moment, an implementation detail of upstream callers. Checkpointable
  181. does not provide any garuantees around consistency, idempotency, or safety of calling its APIs, yet.
  182. In the future, it will have a closer coupling to a generic Checkpoint management system.
  183. """
  184. class Checkpointable(ABC, Generic[T]):
  185. @abstractmethod
  186. def copy_graphstate(self) -> T:
  187. ...
  188. @abstractmethod
  189. def restore_graphstate(self, state: T):
  190. ...
  191. """
  192. The GuardCheckpointState - it is the T of Checkpointable[T] for GuardsContext
  193. """
  194. class GuardsCheckpointState:
  195. dynamo_guards: Set[Guard] = set()
  196. def __init__(self, dynamo_guards):
  197. self.dynamo_guards = dynamo_guards
  198. """
  199. Produces a delta against another GuardsCheckpointState.
  200. Returns None if no delta is found, otherwise, return a set() of mismatched
  201. Guard type objects.
  202. """
  203. def diff(self, other):
  204. r = self.dynamo_guards.difference(other.dynamo_guards)
  205. if len(r) == 0:
  206. return None
  207. return r
  208. def __eq__(self, other):
  209. return self.diff(other) is None
  210. """
  211. A GuardsContext is a checkpointable representation of all the guards in the current tracing
  212. context. It's lifecycle is bound 1:1 to the tracing context, and it should never be instantiated
  213. directly outside of it. For passing around internal state representations of this object,
  214. prefer to extract them with copy_graphstate to produce a GuardsCheckpointState.
  215. """
  216. class GuardsContext(Checkpointable[GuardsCheckpointState]):
  217. def __init__(self):
  218. self.dynamo_guards: Set[Guard] = set()
  219. self.aotautograd_guards: List[GuardEnvExpr] = []
  220. def copy_graphstate(self):
  221. return GuardsCheckpointState(set(self.dynamo_guards))
  222. def restore_graphstate(self, state):
  223. assert isinstance(state, GuardsCheckpointState)
  224. self.dynamo_guards = state.dynamo_guards
  225. _CURRENT_TRACING_CONTEXT = None
  226. """
  227. TracingContext is the source of truth for all currently accumulated information
  228. needed to trace. Its lifecycle is kept 1:1 when using TorchDynamo, but other systems
  229. are open to managing their own TracingContext with that in mind.
  230. Currently, only guards live on the TracingContext, in the form of a GuardsContext.
  231. However, future implementations will move FakeTensorMode (and its owned ShapeEnv), as well
  232. as other structures into it.
  233. The purpose of TracingContext is not to be a dumping ground, or god object, but rather to avoid
  234. having to plumb complex subsystems across multiple verticals.
  235. Ex: A common example is guard accumulation between dynamo, shape_env, aot_autograd, and inductor.
  236. Accessing the current tracing context via
  237. TracingContext.get() allows users to accumulate their own guards for processing, without needing to know how
  238. to plumb objects back up to where frame interpretation happend.
  239. """
  240. class TracingContext:
  241. """
  242. Provides the currently installed TracingContext, or None.
  243. Note that it is a staticmethod, and invocations outside of `with tracing()` (see below), are valid but
  244. will return NoNe.
  245. """
  246. @staticmethod
  247. def get() -> Optional["TracingContext"]:
  248. return _CURRENT_TRACING_CONTEXT
  249. def __init__(self, fake_mode):
  250. self.guards_context = GuardsContext()
  251. self.fake_mode = fake_mode
  252. """
  253. This function installs the passed in tracing context as a dynamic scoped global variable.
  254. Calls to TracingContext.get() while not under a `with tracing()` context will return None.
  255. """
  256. @contextmanager
  257. def tracing(context: TracingContext):
  258. global _CURRENT_TRACING_CONTEXT
  259. old_context = _CURRENT_TRACING_CONTEXT
  260. _CURRENT_TRACING_CONTEXT = context
  261. try:
  262. yield _CURRENT_TRACING_CONTEXT
  263. finally:
  264. _CURRENT_TRACING_CONTEXT = old_context
  265. # Subclasses can be found in torch/_dynamo/source.py
  266. @dataclasses.dataclass
  267. class Source:
  268. def reconstruct(self, codegen):
  269. raise NotImplementedError()
  270. def guard_source(self):
  271. raise NotImplementedError()
  272. def name(self):
  273. raise NotImplementedError()
  274. def make_guard(self, fn, is_volatile=False):
  275. if self.guard_source() is GuardSource.CONSTANT:
  276. raise NotImplementedError()
  277. return Guard(self.name(), self.guard_source(), fn, is_volatile)
  278. def is_nn_module(self):
  279. return self.guard_source() in (
  280. GuardSource.LOCAL_NN_MODULE,
  281. GuardSource.GLOBAL_NN_MODULE,
  282. )