source.py 43 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300
  1. """
  2. This module provides Source classes that track the origins of values in PyTorch Dynamo.
  3. Sources represent where values come from (e.g. local variables, globals, attributes) and
  4. are used for guard generation and code reconstruction during compilation.
  5. The module includes specialized sources for:
  6. - Local variables and synthetic locals
  7. - Global variables and constants
  8. - Object attributes and method calls
  9. - NN module specialization (specialized vs unspecialized)
  10. - Random values and tensor properties
  11. - Default argument handling
  12. - FSDP (Fully Sharded Data Parallel) modules
  13. Sources play a key role in Dynamo's guard system by tracking value origins for
  14. guard generation, and in code reconstruction by providing methods to rebuild
  15. the code needed to recreate values.
  16. """
  17. import dataclasses
  18. import enum
  19. import functools
  20. from collections.abc import Callable
  21. from typing import Any, Optional, TYPE_CHECKING, Union
  22. from torch import device as device_type
  23. from torch._guards import (
  24. ChainedSource,
  25. dataclass_with_cached_hash,
  26. Guard,
  27. GuardSource,
  28. Source,
  29. )
  30. from . import utils
  31. from .bytecode_transformation import (
  32. create_binary_subscr,
  33. create_build_tuple,
  34. create_call_function,
  35. )
  36. if TYPE_CHECKING:
  37. from .codegen import PyCodegen
  38. # It shouldn't be supported to construct an NNModuleVariable inside an FSDP module,
  39. # so those cases are omitted intentionally
  40. # represents nn.Modules tracked with NNModuleVariable (specialized is implicit in the variable name)
  41. _GUARD_SOURCE_SPECIALIZED_NN_MODULE = {
  42. GuardSource.LOCAL: GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
  43. GuardSource.GLOBAL: GuardSource.GLOBAL_SPECIALIZED_NN_MODULE,
  44. GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_SPECIALIZED_NN_MODULE,
  45. GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_SPECIALIZED_NN_MODULE,
  46. # Just to ensure that guard_source() works
  47. GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE,
  48. GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE,
  49. GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  50. GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  51. GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE,
  52. GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE,
  53. }
  54. # represents nn.Modules tracked with UnspecializedNNModuleVariable
  55. _GUARD_SOURCE_UNSPECIALIZED_NN_MODULE = {
  56. GuardSource.LOCAL: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE,
  57. GuardSource.GLOBAL: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE,
  58. GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE,
  59. GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE,
  60. # this happens for an UnspecializedNNModule submodule on a NNModuleVariable
  61. GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE,
  62. GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE,
  63. # Just to ensure that guard_source() works
  64. GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  65. GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  66. GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE,
  67. GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE,
  68. }
  69. # represents nn.Modules tracked with UnspecializedBuiltinNNModuleVariable
  70. _GUARD_SOURCE_UNSPECIALIZED_BUILTIN_NN_MODULE = {
  71. GuardSource.LOCAL: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  72. GuardSource.GLOBAL: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  73. GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  74. GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  75. GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  76. GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  77. # Just to ensure that guard_source() works
  78. GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  79. GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE,
  80. GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE,
  81. GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE,
  82. }
  83. _GUARD_SOURCE_FSDP_MODULE = {
  84. GuardSource.LOCAL: GuardSource.LOCAL_FSDP_MODULE,
  85. GuardSource.GLOBAL: GuardSource.GLOBAL_FSDP_MODULE,
  86. GuardSource.LOCAL_SPECIALIZED_NN_MODULE: GuardSource.LOCAL_FSDP_MODULE,
  87. GuardSource.GLOBAL_SPECIALIZED_NN_MODULE: GuardSource.GLOBAL_FSDP_MODULE,
  88. GuardSource.LOCAL_FSDP_MODULE: GuardSource.LOCAL_FSDP_MODULE,
  89. GuardSource.GLOBAL_FSDP_MODULE: GuardSource.GLOBAL_FSDP_MODULE,
  90. GuardSource.LOCAL_UNSPECIALIZED_NN_MODULE: GuardSource.LOCAL_FSDP_MODULE,
  91. GuardSource.GLOBAL_UNSPECIALIZED_NN_MODULE: GuardSource.GLOBAL_FSDP_MODULE,
  92. GuardSource.LOCAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.LOCAL_FSDP_MODULE,
  93. GuardSource.GLOBAL_UNSPECIALIZED_BUILTIN_NN_MODULE: GuardSource.GLOBAL_FSDP_MODULE,
  94. }
  95. def is_constant_source(source: Source) -> bool:
  96. if isinstance(source, ConstantSource):
  97. return True
  98. try:
  99. if source.guard_source == GuardSource.CONSTANT:
  100. return True
  101. except NotImplementedError:
  102. pass
  103. return False
  104. def _get_source_debug_name(source: Optional[Source]) -> str:
  105. if source is None:
  106. return "<unknown source>"
  107. else:
  108. try:
  109. return source.name
  110. except NotImplementedError:
  111. return "<unknown source>"
  112. def _esc_str(s: Any, apply_repr: bool = False) -> str:
  113. """
  114. Escapes curly brackets for format strings.
  115. e.g. "frozenset({0})" becomes "frozenset({{0}})".
  116. This is used by _name_template for example, because it's
  117. expected to return a format string, but we may wish to include
  118. strings that should not be accidentally formatted.
  119. """
  120. if apply_repr:
  121. s = repr(s)
  122. else:
  123. s = str(s)
  124. return s.replace("{", "{{").replace("}", "}}")
  125. @dataclass_with_cached_hash(frozen=True)
  126. class LocalSource(Source):
  127. local_name: str
  128. # Whether this local is an input to the root frame.
  129. is_input: bool = False
  130. # Whether we know this input is dynamic (based on example_inputs)
  131. # For non tensors, we simply look at the first index of the tuple
  132. dynamism: Optional[frozenset[str]] = None
  133. # Whether the item at this source is the _content_ of a cell that is
  134. # dereferenced from the root frame, i.e., it's a part of the `co_cellvars`
  135. # or `co_freevars`.
  136. is_derefed_cell_contents: bool = False
  137. def reconstruct(self, codegen: "PyCodegen") -> None:
  138. if self.is_derefed_cell_contents:
  139. codegen.load_deref(self.local_name)
  140. else:
  141. codegen.append_output(codegen.create_load(self.local_name))
  142. @property
  143. def guard_source(self) -> GuardSource:
  144. return GuardSource.LOCAL
  145. @functools.cached_property
  146. def _name_template(self) -> str:
  147. return f"L[{_esc_str(self.local_name, apply_repr=True)}]"
  148. @dataclass_with_cached_hash(frozen=True)
  149. class TempLocalSource(Source):
  150. # like LocalSource, but cannot be guarded on
  151. local_name: str
  152. def reconstruct(self, codegen: "PyCodegen") -> None:
  153. codegen.append_output(codegen.create_load(self.local_name))
  154. @property
  155. def guard_source(self) -> GuardSource:
  156. return GuardSource.TEMP_LOCAL
  157. @property
  158. def _name_template(self) -> str:
  159. raise NotImplementedError(
  160. "Cannot create guard on TempLocalSource - this is an internal Dynamo bug. Please file an issue on GitHub."
  161. )
  162. @dataclass_with_cached_hash(frozen=True)
  163. class SyntheticLocalSource(Source):
  164. local_name: str
  165. def reconstruct(self, codegen: "PyCodegen") -> None:
  166. codegen.append_output(codegen.create_load(self.local_name))
  167. @property
  168. def guard_source(self) -> GuardSource:
  169. return GuardSource.SYNTHETIC_LOCAL
  170. @functools.cached_property
  171. def _name_template(self) -> str:
  172. return f"SYNTHETIC_LOCAL[{_esc_str(self.local_name, apply_repr=True)}]"
  173. @dataclass_with_cached_hash(frozen=True)
  174. class RandomValueSource(Source):
  175. random_call_index: int
  176. @property
  177. def guard_source(self) -> GuardSource:
  178. return GuardSource.RANDOM_VALUE
  179. def reconstruct(self, codegen: "PyCodegen") -> None:
  180. codegen.append_output(codegen.create_load(codegen.tx.output.random_values_var))
  181. codegen.append_output(codegen.create_load_const(self.random_call_index))
  182. codegen.append_output(create_binary_subscr())
  183. @functools.cached_property
  184. def _name_template(self) -> str:
  185. return f"random_value_{_esc_str(self.random_call_index)}"
  186. @dataclass_with_cached_hash(frozen=True)
  187. class GlobalSource(Source):
  188. global_name: str
  189. def reconstruct(self, codegen: "PyCodegen") -> None:
  190. codegen.append_output(codegen.create_load_global(self.global_name, add=True))
  191. @property
  192. def guard_source(self) -> GuardSource:
  193. return GuardSource.GLOBAL
  194. @functools.cached_property
  195. def _name_template(self) -> str:
  196. return f"G[{_esc_str(self.global_name, apply_repr=True)}]"
  197. @dataclass_with_cached_hash(frozen=True)
  198. class GlobalWeakRefSource(Source):
  199. global_name: str
  200. def reconstruct(self, codegen: "PyCodegen") -> None:
  201. codegen.add_push_null(
  202. lambda: codegen.append_output(
  203. codegen.create_load_global(self.global_name, add=True)
  204. )
  205. )
  206. codegen.extend_output(create_call_function(0, False))
  207. @property
  208. def guard_source(self) -> GuardSource:
  209. return GuardSource.GLOBAL
  210. @functools.cached_property
  211. def _name_template(self) -> str:
  212. return f"G[{_esc_str(self.global_name, apply_repr=True)}]()"
  213. @dataclass_with_cached_hash(frozen=True)
  214. class WeakRefCallSource(ChainedSource):
  215. def reconstruct(self, codegen: "PyCodegen") -> None:
  216. codegen.add_push_null(lambda: codegen(self.base))
  217. codegen.extend_output(create_call_function(0, False))
  218. @property
  219. def _name_template(self) -> str:
  220. return "{0}()"
  221. @dataclass_with_cached_hash(frozen=True)
  222. class CallFunctionNoArgsSource(WeakRefCallSource):
  223. pass
  224. @dataclass_with_cached_hash(frozen=True)
  225. class AttrSource(ChainedSource):
  226. member: str
  227. def __post_init__(self) -> None:
  228. assert self.base, "Can't construct an AttrSource without a valid base source"
  229. if "." in self.member:
  230. member_parts = self.member.split(".")
  231. object.__setattr__(
  232. self, "base", AttrSource(self.base, ".".join(member_parts[:-1]))
  233. )
  234. object.__setattr__(self, "member", member_parts[-1])
  235. def reconstruct(self, codegen: "PyCodegen") -> None:
  236. codegen(self.base)
  237. codegen.extend_output(codegen.create_load_attrs(self.member))
  238. @functools.cached_property
  239. def _name_template(self) -> str:
  240. if not self.member.isidentifier():
  241. return f"getattr({{0}}, {_esc_str(self.member, apply_repr=True)})"
  242. return f"{{0}}.{_esc_str(self.member)}"
  243. @dataclass_with_cached_hash(frozen=True)
  244. class GenericAttrSource(ChainedSource):
  245. member: str
  246. def __post_init__(self) -> None:
  247. assert self.base, "Can't construct an AttrSource without a valid base source"
  248. if "." in self.member:
  249. member_parts = self.member.split(".")
  250. object.__setattr__(
  251. self, "base", AttrSource(self.base, ".".join(member_parts[:-1]))
  252. )
  253. object.__setattr__(self, "member", member_parts[-1])
  254. def reconstruct(self, codegen: "PyCodegen") -> None:
  255. codegen(self.base)
  256. codegen.extend_output(codegen.create_load_attrs(self.member))
  257. @functools.cached_property
  258. def _name_template(self) -> str:
  259. return (
  260. f"object.__getattribute__({{0}}, {_esc_str(self.member, apply_repr=True)})"
  261. )
  262. # Represents obj.__dict__ where obj is a type object
  263. @dataclass_with_cached_hash(frozen=True)
  264. class TypeDictSource(ChainedSource):
  265. def reconstruct(self, codegen: "PyCodegen") -> None:
  266. codegen(self.base)
  267. codegen.extend_output(codegen.create_load_attrs("__dict__"))
  268. @property
  269. def _name_template(self) -> str:
  270. # type(ob).__dict__ can return a proxy of the dict. But in the C++
  271. # guard accessor, we are use type->tp_dict which is a dict. So,
  272. # forcefully pass a dict object to ensure that the GuardManager
  273. # registers that its working on a dict object.
  274. return "dict({0}.__dict__)"
  275. # Represents obj.__mro__ where object is type object
  276. @dataclass_with_cached_hash(frozen=True)
  277. class TypeMROSource(ChainedSource):
  278. def reconstruct(self, codegen: "PyCodegen") -> None:
  279. codegen(self.base)
  280. codegen.extend_output(codegen.create_load_attrs("__mro__"))
  281. @property
  282. def _name_template(self) -> str:
  283. return "{0}.__mro__"
  284. @dataclass_with_cached_hash(frozen=True)
  285. class LocalCellSource(Source):
  286. """
  287. Conceptually, this class is `LocalSource` for cell objects implicitly
  288. generated by Python (e.g., captured variables).
  289. """
  290. local_name: str
  291. def reconstruct(self, codegen: "PyCodegen") -> None:
  292. # Although `LOAD_FAST` and `LOAD_CLOSURE` have the same semantics,
  293. # Dynamo's bytecode transformation differentiates them slightly, so we
  294. # always emit `LOAD_CLOSURE` here.
  295. codegen.append_output(codegen.create_load_closure(self.local_name))
  296. # All the other methods are intentionally unimplemented because e.g., a
  297. # local cell object should never be used for guards.
  298. # Represents obj.__code__ where object is type object
  299. @dataclass_with_cached_hash(frozen=True)
  300. class CodeSource(ChainedSource):
  301. def reconstruct(self, codegen: "PyCodegen") -> None:
  302. codegen(self.base)
  303. codegen.extend_output(codegen.create_load_attrs("__code__"))
  304. @property
  305. def _name_template(self) -> str:
  306. return "{0}.__code__"
  307. # Represents obj.__closure__ where object is type object
  308. @dataclass_with_cached_hash(frozen=True)
  309. class ClosureSource(ChainedSource):
  310. def reconstruct(self, codegen: "PyCodegen") -> None:
  311. codegen(self.base)
  312. codegen.extend_output(codegen.create_load_attrs("__closure__"))
  313. @property
  314. def _name_template(self) -> str:
  315. return "{0}.__closure__"
  316. # Represents tensor.grad source. It could be represented by AttrSource as well.
  317. # But, we could access grad field on tensor directly in C++ without going
  318. # through the Python bytecodes. Therefore, we use a separate source for grad
  319. # field.
  320. @dataclass_with_cached_hash(frozen=True)
  321. class GradSource(ChainedSource):
  322. member: str = "grad"
  323. def reconstruct(self, codegen: "PyCodegen") -> None:
  324. codegen(self.base)
  325. codegen.extend_output(codegen.create_load_attrs(self.member))
  326. @functools.cached_property
  327. def _name_template(self) -> str:
  328. return f"{{0}}.{_esc_str(self.member)}"
  329. @dataclass_with_cached_hash(frozen=True)
  330. class ParamBufferSource(AttrSource):
  331. @functools.cached_property
  332. def guard_source(self) -> GuardSource:
  333. return _GUARD_SOURCE_SPECIALIZED_NN_MODULE[self.base.guard_source]
  334. # Special AttrSource to differentiate module._buffers or module._parameters
  335. @dataclass_with_cached_hash(frozen=True)
  336. class UnspecializedParamBufferSource(AttrSource):
  337. pass
  338. # This source is intended to be used in places where a source is needed but it is expected
  339. # that the symbol will be simplified out later on. Symbols with ephemeral sources are
  340. # prioritized to be simplified out when e.g. compared against a symbol without an ephemeral
  341. # source. Guarding on this source is an error.
  342. #
  343. # Example: During subclass view fake-ification, any close-over ViewFunc state should be
  344. # symbolicized / fake-ified to avoid invalid specialization during view replay. This source
  345. # is useful for symbols utilized in the middle of the view chain that are not expected to be
  346. # present within the final view shape metadata.
  347. @dataclass_with_cached_hash(frozen=True)
  348. class EphemeralSource(Source):
  349. desc: Optional[str] = None
  350. @property
  351. def guard_source(self) -> GuardSource:
  352. return GuardSource.EPHEMERAL
  353. @functools.cached_property
  354. def _name_template(self) -> str:
  355. desc = ": " + self.desc if self.desc is not None else ""
  356. return f"<ephemeral{_esc_str(desc)}>"
  357. def make_guard(self, fn: Callable[..., Any]) -> Guard:
  358. raise NotImplementedError
  359. def is_ephemeral(self) -> bool:
  360. return True
  361. @dataclass_with_cached_hash(frozen=True)
  362. class SkipGuardSource(ChainedSource):
  363. def reconstruct(self, codegen: "PyCodegen") -> None:
  364. self.base.reconstruct(codegen)
  365. @property
  366. def _name_template(self) -> str:
  367. return "{0}"
  368. class TensorProperty(enum.Enum):
  369. SIZE = 0
  370. STRIDE = 1
  371. STORAGE_OFFSET = 2
  372. def method_name(self) -> str:
  373. if self is TensorProperty.SIZE:
  374. return "size"
  375. elif self is TensorProperty.STRIDE:
  376. return "stride"
  377. elif self is TensorProperty.STORAGE_OFFSET:
  378. return "storage_offset"
  379. else:
  380. raise AssertionError(f"unhandled {_esc_str(self)}")
  381. @dataclass_with_cached_hash(frozen=True)
  382. class TensorPropertySource(ChainedSource):
  383. prop: TensorProperty
  384. idx: Optional[int] = None # None for STORAGE_OFFSET
  385. def __post_init__(self) -> None:
  386. assert self.base is not None
  387. if self.prop is TensorProperty.STORAGE_OFFSET:
  388. assert self.idx is None
  389. else:
  390. assert self.idx is not None
  391. def reconstruct(self, codegen: "PyCodegen") -> None:
  392. codegen.add_push_null(
  393. lambda: codegen.load_import_from(
  394. utils.__name__, f"call_{_esc_str(self.prop.method_name())}"
  395. )
  396. )
  397. codegen(self.base)
  398. if self.idx is not None:
  399. codegen.append_output(codegen.create_load_const(self.idx))
  400. codegen.extend_output(
  401. create_call_function(2 if self.idx is not None else 1, False)
  402. )
  403. @functools.cached_property
  404. def _name_template(self) -> str:
  405. if self.prop is TensorProperty.SIZE:
  406. return f"{{0}}.size()[{_esc_str(self.idx)}]"
  407. elif self.prop is TensorProperty.STRIDE:
  408. return f"{{0}}.stride()[{_esc_str(self.idx)}]"
  409. elif self.prop is TensorProperty.STORAGE_OFFSET:
  410. assert self.idx is None
  411. return "{0}.storage_offset()"
  412. else:
  413. raise AssertionError(f"unhandled {_esc_str(self.prop)}")
  414. @dataclass_with_cached_hash(frozen=True)
  415. class IndexedSource(ChainedSource):
  416. idx: int
  417. def __post_init__(self) -> None:
  418. assert self.base is not None
  419. def reconstruct(self, codegen: "PyCodegen") -> None:
  420. raise NotImplementedError
  421. @functools.cached_property
  422. def _name_template(self) -> str:
  423. return f"({_esc_str(self.idx)}, {{0}})"
  424. @dataclass_with_cached_hash(frozen=True)
  425. class NegateSource(ChainedSource):
  426. def __post_init__(self) -> None:
  427. assert self.base is not None
  428. def reconstruct(self, codegen: "PyCodegen") -> None:
  429. raise NotImplementedError
  430. @property
  431. def _name_template(self) -> str:
  432. # NB: use method call so that function stripping regexes work
  433. return "{0}.__neg__()"
  434. @dataclass_with_cached_hash(frozen=True)
  435. class ConvertIntSource(ChainedSource):
  436. def __post_init__(self) -> None:
  437. assert self.base is not None
  438. def reconstruct(self, codegen: "PyCodegen") -> None:
  439. codegen(self.base)
  440. @property
  441. def _name_template(self) -> str:
  442. return "cast_symbool_to_symint_guardless({0})"
  443. @dataclass_with_cached_hash(frozen=True)
  444. class DynamicScalarSource(ChainedSource):
  445. is_int: bool
  446. def __post_init__(self) -> None:
  447. assert self.base is not None
  448. def reconstruct(self, codegen: "PyCodegen") -> None:
  449. # Integer casting at reconstruction helps reduce the amount of DynamicInts returned
  450. # to the user, in favor of plain ints.
  451. # For example, a compiled region that only does int arithmetic could return a
  452. # DynamicInt without the casting here.
  453. codegen.add_push_null(lambda: codegen.load_import_from("builtins", "int"))
  454. codegen(self.base)
  455. codegen.extend_output(create_call_function(1, False))
  456. @property
  457. def _name_template(self) -> str:
  458. return "int({0})"
  459. @dataclass_with_cached_hash(frozen=True)
  460. class FlattenScriptObjectSource(ChainedSource):
  461. def __post_init__(self) -> None:
  462. assert self.base is not None
  463. def reconstruct(self, codegen: "PyCodegen") -> None:
  464. codegen(self.base)
  465. @property
  466. def _name_template(self) -> str:
  467. return "{0}.__obj_flatten__()"
  468. @dataclass_with_cached_hash(frozen=True)
  469. class ScriptObjectQualifiedNameSource(ChainedSource):
  470. def __post_init__(self) -> None:
  471. assert self.base is not None
  472. def reconstruct(self, codegen: "PyCodegen") -> None:
  473. codegen(self.base)
  474. @property
  475. def _name_template(self) -> str:
  476. return "{0}._type().qualified_name()"
  477. class AttrProxySource(ChainedSource):
  478. def reconstruct(self, codegen: "PyCodegen") -> None:
  479. codegen(self.base)
  480. @property
  481. def _name_template(self) -> str:
  482. return "{0}.get_base()"
  483. @dataclass_with_cached_hash(frozen=True)
  484. class DefaultsSource(ChainedSource):
  485. idx_key: Union[int, str]
  486. is_kw: bool = False
  487. field: str = dataclasses.field(init=False, repr=False, compare=False)
  488. _name: str = dataclasses.field(init=False, repr=False, compare=False)
  489. def __post_init__(self) -> None:
  490. assert self.base, (
  491. "Base must be a valid source in order to properly track and guard this Defaults to its origin."
  492. )
  493. if self.is_kw:
  494. assert isinstance(self.idx_key, str)
  495. object.__setattr__(self, "field", "__kwdefaults__")
  496. object.__setattr__(
  497. self,
  498. "_name",
  499. f"{{0}}.{_esc_str(self.field)}['{_esc_str(self.idx_key)}']",
  500. )
  501. else:
  502. assert isinstance(self.idx_key, int)
  503. object.__setattr__(self, "field", "__defaults__")
  504. object.__setattr__(
  505. self, "_name", f"{{0}}.{_esc_str(self.field)}[{_esc_str(self.idx_key)}]"
  506. )
  507. def reconstruct(self, codegen: "PyCodegen") -> None:
  508. codegen(self.base)
  509. codegen.extend_output(codegen.create_load_attrs(self.field))
  510. codegen.append_output(codegen.create_load_const(self.idx_key))
  511. codegen.append_output(create_binary_subscr())
  512. @functools.cached_property
  513. def _name_template(self) -> str:
  514. return self._name
  515. @dataclass_with_cached_hash(frozen=True)
  516. class GetItemSource(ChainedSource):
  517. index: Any
  518. index_is_slice: bool = False
  519. def __post_init__(self) -> None:
  520. assert self.base is not None
  521. if isinstance(self.index, slice):
  522. # store the hashable version of the slice so the whole GetItemSource is hashable
  523. super().__setattr__("index", self.index.__reduce__())
  524. super().__setattr__("index_is_slice", True)
  525. def reconstruct(self, codegen: "PyCodegen") -> None:
  526. codegen(self.base)
  527. if self.index_is_slice:
  528. codegen.append_output(codegen.create_load_const(self.unpack_slice()))
  529. else:
  530. codegen.append_output(codegen.create_load_const(self.index))
  531. codegen.append_output(create_binary_subscr())
  532. def unpack_slice(self) -> slice:
  533. assert self.index_is_slice
  534. slice_class, slice_args = self.index
  535. return slice_class(*slice_args)
  536. @functools.cached_property
  537. def _name_template(self) -> str:
  538. # Index can be of following types
  539. # 1) index is a slice - example 1:4
  540. # 2) index is a constant - example string, integer
  541. assert not isinstance(self.index, Source)
  542. if self.index_is_slice:
  543. return f"{{0}}[{_esc_str(self.unpack_slice(), apply_repr=True)}]"
  544. else:
  545. return f"{{0}}[{_esc_str(self.index, apply_repr=True)}]"
  546. @dataclass_with_cached_hash(frozen=True)
  547. class ConstDictKeySource(ChainedSource):
  548. index: Any
  549. def reconstruct(self, codegen: "PyCodegen") -> None:
  550. codegen.add_push_null(
  551. lambda: codegen.load_import_from(utils.__name__, "dict_keys_getitem")
  552. )
  553. codegen(self.base)
  554. codegen.append_output(codegen.create_load_const(self.index))
  555. codegen.extend_output(create_call_function(2, False))
  556. @functools.cached_property
  557. def _name_template(self) -> str:
  558. # The list creation will be CSE'd by PyExprCSEPass
  559. return f"list(dict.keys({{0}}))[{_esc_str(self.index, apply_repr=True)}]"
  560. def is_dict_key(self) -> bool:
  561. return True
  562. @dataclass_with_cached_hash(frozen=True)
  563. class NonSerializableSetGetItemSource(ChainedSource):
  564. index: int
  565. def __post_init__(self) -> None:
  566. from .variables import ConstantVariable
  567. assert ConstantVariable.is_literal(self.index)
  568. def reconstruct(self, codegen: "PyCodegen") -> None:
  569. codegen.add_push_null(
  570. lambda: codegen.load_import_from(utils.__name__, "set_getitem")
  571. )
  572. codegen(self.base)
  573. codegen.append_output(codegen.create_load_const(self.index))
  574. codegen.extend_output(create_call_function(2, False))
  575. @functools.cached_property
  576. def _name_template(self) -> str:
  577. # set ordering might not be stable
  578. return f"list({{0}})[{_esc_str(self.index, apply_repr=True)}]"
  579. def is_dict_key(self) -> bool:
  580. return False
  581. # Used to access an item from the dictionary
  582. @dataclass_with_cached_hash(frozen=True)
  583. class DictGetItemSource(ChainedSource):
  584. # Key to access in the dictionary. It can be one of the following types
  585. # 1) ConstDictKeySource
  586. # 2) constant - like string, integer
  587. index: Any
  588. def __post_init__(self) -> None:
  589. from .variables import ConstantVariable
  590. assert isinstance(
  591. self.index, ConstDictKeySource
  592. ) or ConstantVariable.is_literal(self.index)
  593. def reconstruct(self, codegen: "PyCodegen") -> None:
  594. # Load dict
  595. codegen(self.base)
  596. # Load key
  597. if isinstance(self.index, Source):
  598. codegen(self.index)
  599. else:
  600. codegen.append_output(codegen.create_load_const(self.index))
  601. codegen.append_output(create_binary_subscr())
  602. @functools.cached_property
  603. def _name_template(self) -> str:
  604. if isinstance(self.index, ConstDictKeySource):
  605. return f"{{0}}[{_esc_str(self.index.name)}]"
  606. else:
  607. return f"{{0}}[{_esc_str(self.index, apply_repr=True)}]"
  608. # Same as DictGetItemSource but used for dict.__getitem__ calls to ensure that
  609. # torch.compile does not run the overridden __getitem__ method
  610. @dataclass_with_cached_hash(frozen=True)
  611. class DictSubclassGetItemSource(ChainedSource):
  612. # Key to access in the dictionary. It can be one of the following types
  613. # 1) ConstDictKeySource
  614. # 2) constant - like string, integer
  615. index: Any
  616. def __post_init__(self) -> None:
  617. from .variables import ConstantVariable
  618. assert isinstance(
  619. self.index, ConstDictKeySource
  620. ) or ConstantVariable.is_literal(self.index)
  621. def reconstruct(self, codegen: "PyCodegen") -> None:
  622. # reconstruct dict.__getitem__(dct, key)
  623. # Load dict.__getitem__
  624. codegen.add_push_null(
  625. lambda: codegen.load_import_from(utils.__name__, "dict_getitem")
  626. )
  627. # Load dict
  628. codegen(self.base)
  629. # Load key
  630. if isinstance(self.index, Source):
  631. codegen(self.index)
  632. else:
  633. codegen.append_output(codegen.create_load_const(self.index))
  634. codegen.extend_output(create_call_function(2, False))
  635. @functools.cached_property
  636. def _name_template(self) -> str:
  637. if isinstance(self.index, ConstDictKeySource):
  638. return f"dict.__getitem__({{0}}, {_esc_str(self.index.name)})"
  639. else:
  640. return f"{{0}}[{_esc_str(self.index, apply_repr=True)}]"
  641. @dataclass_with_cached_hash(frozen=True)
  642. class ListGetItemSource(GetItemSource):
  643. """
  644. Same as GetItemSource with reconstruct and name overridden to be list specific.
  645. """
  646. def reconstruct(self, codegen: "PyCodegen") -> None:
  647. # Reconstruct list.__getitem__(lst, index) to avoid any side effects
  648. # from possibly overridden __getitem__.
  649. # Load list.__getitem__
  650. codegen.add_push_null(
  651. lambda: codegen.load_import_from(utils.__name__, "list_getitem")
  652. )
  653. # Load the list
  654. codegen(self.base)
  655. # Load the index
  656. if self.index_is_slice:
  657. raise RuntimeError(
  658. "List[slice] is a temporary object and should not have a source"
  659. )
  660. else:
  661. codegen.append_output(codegen.create_load_const(self.index))
  662. codegen.extend_output(create_call_function(2, False))
  663. @functools.cached_property
  664. def _name_template(self) -> str:
  665. # Index can be of following types
  666. # 1) index is a slice - example 1:4
  667. # 2) index is a constant - example string, integer
  668. assert not isinstance(self.index, Source)
  669. if self.index_is_slice:
  670. raise RuntimeError(
  671. "List[slice] is a temporary object and should not have a source"
  672. )
  673. else:
  674. return f"list.__getitem__({{0}}, {_esc_str(self.index, apply_repr=True)})"
  675. @dataclass_with_cached_hash(frozen=True)
  676. class TupleIteratorGetItemSource(GetItemSource):
  677. def reconstruct(self, codegen: "PyCodegen") -> None:
  678. codegen.add_push_null(
  679. lambda: codegen.load_import_from(utils.__name__, "tuple_iterator_getitem")
  680. )
  681. codegen(self.base)
  682. codegen.append_output(codegen.create_load_const(self.index))
  683. codegen.extend_output(create_call_function(2, False))
  684. @functools.cached_property
  685. def _name_template(self) -> str:
  686. return (
  687. f"___tuple_iterator_getitem({{0}}, {_esc_str(self.index, apply_repr=True)})"
  688. )
  689. @dataclass_with_cached_hash(frozen=True)
  690. class NamedTupleFieldsSource(ChainedSource):
  691. def reconstruct(self, codegen: "PyCodegen") -> None:
  692. codegen(self.base)
  693. codegen.extend_output(codegen.create_load_attrs("_fields"))
  694. @property
  695. def _name_template(self) -> str:
  696. return "___namedtuple_fields({0})"
  697. @dataclass_with_cached_hash(frozen=True)
  698. class DataclassFieldsSource(ChainedSource):
  699. def reconstruct(self, codegen: "PyCodegen") -> None:
  700. codegen.add_push_null(
  701. lambda: codegen.load_import_from(utils.__name__, "dataclass_fields")
  702. )
  703. codegen(self.base)
  704. codegen.extend_output(create_call_function(1, False))
  705. @property
  706. def _name_template(self) -> str:
  707. return "___dataclass_fields({0})"
  708. @dataclass_with_cached_hash(frozen=True)
  709. class TypeSource(ChainedSource):
  710. def __post_init__(self) -> None:
  711. assert self.base is not None
  712. def reconstruct(self, codegen: "PyCodegen") -> None:
  713. codegen.add_push_null(lambda: codegen.load_import_from("builtins", "type"))
  714. codegen(self.base)
  715. codegen.extend_output(create_call_function(1, False))
  716. @property
  717. def _name_template(self) -> str:
  718. return "type({0})"
  719. @dataclass_with_cached_hash(frozen=True)
  720. class OptimizerSource(ChainedSource):
  721. def reconstruct(self, codegen: "PyCodegen") -> None:
  722. codegen(self.base)
  723. @property
  724. def _name_template(self) -> str:
  725. return "{0}"
  726. @dataclass_with_cached_hash(frozen=True)
  727. class NNModuleSource(ChainedSource):
  728. def reconstruct(self, codegen: "PyCodegen") -> None:
  729. codegen(self.base)
  730. @functools.cached_property
  731. def guard_source(self) -> GuardSource:
  732. return _GUARD_SOURCE_SPECIALIZED_NN_MODULE[self.base.guard_source]
  733. @property
  734. def _name_template(self) -> str:
  735. return "{0}"
  736. @dataclass_with_cached_hash(frozen=True)
  737. class UnspecializedNNModuleSource(NNModuleSource):
  738. @functools.cached_property
  739. def guard_source(self) -> GuardSource:
  740. return _GUARD_SOURCE_UNSPECIALIZED_NN_MODULE[self.base.guard_source]
  741. @dataclass_with_cached_hash(frozen=True)
  742. class UnspecializedBuiltinNNModuleSource(UnspecializedNNModuleSource):
  743. @functools.cached_property
  744. def guard_source(self) -> GuardSource:
  745. return _GUARD_SOURCE_UNSPECIALIZED_BUILTIN_NN_MODULE[self.base.guard_source]
  746. @dataclass_with_cached_hash(frozen=True)
  747. class FSDPNNModuleSource(NNModuleSource):
  748. @functools.cached_property
  749. def guard_source(self) -> GuardSource:
  750. return _GUARD_SOURCE_FSDP_MODULE[self.base.guard_source]
  751. @dataclass_with_cached_hash(frozen=True)
  752. class GlobalStateSource(Source):
  753. @property
  754. def _name_template(self) -> str:
  755. return ""
  756. @property
  757. def guard_source(self) -> GuardSource:
  758. return GuardSource.GLOBAL
  759. @dataclass_with_cached_hash(frozen=True)
  760. class TorchSource(Source):
  761. """Points to the actual `torch` module - used instead of GlobalSource
  762. in case the user has overridden `torch` in their local namespace"""
  763. def __init__(self, *args: Any, **kwargs: Any) -> None:
  764. super().__init__(*args, **kwargs)
  765. from .guards import GuardBuilder, install_guard
  766. install_guard(self.make_guard(GuardBuilder.ID_MATCH))
  767. @property
  768. def _name_template(self) -> str:
  769. return "__import__('torch')"
  770. def reconstruct(self, codegen: "PyCodegen") -> None:
  771. codegen.extend_output(
  772. [
  773. codegen.create_load_const(0), # level
  774. create_build_tuple(0), # fromlist
  775. codegen.create_import_name("torch"),
  776. ]
  777. )
  778. @property
  779. def guard_source(self) -> GuardSource:
  780. return GuardSource.GLOBAL
  781. @dataclass_with_cached_hash(frozen=True)
  782. class CollectionsSource(Source):
  783. """Points to the actual `collections` module - used instead of GlobalSource
  784. in case the user has overridden `collections` in their local namespace"""
  785. def __init__(self, *args: Any, **kwargs: Any) -> None:
  786. super().__init__(*args, **kwargs)
  787. from .guards import GuardBuilder, install_guard
  788. install_guard(self.make_guard(GuardBuilder.ID_MATCH))
  789. @property
  790. def _name_template(self) -> str:
  791. return "__import__('collections')"
  792. def reconstruct(self, codegen: "PyCodegen") -> None:
  793. codegen.extend_output(
  794. [
  795. codegen.create_load_const(0), # level
  796. create_build_tuple(0), # fromlist
  797. codegen.create_import_name("collections"),
  798. ]
  799. )
  800. @property
  801. def guard_source(self) -> GuardSource:
  802. return GuardSource.GLOBAL
  803. @dataclass_with_cached_hash(frozen=True)
  804. class TorchFunctionModeStackSource(Source):
  805. ind: int
  806. @functools.cached_property
  807. def _name_template(self) -> str:
  808. return f"___get_torch_function_mode_stack_at({_esc_str(self._get_index())})"
  809. def _get_index(self) -> int:
  810. from .variables.torch_function import TorchFunctionModeStackVariable
  811. return TorchFunctionModeStackVariable.get_mode_index(self.ind)
  812. def reconstruct(self, codegen: "PyCodegen") -> None:
  813. codegen.add_push_null(
  814. lambda: codegen.load_import_from(
  815. utils.__name__, "get_torch_function_mode_stack_at"
  816. )
  817. )
  818. codegen.extend_output([codegen.create_load_const(self._get_index())])
  819. codegen.extend_output(create_call_function(1, False))
  820. @property
  821. def guard_source(self) -> GuardSource:
  822. return GuardSource.GLOBAL
  823. @dataclass_with_cached_hash(frozen=True)
  824. class ConstantSource(Source):
  825. source_name: str
  826. def reconstruct(self, codegen: "PyCodegen") -> None:
  827. codegen.append_output(codegen.create_load_global(self.source_name, add=False))
  828. @property
  829. def guard_source(self) -> GuardSource:
  830. return GuardSource.CONSTANT
  831. @functools.cached_property
  832. def _name_template(self) -> str:
  833. return self.source_name
  834. def make_guard(self, fn: Any) -> Any:
  835. raise NotImplementedError
  836. @dataclass_with_cached_hash(frozen=True)
  837. class NumpyTensorSource(ChainedSource):
  838. @property
  839. def _name_template(self) -> str:
  840. return "___from_numpy({0})"
  841. def reconstruct(self, codegen: "PyCodegen") -> None:
  842. codegen.add_push_null(lambda: codegen.load_import_from("torch", "as_tensor"))
  843. codegen(self.base)
  844. codegen.extend_output(create_call_function(1, False))
  845. @dataclass_with_cached_hash(frozen=True)
  846. class SubclassAttrListSource(ChainedSource):
  847. @property
  848. def _name_template(self) -> str:
  849. return "{0}.__tensor_flatten__()[0]"
  850. # NB: We don't expect you to actually ever generate guards against this
  851. # source, it is ephemeral
  852. @dataclass_with_cached_hash(frozen=True)
  853. class FloatTensorSource(ChainedSource):
  854. @property
  855. def _name_template(self) -> str:
  856. return "___as_tensor({0})"
  857. @dataclass_with_cached_hash(frozen=True)
  858. class CallMethodItemSource(ChainedSource):
  859. @property
  860. def _name_template(self) -> str:
  861. return "{0}.item()"
  862. # This is a synthetic source that is associated with the singleton
  863. # shape env guard we always register for all frames. We get the actual
  864. # guard contents from the ambient ShapeEnv
  865. @dataclass_with_cached_hash(frozen=True)
  866. class ShapeEnvSource(Source):
  867. @property
  868. def _name_template(self) -> str:
  869. return ""
  870. @property
  871. def guard_source(self) -> GuardSource:
  872. return GuardSource.SHAPE_ENV
  873. @dataclass_with_cached_hash(frozen=True)
  874. class CurrentStreamSource(Source):
  875. device: device_type
  876. @functools.cached_property
  877. def _name_template(self) -> str:
  878. return f"___get_current_stream(torch.device('{_esc_str(self.device.type)}', {_esc_str(self.device.index)}))"
  879. def reconstruct(self, codegen: "PyCodegen") -> None:
  880. num_args = 1
  881. codegen.add_push_null(
  882. lambda: codegen.load_import_from(utils.__name__, "get_current_stream")
  883. )
  884. codegen.add_push_null(lambda: codegen.load_import_from("torch", "device"))
  885. codegen.extend_output([codegen.create_load_const(self.device.type)])
  886. if self.device.index is not None:
  887. num_args += 1
  888. codegen.extend_output([codegen.create_load_const(self.device.index)])
  889. codegen.extend_output(create_call_function(num_args, False))
  890. codegen.extend_output(create_call_function(1, False))
  891. @property
  892. def guard_source(self) -> GuardSource:
  893. return GuardSource.GLOBAL
  894. @dataclass_with_cached_hash(frozen=True)
  895. class BackwardStateSource(Source):
  896. @property
  897. def _name_template(self) -> str:
  898. return ""
  899. @property
  900. def guard_source(self) -> GuardSource:
  901. return GuardSource.BACKWARD_STATE
  902. def get_local_source_name(
  903. source: Source, *, only_allow_input: bool = False
  904. ) -> Optional[str]:
  905. if isinstance(source, ChainedSource):
  906. return get_local_source_name(source.base, only_allow_input=only_allow_input)
  907. if not isinstance(source, LocalSource):
  908. return None
  909. if only_allow_input and not source.is_input:
  910. return None
  911. return source.local_name
  912. def is_from_local_source(source: Source, *, only_allow_input: bool = False) -> bool:
  913. return get_local_source_name(source, only_allow_input=only_allow_input) is not None
  914. def is_from_global_source(source: Source) -> bool:
  915. return get_global_source_name(source) is not None
  916. def get_global_source_name(source: Source) -> Optional[str]:
  917. if isinstance(source, ChainedSource):
  918. return get_global_source_name(source.base)
  919. if not isinstance(source, GlobalSource):
  920. return None
  921. return source.global_name
  922. def is_from_nonlocal_source(source: Source) -> bool:
  923. if isinstance(source, ChainedSource):
  924. return is_from_nonlocal_source(source.base)
  925. return (
  926. isinstance(source, LocalSource)
  927. and source.is_derefed_cell_contents
  928. and not source.is_input
  929. )
  930. def is_from_closure_source(source: Source) -> bool:
  931. if isinstance(source, ClosureSource):
  932. return True
  933. if isinstance(source, ChainedSource):
  934. return is_from_closure_source(source.base)
  935. return False
  936. def is_from_source(source: Source, target: Source) -> bool:
  937. if isinstance(source, ChainedSource):
  938. return is_from_source(source.base, target)
  939. return source == target
  940. @functools.lru_cache
  941. def is_from_unspecialized_nn_module_source(source: Source) -> bool:
  942. if isinstance(source, UnspecializedNNModuleSource):
  943. return True
  944. if isinstance(source, ChainedSource):
  945. return is_from_unspecialized_nn_module_source(source.base)
  946. return False
  947. @functools.lru_cache
  948. def is_from_unspecialized_builtin_nn_module_source(source: Source) -> bool:
  949. if isinstance(source, UnspecializedBuiltinNNModuleSource):
  950. return True
  951. if isinstance(source, ChainedSource):
  952. return is_from_unspecialized_builtin_nn_module_source(source.base)
  953. return False
  954. @functools.lru_cache
  955. def is_from_unspecialized_param_buffer_source(source: Source) -> bool:
  956. if isinstance(source, UnspecializedParamBufferSource):
  957. return True
  958. if isinstance(source, ChainedSource):
  959. return is_from_unspecialized_param_buffer_source(source.base)
  960. return False
  961. @functools.lru_cache
  962. def is_from_flatten_script_object_source(source: Source) -> bool:
  963. if isinstance(source, FlattenScriptObjectSource):
  964. return True
  965. elif isinstance(source, ChainedSource):
  966. return is_from_flatten_script_object_source(source.base)
  967. return False
  968. @functools.lru_cache
  969. def is_from_optimizer_source(source: Source) -> bool:
  970. if isinstance(source, OptimizerSource):
  971. return True
  972. if isinstance(source, ChainedSource):
  973. return is_from_optimizer_source(source.base)
  974. return False
  975. # TODO: can probably write a generic "test this on everything in the chain"
  976. # helper
  977. @functools.lru_cache
  978. def is_from_defaults(source: Source) -> bool:
  979. if isinstance(source, DefaultsSource):
  980. return True
  981. # Accessed with func.__kwdefaults__["foo"]
  982. if (
  983. isinstance(source, DictGetItemSource)
  984. and isinstance(source.base, AttrSource)
  985. and source.base.member == "__kwdefaults__"
  986. ):
  987. return True
  988. # Accessed with func.__defaults__[0]
  989. if (
  990. isinstance(source, GetItemSource)
  991. and isinstance(source.base, AttrSource)
  992. and source.base.member == "__defaults__"
  993. ):
  994. return True
  995. if isinstance(source, ChainedSource):
  996. return is_from_defaults(source.base)
  997. return False
  998. @functools.lru_cache
  999. def is_from_skip_guard_source(source: Source) -> bool:
  1000. if isinstance(source, SkipGuardSource):
  1001. return True
  1002. if isinstance(source, ChainedSource):
  1003. return is_from_skip_guard_source(source.base)
  1004. return False