package.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  1. """
  2. This module provides the infrastructure for creating and managing compile package
  3. for torch.compile. We mainly have two abstractions here:
  4. - CompilePackage: Overarching data structure for store and lookup a list of compiled codes.
  5. - CodeCacheEntry: Data structure for a single code being compiled by torch.compile.
  6. The caching behavior is always under user control explicitly so that a stronger guarantee can
  7. be provided about cache hit for a specific compiled model. Users can load the compile package
  8. from a different process or host.
  9. """
  10. import abc
  11. import ast
  12. import contextlib
  13. import dataclasses
  14. import functools
  15. import hashlib
  16. import importlib
  17. import inspect
  18. import json
  19. import logging
  20. import os
  21. import pickle
  22. import platform
  23. import shutil
  24. import sys
  25. import types
  26. from collections.abc import Callable, Generator, Iterator
  27. from contextlib import nullcontext
  28. from typing import Any, NewType, Optional, TYPE_CHECKING, Union
  29. from typing_extensions import Never
  30. import torch
  31. from torch._dynamo.exc import PackageError
  32. from torch._dynamo.graph_utils import _graph_device_type
  33. from torch.utils.weak import WeakIdKeyDictionary
  34. from .bytecode_transformation import get_code_keys
  35. from .utils import counters, dynamo_timed, increment_frame
  36. logger = logging.getLogger(__name__)
  37. if TYPE_CHECKING:
  38. from .guards import GuardManagerWrapper, GuardsState
  39. _CODE_CACHE = WeakIdKeyDictionary()
  40. def _code_cache(fn: Callable[..., Any]) -> Callable[..., Any]:
  41. def _(
  42. cls: type[Any], code: Union["SerializedCode", types.CodeType]
  43. ) -> Union["SerializedCode", types.CodeType]:
  44. if code in _CODE_CACHE:
  45. return _CODE_CACHE[code]
  46. res = fn(cls, code)
  47. _CODE_CACHE[code] = res
  48. return res
  49. return _
  50. @dataclasses.dataclass(frozen=True)
  51. class SerializedCode:
  52. co_argcount: int
  53. co_posonlyargcount: int
  54. co_kwonlyargcount: int
  55. co_nlocals: int
  56. co_stacksize: int
  57. co_flags: int
  58. co_code: bytes
  59. co_consts: tuple[Any, ...]
  60. co_names: tuple[str, ...]
  61. co_varnames: tuple[str, ...]
  62. co_filename: str
  63. co_name: str
  64. co_firstlineno: int
  65. co_cellvars: tuple[str, ...]
  66. co_freevars: tuple[str, ...]
  67. co_linetable: Optional[bytes] = None
  68. co_qualname: Optional[str] = None
  69. co_exceptiontable: Optional[bytes] = None
  70. co_lnotab: Optional[str] = None
  71. @classmethod
  72. @_code_cache
  73. def from_code_object(cls, code: types.CodeType) -> "SerializedCode":
  74. kwargs = {key: getattr(code, key) for key in get_code_keys()}
  75. kwargs["co_consts"] = tuple(
  76. cls.from_code_object(c) if isinstance(c, types.CodeType) else c
  77. for c in kwargs["co_consts"]
  78. )
  79. return cls(**kwargs)
  80. @classmethod
  81. @_code_cache
  82. def to_code_object(cls, serialized_code: "SerializedCode") -> types.CodeType:
  83. kwargs = {key: getattr(serialized_code, key) for key in get_code_keys()}
  84. kwargs["co_consts"] = tuple(
  85. cls.to_code_object(c) if isinstance(c, SerializedCode) else c
  86. for c in kwargs["co_consts"]
  87. )
  88. return types.CodeType(
  89. *kwargs.values(),
  90. )
  91. @dataclasses.dataclass
  92. class _GuardedCodeCacheEntry:
  93. """
  94. Contains the serializable information associated with a single compilation in dynamo.
  95. To restore an execution of compiled code, we will need to serialize the following data:
  96. - Dynamo bytecode for mapping Python inputs/outputs.
  97. - Dynamo guards.
  98. """
  99. guards_state: bytes
  100. dynamo_code: SerializedCode
  101. def load_guards_state(guards_state: bytes) -> Any:
  102. try:
  103. import torch.distributed.fsdp._fully_shard._fully_shard as _fully_shard
  104. ctx = _fully_shard.disable_fsdp_module_new_init()
  105. except ImportError:
  106. ctx = nullcontext() # type: ignore[assignment]
  107. with ctx:
  108. return pickle.loads(guards_state)
  109. def load_guard_manager(
  110. guards_state: "GuardsState",
  111. target_code: types.CodeType,
  112. runtime_global_scope: Any,
  113. ) -> "GuardManagerWrapper":
  114. from .output_graph import OutputGraphCommon
  115. return torch._dynamo.guards.CheckFunctionManager(
  116. target_code,
  117. OutputGraphCommon(guards_state.output_graph),
  118. shape_code_parts=guards_state.shape_code_parts,
  119. runtime_global_scope=runtime_global_scope,
  120. ).guard_manager
  121. _BackendId = NewType("_BackendId", str) # __compiled_fn
  122. _FunctionId = NewType("_FunctionId", str) # __resume_at
  123. @dataclasses.dataclass(frozen=True)
  124. class InlinedSource:
  125. module: str
  126. firstlineno: int
  127. lastlineno: int
  128. checksum: str
  129. content: str
  130. @functools.cache
  131. def _get_module_content(module: types.ModuleType) -> str:
  132. return inspect.getsource(module)
  133. @dataclasses.dataclass
  134. class SourceInfo:
  135. inlined_sources: set[InlinedSource]
  136. def add_code(self, code: types.CodeType) -> None:
  137. module = inspect.getmodule(code)
  138. if module is None:
  139. return
  140. sourcelines, firstlineno = inspect.getsourcelines(code)
  141. lastlineno = firstlineno + len(sourcelines)
  142. source = "".join(sourcelines)
  143. assert source == "".join(_get_sourcelines(module, firstlineno, lastlineno))
  144. self.inlined_sources.add(
  145. InlinedSource(
  146. module=module.__name__,
  147. firstlineno=firstlineno,
  148. lastlineno=lastlineno,
  149. checksum=_hash_source(source),
  150. content=_get_module_content(module),
  151. )
  152. )
  153. @dataclasses.dataclass
  154. class _DynamoCodeCacheEntry:
  155. """
  156. Contains the serializable information associated with a single code object
  157. in dynamo. To restore an execution of compiled code, we will need the following
  158. ingredients:
  159. 1. The "original" code object, which serves as the entry point for eager
  160. execution, i.e. the code only executed when there's no cache entry hit.
  161. 2. The python module name this code object belongs to, for identifying the
  162. enclosing global scope to inject compiled and resume functions.
  163. 3. A list of function names that pointing to this code object. There could be
  164. multiple function objects pointing to the same code such as recursive functions.
  165. 4. A list of guarded code that eval frame dispatches to.
  166. 5. A list of imported module objects unioned from all compiled branches.
  167. 6. A list of "backends" (compiled fx graph) unioned from all compield branches.
  168. 7. A string path used to access the original code object users defined.
  169. A code object can be accessed by "{python_module}.{function_name}.{code_source}" .
  170. 8. A boolean flag indicating whether the function is installed to global scope.
  171. 9. A boolean flag indicating whether the function has a compile id.
  172. 10. Whether or not this code entry was bypassed
  173. """
  174. python_code: SerializedCode
  175. python_module: str
  176. function_names: list[_FunctionId]
  177. guarded_codes: list[_GuardedCodeCacheEntry]
  178. import_sources: dict[str, str]
  179. backend_ids: list[_BackendId]
  180. code_source: Optional[str]
  181. install_to_global: bool
  182. has_compile_id: bool = False
  183. bypassed: bool = False
  184. def _lookup_code(entry: _DynamoCodeCacheEntry) -> types.CodeType:
  185. assert len(entry.function_names) == 1
  186. fn: Any = sys.modules[entry.python_module]
  187. parts = entry.function_names[0].split(".")
  188. for part in parts:
  189. fn = getattr(fn, part)
  190. if entry.code_source:
  191. parts = entry.code_source.split(".")
  192. for part in parts:
  193. if part.endswith("]"):
  194. index_begin = part.rfind("[")
  195. assert isinstance(index_begin, int) and index_begin >= 0
  196. attr = getattr(fn, part[:index_begin], None)
  197. if attr is None:
  198. raise PackageError(f"Cannot find source for code entry {entry}")
  199. fn = attr[ast.literal_eval(part[index_begin + 1 : -1])]
  200. else:
  201. fn = getattr(fn, part)
  202. else:
  203. raise PackageError(f"Cannot find source for code entry {entry}")
  204. assert isinstance(fn, types.CodeType)
  205. return fn
  206. def _raise_resolution_error(code: types.CodeType, scope: Any) -> Never:
  207. raise PackageError(
  208. f"Cannot resolve a fully qualified name for {code}. Lookup scope: {scope}"
  209. )
  210. def _get_code_source(code: types.CodeType) -> tuple[str, str]:
  211. """
  212. Given a code object, return a fully qualified name which will be used as
  213. a serialized handle to access the code object from the new process.
  214. This is normally a straightforward process, but there are some corner cases:
  215. 1. When a function is defined with decorator, then this function will be captured
  216. inside a closure with the wrapper object.
  217. 2. When a function is defined as a nested function, then the code object will be
  218. stored on the co_consts field of the parent code object by Python compiler.
  219. This function handles all of the corner cases above.
  220. """
  221. module = inspect.getmodule(code)
  222. if module is None:
  223. raise PackageError(f"Cannot find module for code {code}")
  224. toplevel: Any = module
  225. if sys.version_info >= (3, 11):
  226. parts = code.co_qualname.split(".")
  227. for part in parts:
  228. if not hasattr(toplevel, part):
  229. _raise_resolution_error(code, toplevel)
  230. toplevel = getattr(toplevel, part)
  231. if inspect.isfunction(toplevel):
  232. break
  233. seen = set()
  234. def _find_code_source(obj: Any) -> Optional[str]:
  235. nonlocal toplevel
  236. nonlocal seen
  237. if obj in seen:
  238. return None
  239. seen.add(obj)
  240. if inspect.iscode(obj):
  241. if obj is code:
  242. return ""
  243. for i, const in enumerate(obj.co_consts):
  244. if (res := _find_code_source(const)) is not None:
  245. return f".co_consts[{i}]{res}"
  246. if inspect.isfunction(obj):
  247. if (res := _find_code_source(obj.__code__)) is not None:
  248. toplevel = obj
  249. return f".__code__{res}"
  250. if obj.__closure__ is not None:
  251. for i, cell in enumerate(obj.__closure__):
  252. try:
  253. cell_contents = cell.cell_contents
  254. except ValueError:
  255. continue
  256. if not (
  257. inspect.isfunction(cell_contents)
  258. or inspect.iscode(cell_contents)
  259. ):
  260. continue
  261. if (res := _find_code_source(cell_contents)) is not None:
  262. toplevel = obj
  263. return f".__closure__[{i}].cell_contents{res}"
  264. if sys.version_info < (3, 11):
  265. if inspect.ismodule(obj):
  266. for value in obj.__dict__.values():
  267. if not (inspect.isfunction(value) or inspect.isclass(value)):
  268. continue
  269. if (res := _find_code_source(value)) is not None:
  270. return res
  271. if inspect.isclass(obj):
  272. for name, value in obj.__dict__.items():
  273. value = getattr(obj, name)
  274. if not (inspect.isfunction(value) or inspect.isclass(value)):
  275. continue
  276. if (res := _find_code_source(value)) is not None:
  277. if value.__name__ != name:
  278. _raise_resolution_error(code, toplevel)
  279. return res
  280. return None
  281. code_source = _find_code_source(toplevel)
  282. if code_source is None:
  283. _raise_resolution_error(code, toplevel)
  284. # pyrefly: ignore [missing-attribute]
  285. return toplevel.__qualname__, code_source.strip(".")
  286. @dataclasses.dataclass(frozen=True)
  287. class SystemInfo:
  288. """
  289. System information including Python, PyTorch, and GPU details.
  290. This information is used to ensure compiled artifacts can only be loaded
  291. with compatible system configurations.
  292. """
  293. python_version: str
  294. torch_version: str
  295. toolkit_version: Optional[str]
  296. triton_version: Optional[tuple[int, int]]
  297. gpu_name: Optional[str]
  298. CHECK_GPUS = ("cuda", "xpu")
  299. @classmethod
  300. def current(cls) -> "SystemInfo":
  301. """Create a SystemInfo instance with current system information."""
  302. # Get GPU name if CUDA or XPU is available
  303. gpu_name = None
  304. from torch.utils._triton import get_triton_version
  305. gpu_name, toolkit_version = None, None
  306. for device_type in cls.CHECK_GPUS:
  307. if getattr(torch, device_type).is_available():
  308. try:
  309. gpu_name = getattr(torch, device_type).get_device_name()
  310. toolkit_version = getattr(torch.version, device_type)
  311. break
  312. except Exception:
  313. pass
  314. return cls(
  315. python_version=platform.python_version(),
  316. torch_version=torch.__version__,
  317. toolkit_version=toolkit_version,
  318. triton_version=get_triton_version((0, 0)),
  319. gpu_name=gpu_name,
  320. )
  321. def check_compatibility(
  322. self, other: "SystemInfo", device_type: str = "cpu"
  323. ) -> None:
  324. """
  325. Check if this SystemInfo is compatible with another SystemInfo.
  326. Raises RuntimeError if incompatible.
  327. """
  328. if self.python_version != other.python_version:
  329. raise RuntimeError(
  330. f"Compile package was created with a different Python version: {self.python_version}"
  331. )
  332. if self.torch_version != other.torch_version:
  333. raise RuntimeError(
  334. f"Compile package was created with a different PyTorch version: {self.torch_version}"
  335. )
  336. if device_type in self.CHECK_GPUS:
  337. if not getattr(torch, device_type).is_available():
  338. raise RuntimeError(f"{device_type} is not available")
  339. if self.toolkit_version != other.toolkit_version:
  340. raise RuntimeError(
  341. f"Compile package was created with a different toolkit version: {self.toolkit_version}"
  342. )
  343. if (
  344. other.triton_version != (0, 0)
  345. and self.triton_version != other.triton_version
  346. ):
  347. raise RuntimeError(
  348. f"Compile package was created with a different Triton version: {self.triton_version}"
  349. )
  350. # Check GPU name if CUDA/XPU was used
  351. if other.gpu_name is not None and self.gpu_name != other.gpu_name:
  352. raise RuntimeError(
  353. f"Compile package was created with different GPU: "
  354. f"cached={self.gpu_name}, current={other.gpu_name}"
  355. )
  356. @dataclasses.dataclass
  357. class _DynamoCacheEntry:
  358. codes: list[_DynamoCodeCacheEntry]
  359. source_info: SourceInfo
  360. device_type: str
  361. system_info: SystemInfo = dataclasses.field(default_factory=SystemInfo.current)
  362. fn_name: Optional[str] = None
  363. fn_first_lineno: Optional[str] = None
  364. @property
  365. def backend_ids(self) -> set[_BackendId]:
  366. return {backend_id for code in self.codes for backend_id in code.backend_ids}
  367. def check_versions(self) -> None:
  368. """Check if the current system is compatible with the system used to create this cache entry."""
  369. current_system_info = SystemInfo.current()
  370. self.system_info.check_compatibility(current_system_info, self.device_type)
  371. def debug_info(self) -> dict[str, Any]:
  372. assert len(self.codes) > 0
  373. return {
  374. "num_codes": str(len(self.codes)),
  375. "fn_name": self.fn_name,
  376. "fn_first_lineno": self.fn_first_lineno,
  377. "device_type": self.device_type,
  378. "backend_ids": list(self.backend_ids),
  379. }
  380. from torch.compiler._cache import (
  381. CacheArtifact,
  382. CacheArtifactFactory,
  383. CacheArtifactManager,
  384. )
  385. @CacheArtifactFactory.register
  386. class PrecompileCacheArtifact(CacheArtifact):
  387. def populate_cache(self) -> None:
  388. DynamoCache._write_to_local_cache(self.content, self.key)
  389. @staticmethod
  390. def type() -> str:
  391. return "precompile"
  392. @dataclasses.dataclass
  393. class PrecompileCacheEntry:
  394. """
  395. A full cache entry for caching precompile, for a toplevel torch.compile.
  396. Consists of a _DynamoCacheEntry, which contains all the dynamo related contents,
  397. and a set of backends content. In general, the backend content here will always
  398. be of type precompile_context.BackendCacheArtifact
  399. """
  400. dynamo: _DynamoCacheEntry
  401. backends: dict[_BackendId, Any]
  402. @staticmethod
  403. def from_cache_entry(
  404. cache_entry: _DynamoCacheEntry, backends: dict[_BackendId, Any]
  405. ) -> Optional["PrecompileCacheEntry"]:
  406. backend_content: dict[_BackendId, Any] = {}
  407. for code in cache_entry.codes:
  408. for backend_id in code.backend_ids:
  409. if backend_id not in backends:
  410. logger.warning("Backend not found")
  411. debug_str = json.dumps(
  412. {
  413. "entry": cache_entry.debug_info(),
  414. "missing_backend": backend_id,
  415. }
  416. )
  417. torch._logging.trace_structured(
  418. "artifact",
  419. metadata_fn=lambda: {
  420. "name": "dynamo_cache_bypass",
  421. "encoding": "json",
  422. },
  423. payload_fn=lambda: debug_str,
  424. expect_trace_id=False,
  425. )
  426. code.bypassed = True
  427. break
  428. else:
  429. backend_content[backend_id] = backends[backend_id]
  430. return PrecompileCacheEntry(dynamo=cache_entry, backends=backend_content)
  431. def _hash_source(source: str) -> str:
  432. sha256_hash = hashlib.sha256()
  433. sha256_hash.update(source.encode())
  434. return sha256_hash.hexdigest()
  435. def _get_sourcelines(
  436. m: types.ModuleType, firstlineno: int, lastlineno: int
  437. ) -> list[str]:
  438. return inspect.getsourcelines(m)[0][firstlineno - 1 : lastlineno - 1]
  439. def _hash_sourcelines(m: types.ModuleType, firstlineno: int, lastlineno: int) -> str:
  440. return _hash_source("".join(_get_sourcelines(m, firstlineno, lastlineno)))
  441. def _compile_frame_context(
  442. code: types.CodeType,
  443. ) -> contextlib.AbstractContextManager[None]:
  444. from torch._dynamo.convert_frame import get_compile_id, log_dynamo_start
  445. from torch._guards import compile_context, CompileContext
  446. # Each code represents a new compile frame
  447. # recompiles on the same frame are all saved
  448. # under the same cache entry, so we don't have recompile ids
  449. # i.e. If cold start had 0/0, 0/1, 1/0, 1/1, these would be
  450. # collapsed into 0/0, 1/0 on warm.
  451. @contextlib.contextmanager
  452. def _ctx() -> Iterator[None]:
  453. increment_frame()
  454. compile_id = get_compile_id(frame_state={})
  455. with (
  456. compile_context(CompileContext(compile_id)),
  457. dynamo_timed(
  458. "_compile.compile_inner",
  459. phase_name="entire_frame_compile",
  460. dynamo_compile_column_us="dynamo_cumulative_compile_time_us",
  461. # TODO: save all relevant compilation metrics
  462. metadata={
  463. "frame_key": str(torch._dynamo.utils.curr_frame),
  464. "co_name": code.co_name,
  465. "co_filename": code.co_filename,
  466. "co_firstlineno": code.co_firstlineno,
  467. },
  468. ),
  469. ):
  470. log_dynamo_start(code)
  471. yield
  472. return _ctx()
  473. class CompilePackage:
  474. """
  475. CompilePackage is considered a low level component and should not be directly exposed to
  476. end users. It has the following interface:
  477. 1. `CompilePackage.__init__()` which optionally takes previously serialized dynamo states.
  478. a. when `dynamo` argument is None, it will construct a brand new CompilePackage object.
  479. b. when `dynamo` argument is not None, it will load a pre-compiled dynamo state.
  480. 2. `package.save()` which dumps the dynamo and backend states to a DynamoCacheEntry object.
  481. 3. `package.install(backends) which will handle all the side-effectful global scope
  482. updates with compiled functions and resume functions.
  483. """
  484. def __init__(
  485. self,
  486. fn: Optional[Callable[..., Any]],
  487. dynamo: Optional[_DynamoCacheEntry] = None,
  488. ignore_inlined_sources: bool = False,
  489. ) -> None:
  490. self._innermost_fn = None
  491. self._codes: dict[types.CodeType, _DynamoCodeCacheEntry] = {}
  492. self._current_entry: Optional[_DynamoCodeCacheEntry] = None
  493. self._installed_globals: dict[types.ModuleType, list[str]] = {}
  494. # device_type that model compiled with.
  495. self._device_type = "cpu"
  496. # For debugging/testing purpose only.
  497. self._cached_backends: dict[_BackendId, Any] = {}
  498. self._source_info: SourceInfo = SourceInfo(inlined_sources=set())
  499. self._resume_codes: set[types.CodeType] = set()
  500. self._initialized = False
  501. if fn is not None:
  502. self.initialize(fn, dynamo, ignore_inlined_sources)
  503. self.uninstall()
  504. self.validate()
  505. def is_initialized(self) -> bool:
  506. return self._initialized
  507. def initialize(
  508. self,
  509. fn: Any,
  510. dynamo: Optional[_DynamoCacheEntry] = None,
  511. ignore_inlined_sources: bool = False,
  512. ) -> None:
  513. from .eval_frame import innermost_fn
  514. assert not self._initialized
  515. self._source_info = SourceInfo(inlined_sources=set())
  516. self._innermost_fn = innermost_fn(fn) # type: ignore[assignment]
  517. assert self._innermost_fn is not None
  518. if dynamo is not None:
  519. assert isinstance(dynamo, _DynamoCacheEntry)
  520. dynamo.check_versions()
  521. if not ignore_inlined_sources:
  522. for code in dynamo.source_info.inlined_sources:
  523. m = importlib.import_module(code.module)
  524. checksum = _hash_sourcelines(m, code.firstlineno, code.lastlineno)
  525. if checksum != code.checksum:
  526. raise RuntimeError(
  527. f"Source code changes detected for {code.module} (line {code.firstlineno} - line {code.lastlineno})"
  528. )
  529. # pyrefly: ignore [bad-assignment]
  530. self._source_info = dynamo.source_info
  531. main, *codes = dynamo.codes
  532. # pyrefly: ignore [bad-assignment]
  533. self._codes = {self._innermost_fn.__code__: main}
  534. for code in codes:
  535. self._codes[SerializedCode.to_code_object(code.python_code)] = code
  536. else:
  537. self._add_function(
  538. self._innermost_fn.__code__, self._innermost_fn.__module__
  539. )
  540. # pyrefly: ignore [bad-assignment]
  541. self._initialized = True
  542. def _add_function(
  543. self,
  544. python_code: types.CodeType,
  545. python_module: str,
  546. function_name: Optional[_FunctionId] = None,
  547. code_source: Optional[str] = None,
  548. install_to_global: bool = False,
  549. ) -> None:
  550. if python_code not in self._codes:
  551. code = _DynamoCodeCacheEntry(
  552. python_code=SerializedCode.from_code_object(python_code),
  553. python_module=python_module,
  554. function_names=[],
  555. guarded_codes=[],
  556. import_sources={},
  557. backend_ids=[],
  558. code_source=code_source,
  559. install_to_global=install_to_global,
  560. )
  561. self._codes[python_code] = code
  562. else:
  563. code = self._codes[python_code]
  564. assert code.python_module == python_module
  565. assert code.install_to_global == install_to_global
  566. assert code.code_source == code_source
  567. if function_name is not None:
  568. code.function_names.append(function_name)
  569. @property
  570. def cached_backends(self) -> dict[_BackendId, Any]:
  571. return self._cached_backends
  572. @functools.cached_property
  573. def source_id(self) -> str:
  574. assert self._innermost_fn is not None
  575. return CompilePackage.source_id_from_fn(self._innermost_fn)
  576. def _add_user_function(self, code: types.CodeType) -> None:
  577. function_name, code_source = _get_code_source(code)
  578. module = inspect.getmodule(code)
  579. if module is None:
  580. raise PackageError(f"Cannot find module for code {code}")
  581. self._add_function(
  582. code,
  583. module.__name__,
  584. function_name=_FunctionId(function_name),
  585. code_source=code_source,
  586. )
  587. @contextlib.contextmanager
  588. def code_context(self, code: types.CodeType) -> Generator[None, None, None]:
  589. assert self._current_entry is None
  590. # Sometimes user code cannot be inlined in dynamo resulting in extra user code
  591. # being compiled. We should record these as when they are actually invoked.
  592. if code not in self._codes:
  593. self._add_user_function(code)
  594. entry = self._codes[code]
  595. self._current_entry = entry
  596. try:
  597. yield
  598. finally:
  599. entry.has_compile_id = True
  600. self._current_entry = None
  601. def add_guarded_code(
  602. self,
  603. guards_state: bytes,
  604. dynamo_code: types.CodeType,
  605. ) -> None:
  606. assert self._current_entry is not None
  607. if self._current_entry.bypassed:
  608. return
  609. guarded_code_entry = _GuardedCodeCacheEntry(
  610. guards_state=guards_state,
  611. dynamo_code=SerializedCode.from_code_object(dynamo_code),
  612. )
  613. self._current_entry.guarded_codes.append(guarded_code_entry)
  614. def add_inlined_source(self, sources: list[types.CodeType]) -> None:
  615. assert self._current_entry is not None
  616. if self._current_entry.bypassed:
  617. return
  618. for code in sources:
  619. if code in self._resume_codes:
  620. continue
  621. self._source_info.add_code(code)
  622. def update_device_type(self, graph: Optional[torch.fx.Graph]) -> None:
  623. self._device_type = _graph_device_type(graph)
  624. def bypass_current_entry(self) -> None:
  625. assert self._current_entry is not None
  626. self._current_entry.bypassed = True
  627. def add_resume_function(
  628. self,
  629. python_code: types.CodeType,
  630. python_module: str,
  631. function_name: Optional[str],
  632. ) -> None:
  633. self._add_function(
  634. python_code,
  635. python_module,
  636. function_name=_FunctionId(function_name) if function_name else None,
  637. install_to_global=True,
  638. )
  639. self._resume_codes.add(python_code)
  640. def add_import_source(self, alias: str, module_name: str) -> None:
  641. assert self._current_entry is not None
  642. self._current_entry.import_sources[alias] = module_name
  643. def add_backend_id(self, backend_id: str, backend: Optional[Any] = None) -> None:
  644. assert self._current_entry is not None
  645. assert backend_id.startswith("__compiled_fn_") # sanity check
  646. backend_id = _BackendId(backend_id)
  647. self._current_entry.backend_ids.append(backend_id)
  648. if backend is not None:
  649. self._cached_backends[backend_id] = backend
  650. def validate(self) -> None:
  651. assert self._current_entry is None
  652. assert self._innermost_fn is not None
  653. assert self._initialized
  654. assert next(iter(self._codes)) is self._innermost_fn.__code__
  655. def _install_global(self, module: types.ModuleType, name: str, value: Any) -> None:
  656. module.__dict__[name] = value
  657. self._installed_globals.setdefault(module, []).append(name)
  658. def uninstall(self) -> None:
  659. from torch._C._dynamo.eval_frame import _reset_precompile_entries
  660. assert self._innermost_fn is not None
  661. for module, names in self._installed_globals.items():
  662. for name in names:
  663. module.__dict__.pop(name)
  664. # pyrefly: ignore [bad-assignment]
  665. self._installed_globals = {}
  666. _reset_precompile_entries(self._innermost_fn.__code__)
  667. def install(self, backends: dict[_BackendId, Any]) -> None:
  668. """
  669. Sync the package states to the compiled function. This includes the following actions:
  670. 1. Clean up the previously installed states.
  671. 2. Install the compiled functions to global scopes.
  672. 3. Install the precompiled cache entries to ExtraStates on the code object.
  673. """
  674. from torch._C._dynamo.eval_frame import _load_precompile_entry
  675. from .output_graph import get_builtins_dict
  676. self.uninstall()
  677. for code, entry in self._codes.items():
  678. context = (
  679. _compile_frame_context(code)
  680. if entry.has_compile_id
  681. else contextlib.nullcontext()
  682. )
  683. with context:
  684. module = sys.modules[entry.python_module]
  685. for alias, module_name in entry.import_sources.items():
  686. self._install_global(
  687. module, alias, importlib.import_module(module_name)
  688. )
  689. target_code = code
  690. if entry.install_to_global:
  691. for function_name in entry.function_names:
  692. fn = types.FunctionType(code, module.__dict__, function_name)
  693. self._install_global(module, function_name, fn)
  694. if entry.code_source:
  695. target_code = _lookup_code(entry)
  696. if entry.bypassed:
  697. # If the entry is bypassed, do not install backends
  698. # or guarded codes.
  699. continue
  700. for backend_id in entry.backend_ids:
  701. if backend_id not in backends:
  702. raise RuntimeError(
  703. f"Backend {backend_id} is not found in the given backends"
  704. )
  705. with dynamo_timed(
  706. "after_deserialization", phase_name="backend_compile"
  707. ):
  708. backend = backends[backend_id].after_deserialization()
  709. self._install_global(
  710. module,
  711. backend_id,
  712. torch._dynamo.disable(backend),
  713. )
  714. if len(entry.guarded_codes) == 0:
  715. # Dynamo generates empty graph for trivial functions, should just skip them
  716. # in these cases.
  717. torch._dynamo.eval_frame.skip_code(target_code)
  718. for guarded_code in entry.guarded_codes:
  719. with dynamo_timed("precompile_load_guards"):
  720. guards_state = load_guards_state(guarded_code.guards_state)
  721. runtime_global_scope = sys.modules[entry.python_module].__dict__
  722. # The installed builtins dict might be absent from the runtime
  723. # while loading guards. Populate it if it's missing.
  724. if (
  725. builtin_dict_name
  726. := guards_state.output_graph.name_of_builtins_dict_key_in_fglobals
  727. ):
  728. builtins_dict = get_builtins_dict(runtime_global_scope)
  729. if builtin_dict_name in runtime_global_scope:
  730. assert (
  731. runtime_global_scope[builtin_dict_name] is builtins_dict
  732. )
  733. else:
  734. runtime_global_scope[builtin_dict_name] = builtins_dict
  735. assert isinstance(guards_state, torch._dynamo.guards.GuardsState)
  736. with dynamo_timed("precompile_build_guards"):
  737. guard_manager = load_guard_manager(
  738. guards_state, target_code, runtime_global_scope
  739. )
  740. _load_precompile_entry(
  741. target_code,
  742. guard_manager,
  743. SerializedCode.to_code_object(guarded_code.dynamo_code),
  744. )
  745. def cache_entry(self) -> _DynamoCacheEntry:
  746. self.validate()
  747. assert self._innermost_fn is not None
  748. return _DynamoCacheEntry(
  749. codes=list(self._codes.values()),
  750. source_info=self._source_info,
  751. device_type=self._device_type,
  752. fn_name=self._innermost_fn.__qualname__,
  753. fn_first_lineno=self._innermost_fn.__code__.co_firstlineno,
  754. )
  755. @staticmethod
  756. def source_id_from_fn(fn: Callable[..., Any]) -> str:
  757. from .eval_frame import innermost_fn
  758. innermost_fn_ = innermost_fn(fn)
  759. sha256_hash = hashlib.sha256()
  760. sha256_hash.update(innermost_fn_.__qualname__.encode())
  761. sha256_hash.update(str(innermost_fn_.__code__.co_firstlineno).encode())
  762. return sha256_hash.hexdigest()
  763. _Backends = dict[_BackendId, Any]
  764. class DynamoStore(abc.ABC):
  765. """
  766. A DynamoStore tracks active CompilePackages, and provides methods to store and retrieve them.
  767. This is an abstract base class for different storage implementations.
  768. """
  769. def record_package(self, package: CompilePackage) -> None:
  770. """
  771. Records a package to PrecompileContext, so that it can be serialized later.
  772. """
  773. from torch._dynamo.precompile_context import PrecompileContext
  774. cache_entry = package.cache_entry()
  775. PrecompileContext.record_dynamo_cache_entry(
  776. cache_entry=cache_entry, key=package.source_id
  777. )
  778. def record_eager_backend(self, backend_id: _BackendId, backend: Any) -> None:
  779. """
  780. Records eager fx graphs to PrecompileContext for testing purposes.
  781. """
  782. from torch._dynamo.precompile_context import (
  783. EagerCacheArtifact,
  784. PrecompileContext,
  785. )
  786. result = EagerCacheArtifact(key=backend_id, content=backend)
  787. PrecompileContext.record_artifact(result)
  788. @abc.abstractmethod
  789. def clear(self) -> None: ...
  790. @abc.abstractmethod
  791. def write(
  792. self,
  793. cache_entry: PrecompileCacheEntry,
  794. path: str,
  795. ) -> None:
  796. """
  797. Abstract method to write dynamo cache entry and backends to storage.
  798. Args:
  799. dynamo: The dynamo cache entry to write
  800. backends: Dictionary of backend content to write
  801. path: Path or key to identify where to write the data
  802. """
  803. ...
  804. def save_cache_entry(self, cache_entry: _DynamoCacheEntry, key: str) -> None:
  805. """
  806. Saves a package to a given path. Grabs backends from PrecompileContext.
  807. """
  808. from torch._dynamo.precompile_context import (
  809. BackendCacheArtifact,
  810. PrecompileContext,
  811. )
  812. backend_content: _Backends = {}
  813. for backend_id in cache_entry.backend_ids:
  814. serialized_backend = PrecompileContext.serialize_artifact_by_key(backend_id)
  815. if serialized_backend is None:
  816. raise RuntimeError(
  817. f"Backend {backend_id} is not found in the given backends"
  818. )
  819. assert isinstance(serialized_backend, BackendCacheArtifact)
  820. backend_content[backend_id] = serialized_backend
  821. entry = PrecompileCacheEntry(cache_entry, backend_content)
  822. self.write(entry, key)
  823. def save_package(self, package: CompilePackage, key: str) -> None:
  824. """
  825. Saves a package to a given path. Grabs backends from PrecompileContext.
  826. """
  827. self.record_package(package)
  828. cache_entry = package.cache_entry()
  829. self.save_cache_entry(cache_entry, key)
  830. @abc.abstractmethod
  831. def read(self, path: str) -> PrecompileCacheEntry:
  832. """
  833. Abstract method to read dynamo cache entry and backends from storage.
  834. Args:
  835. path: Path or key to identify where to read the data from
  836. Returns:
  837. A tuple containing (dynamo_cache_entry, backend_content)
  838. """
  839. ...
  840. def load_cache_entry(self, key: str) -> PrecompileCacheEntry:
  841. from torch._dynamo.precompile_context import (
  842. BackendCacheArtifact,
  843. PrecompileContext,
  844. )
  845. precompile_entry = self.read(key)
  846. for backend in precompile_entry.backends.values():
  847. assert isinstance(backend, BackendCacheArtifact)
  848. PrecompileContext.record_artifact(backend)
  849. return precompile_entry
  850. def load_package(
  851. self, fn: Any, key: str
  852. ) -> tuple[CompilePackage, dict[_BackendId, Any]]:
  853. """
  854. Loads a package from a given path and returns it plus a list of deserialized backends
  855. """
  856. entry = self.load_cache_entry(key)
  857. package = CompilePackage(fn, entry.dynamo)
  858. return package, entry.backends
  859. class InMemoryDynamoStore(DynamoStore):
  860. """
  861. A DynamoStore implementation that keeps state about CompilePackages in memory.
  862. """
  863. def __init__(self) -> None:
  864. self.packages: dict[str, PrecompileCacheEntry] = {}
  865. def clear(self) -> None:
  866. self.packages.clear()
  867. def write(
  868. self,
  869. cache_entry: PrecompileCacheEntry,
  870. path: str,
  871. ) -> None:
  872. """
  873. Store the dynamo cache entry and backends in memory instead of writing to disk.
  874. """
  875. self.packages[path] = cache_entry
  876. def read(self, path: str) -> PrecompileCacheEntry:
  877. """
  878. Read dynamo cache entry and backends from memory.
  879. """
  880. if path not in self.packages:
  881. raise RuntimeError(f"No package found with key {path}")
  882. return self.packages[path]
  883. class DiskDynamoStore(DynamoStore):
  884. """
  885. A DynamoStore implementation that keeps state about CompilePackages on disk.
  886. """
  887. def __init__(self, path_prefix: str = "") -> None:
  888. """
  889. Initialize a DiskDynamoStore with a path prefix.
  890. Args:
  891. path_prefix: Prefix directory for where to put CompilePackages on disk
  892. """
  893. self._path_prefix = path_prefix
  894. def path_prefix(self) -> str:
  895. return self._path_prefix
  896. def clear(self) -> None:
  897. """
  898. Clear all CompilePackages from disk.
  899. """
  900. if self.path_prefix():
  901. shutil.rmtree(self.path_prefix(), ignore_errors=True)
  902. def write(
  903. self,
  904. cache_entry: PrecompileCacheEntry,
  905. path: str,
  906. ) -> None:
  907. """
  908. Write dynamo cache entry and backends to disk.
  909. """
  910. try:
  911. pickled_content: bytes = pickle.dumps(cache_entry)
  912. CacheArtifactManager.record_artifact(
  913. PrecompileCacheArtifact.type(), path, pickled_content
  914. )
  915. self._write_to_local_cache(pickled_content, path)
  916. except Exception as e:
  917. raise RuntimeError(f"Failed to save package to {path}: {e}") from e
  918. def _write_to_local_cache(self, pickled_content: bytes, path: str) -> None:
  919. from torch._inductor.codecache import write_atomic
  920. path = os.path.join(self.path_prefix(), path) if self.path_prefix() else path
  921. try:
  922. os.makedirs(path, exist_ok=True)
  923. write_atomic(os.path.join(path, "entry"), pickled_content)
  924. except Exception as e:
  925. raise RuntimeError(f"Failed to save package to {path}: {e}") from e
  926. def read(self, path: str) -> PrecompileCacheEntry:
  927. """
  928. Read dynamo cache entry and backends from disk.
  929. """
  930. path = os.path.join(self.path_prefix(), path) if self.path_prefix() else path
  931. try:
  932. with open(os.path.join(path, "entry"), "rb") as f:
  933. pickled_content = f.read()
  934. entry = pickle.loads(pickled_content)
  935. return entry
  936. except Exception as e:
  937. raise RuntimeError(f"Failed to load package from path {path}: {e}") from e
  938. class DiskDynamoCache(DiskDynamoStore):
  939. """
  940. Special DiskDynamoStore which adds some helper functions for automatically
  941. tracking paths of packages
  942. """
  943. def save(self, package: CompilePackage) -> None:
  944. """
  945. Saves a package to a given path. Grabs backends from PrecompileContext.
  946. """
  947. key = package.source_id
  948. logger.info("Saving CompilePackage for %s", package.source_id)
  949. super().save_package(package, key)
  950. def load(self, fn: Callable[..., Any]) -> Optional[PrecompileCacheEntry]:
  951. """
  952. Loads a package from a given path and returns it plus a list of deserialized backends
  953. """
  954. key = CompilePackage.source_id_from_fn(fn)
  955. logger.info("Loading CompilePackage for %s", key)
  956. path = os.path.join(self.path_prefix(), key)
  957. if os.path.exists(path):
  958. try:
  959. result = super().load_cache_entry(key)
  960. counters["dynamo_cache"]["dynamo_cache_hit"] += 1
  961. return result
  962. except Exception:
  963. counters["dynamo_cache"]["dynamo_cache_error"] += 1
  964. logger.warning("Failed to load package from path %s", exc_info=True)
  965. return None
  966. logger.info("No package found for %s", key)
  967. counters["dynamo_cache"]["dynamo_cache_miss"] += 1
  968. return None
  969. def load_and_install_package(
  970. self, fn: Callable[..., Any]
  971. ) -> Optional[CompilePackage]:
  972. """
  973. Load directly into a package and install backends
  974. """
  975. results = self.load(fn)
  976. if results is None:
  977. return None
  978. else:
  979. package = CompilePackage(fn, results.dynamo)
  980. package.install(results.backends)
  981. return package
  982. def path_prefix(self) -> str:
  983. return os.path.join(cache_dir(), "dynamo")
  984. def cache_dir() -> str:
  985. from torch._inductor.runtime.cache_dir_utils import cache_dir
  986. return cache_dir()
  987. DynamoCache = DiskDynamoCache(os.path.join(cache_dir(), "dynamo"))