base.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. # mypy: ignore-errors
  2. import collections
  3. from enum import Enum
  4. from typing import Any, Callable, Dict, List
  5. from .. import variables
  6. from ..current_scope_id import current_scope_id
  7. from ..exc import unimplemented
  8. from ..source import AttrSource, Source
  9. from ..utils import istype
  10. class MutableLocalSource(Enum):
  11. """
  12. If the VariableTracker.mutable_local represents a Variable that:
  13. - already existed that Dynamo began tracking while introspection (Existing)
  14. - is a new variable that is created during Dynamo introspection (Local)
  15. """
  16. Existing = 0
  17. Local = 1
  18. class MutableLocalBase:
  19. """
  20. Base class for Variable.mutable_local
  21. """
  22. def __init__(self, typ: MutableLocalSource):
  23. # In HigherOrderOperator tracing, we need to distinguish
  24. # between MutableLocals inside the HigherOrderOperator and
  25. # ones outside it. For example, it is not safe to mutate
  26. # `a` in the following example because it was constructed
  27. # in a different scope.
  28. #
  29. # def f(x):
  30. # a = 1
  31. # def g(x):
  32. # nonlocal a
  33. # a = 2
  34. # return x
  35. # return wrap(g, x) + a
  36. #
  37. # We use self.scope to distinguish this.
  38. # scope == 0: The object was an existing variable
  39. # scope == 1: The object was created while Dynamo
  40. # was introspecting a function
  41. # (and no HigherOrderOps were involved)
  42. # scope >= 2: The object was created through
  43. # Dynamo introspection of a HigherOrderOp.
  44. # The exact number corresponds to the level
  45. # of nested HigherOrderOps.
  46. if typ is MutableLocalSource.Existing:
  47. self.scope = 0
  48. elif typ is MutableLocalSource.Local:
  49. self.scope = current_scope_id()
  50. else:
  51. unimplemented(f"Unsupported MutableLocalSource: {typ}")
  52. class MutableLocal(MutableLocalBase):
  53. """
  54. Marker used to indicate this (list, iter, etc) was constructed in
  55. local scope and can be mutated safely in analysis without leaking
  56. state.
  57. """
  58. def __init__(self):
  59. super().__init__(MutableLocalSource.Local)
  60. def __hash__(self):
  61. return id(self)
  62. def __eq__(self, other):
  63. return self is other
  64. def _is_top_level_scope(scope_id):
  65. return scope_id == 1
  66. def is_side_effect_safe(m: MutableLocalBase):
  67. scope_id = current_scope_id()
  68. # In the top-level scope (if no HigherOrderOperators are involved),
  69. # we are allowed to modify variables created in this scope as well
  70. # as existing variables.
  71. if _is_top_level_scope(scope_id):
  72. return True
  73. # Otherwise, only allow local mutation of variables created in the current scope
  74. return m.scope == scope_id
  75. class VariableTrackerMeta(type):
  76. all_subclasses = []
  77. def __instancecheck__(cls, instance) -> bool:
  78. """Make isinstance work with LazyVariableTracker"""
  79. if type.__instancecheck__(
  80. variables.LazyVariableTracker, instance
  81. ) and cls not in (
  82. VariableTracker,
  83. variables.LazyVariableTracker,
  84. ):
  85. instance = instance.realize()
  86. return type.__instancecheck__(cls, instance)
  87. def __init__(cls, name, bases, attrs):
  88. super().__init__(name, bases, attrs)
  89. VariableTrackerMeta.all_subclasses.append(cls)
  90. class VariableTracker(metaclass=VariableTrackerMeta):
  91. """
  92. Base class for tracked locals and stack values
  93. VariableTracker instances are immutable and should be copied in
  94. order to change them.
  95. """
  96. # fields to leave unmodified in apply()
  97. _nonvar_fields = {
  98. "value",
  99. "guards",
  100. "source",
  101. "mutable_local",
  102. "parents_tracker",
  103. "user_code_variable_name",
  104. }
  105. def clone(self, **kwargs):
  106. """Shallow copy with some (optional) changes"""
  107. args = dict(self.__dict__)
  108. args.update(kwargs)
  109. return self.__class__(**args)
  110. @classmethod
  111. def visit(
  112. cls,
  113. fn: Callable[["VariableTracker"], None],
  114. value,
  115. cache=None,
  116. ):
  117. """
  118. Walk value and call fn on all the VariableTracker instances
  119. """
  120. if cache is None:
  121. cache = dict()
  122. idx = id(value)
  123. if idx in cache:
  124. return
  125. # save `value` to keep it alive and ensure id() isn't reused
  126. cache[idx] = value
  127. if isinstance(value, VariableTracker):
  128. value = value.unwrap()
  129. fn(value)
  130. value = value.unwrap() # calling fn() might have realized it
  131. nonvars = value._nonvar_fields
  132. for key, subvalue in value.__dict__.items():
  133. if key not in nonvars:
  134. cls.visit(fn, subvalue, cache)
  135. elif istype(value, (list, tuple)):
  136. for subvalue in value:
  137. cls.visit(fn, subvalue, cache)
  138. elif istype(value, (dict, collections.OrderedDict)):
  139. for subvalue in value.values():
  140. cls.visit(fn, subvalue, cache)
  141. def __repr__(self):
  142. return f"{self.__class__.__name__}()"
  143. def debug_repr(self):
  144. # Intended to be overridden to provide more info
  145. try:
  146. return repr(self.as_python_constant())
  147. except NotImplementedError:
  148. return repr(self)
  149. def python_type(self):
  150. """
  151. Abstract method to be implemented by subclasses of VariableTracker.
  152. This method should return the type represented by the instance of the subclass.
  153. The purpose is to provide a standardized way to retrieve the Python type information
  154. of the variable being tracked.
  155. Returns:
  156. type: The Python type (such as int, str, list, etc.) of the variable tracked by
  157. the subclass. If the type cannot be determined or is not relevant,
  158. leaving it undefined or invoking super() is always sound.
  159. Note:
  160. This is an abstract method and may be overridden in subclasses.
  161. Example:
  162. class SetVariable(VariableTracker):
  163. def python_type(self):
  164. return set
  165. Raises:
  166. NotImplementedError: If the method is not implemented in a subclass.
  167. """
  168. raise NotImplementedError(f"{self} has no type")
  169. def as_python_constant(self):
  170. """For constants"""
  171. raise NotImplementedError(f"{self} is not a constant")
  172. def guard_as_python_constant(self):
  173. """Similar to as_python_constant(), but add ID_MATCH guards to try to force things to become constants"""
  174. try:
  175. return self.as_python_constant()
  176. except NotImplementedError as e:
  177. unimplemented(str(e))
  178. def is_python_constant(self):
  179. try:
  180. self.as_python_constant()
  181. return True
  182. except NotImplementedError:
  183. return False
  184. def make_guard(self, fn):
  185. if self.source:
  186. return self.source.make_guard(fn)
  187. raise NotImplementedError
  188. def const_getattr(self, tx, name: str) -> Any:
  189. """getattr(self, name) returning a python constant"""
  190. raise NotImplementedError
  191. def var_getattr(self, tx, name: str) -> "VariableTracker":
  192. """getattr(self, name) returning a new variable"""
  193. value = self.const_getattr(tx, name)
  194. if not variables.ConstantVariable.is_literal(value):
  195. raise NotImplementedError
  196. source = None
  197. if self.source:
  198. source = AttrSource(self.source, name)
  199. return variables.ConstantVariable.create(value, source=source)
  200. def is_proxy(self):
  201. try:
  202. self.as_proxy()
  203. return True
  204. except NotImplementedError:
  205. return False
  206. def as_proxy(self):
  207. raise NotImplementedError(str(self))
  208. def maybe_fx_node(self):
  209. try:
  210. proxy = self.as_proxy()
  211. import torch.fx
  212. if isinstance(proxy, torch.fx.Proxy):
  213. return proxy.node
  214. return None
  215. except NotImplementedError:
  216. return None
  217. def reconstruct(self, codegen):
  218. raise NotImplementedError
  219. def can_reconstruct(self, tx):
  220. """If it is possible to reconstruct the Python object this
  221. VariableTracker represents."""
  222. assert tx is tx.output.root_tx, "Only root tx can reconstruct"
  223. try:
  224. from ..codegen import PyCodegen
  225. cg = PyCodegen(tx)
  226. self.reconstruct(cg)
  227. return True
  228. except NotImplementedError:
  229. return False
  230. def unpack_var_sequence(self, tx) -> List["VariableTracker"]:
  231. raise NotImplementedError
  232. def has_unpack_var_sequence(self, tx) -> bool:
  233. try:
  234. self.unpack_var_sequence(tx)
  235. return True
  236. except NotImplementedError:
  237. return False
  238. def inspect_parameter_names(self) -> List[str]:
  239. unimplemented(f"inspect_parameter_names: {self}")
  240. def call_hasattr(self, tx, name: str) -> "VariableTracker":
  241. unimplemented(f"hasattr {self.__class__.__name__} {name}")
  242. def call_function(
  243. self, tx, args: "List[VariableTracker]", kwargs: "Dict[str, VariableTracker]"
  244. ) -> "VariableTracker":
  245. unimplemented(f"call_function {self} {args} {kwargs}")
  246. def call_method(
  247. self,
  248. tx,
  249. name,
  250. args: "List[VariableTracker]",
  251. kwargs: "Dict[str, VariableTracker]",
  252. ) -> "VariableTracker":
  253. if name == "__len__" and self.has_unpack_var_sequence(tx):
  254. assert not (args or kwargs)
  255. return variables.ConstantVariable.create(len(self.unpack_var_sequence(tx)))
  256. elif (
  257. name == "__getattr__"
  258. and len(args) == 1
  259. and args[0].is_python_constant()
  260. and not kwargs
  261. ):
  262. return self.var_getattr(tx, args[0].as_python_constant())
  263. unimplemented(f"call_method {self} {name} {args} {kwargs}")
  264. def set_name_hint(self, name):
  265. pass
  266. def realize(self) -> "VariableTracker":
  267. """Used by LazyVariableTracker to build the real VariableTracker"""
  268. return self
  269. def unwrap(self) -> "VariableTracker":
  270. """Used by LazyVariableTracker to return the real VariableTracker if it already exists"""
  271. return self
  272. def is_realized(self):
  273. """Used by LazyVariableTracker to indicate an unrealized node"""
  274. return True
  275. def next_variable(self, tx):
  276. unimplemented(f"next({self})")
  277. def is_strict_mode(self, tx):
  278. return tx.strict_checks_fn and tx.strict_checks_fn(self)
  279. def __init__(
  280. self,
  281. *,
  282. source: Source = None,
  283. mutable_local: MutableLocal = None,
  284. ):
  285. super().__init__()
  286. self.source = source
  287. self.mutable_local = mutable_local
  288. def typestr(*objs):
  289. if len(objs) == 1:
  290. (obj,) = objs
  291. if isinstance(obj, VariableTracker):
  292. return str(obj)
  293. else:
  294. return type(obj).__name__
  295. else:
  296. return " ".join(map(typestr, objs))