package_exporter.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  1. # mypy: allow-untyped-defs
  2. import collections
  3. import importlib.machinery
  4. import io
  5. import linecache
  6. import os
  7. import pickletools
  8. import platform
  9. import types
  10. from collections import defaultdict, OrderedDict
  11. from collections.abc import Sequence
  12. from dataclasses import dataclass
  13. from enum import Enum
  14. from importlib.machinery import SourceFileLoader
  15. from pathlib import Path
  16. from typing import Any, Callable, cast, IO, Optional, Union
  17. import torch
  18. from torch.serialization import location_tag, normalize_storage_type
  19. from torch.types import FileLike, Storage
  20. from torch.utils.hooks import RemovableHandle
  21. from ._digraph import DiGraph
  22. from ._importlib import _normalize_path
  23. from ._mangling import demangle, is_mangled
  24. from ._package_pickler import create_pickler
  25. from ._stdlib import is_stdlib_module
  26. from .find_file_dependencies import find_files_source_depends_on
  27. from .glob_group import GlobGroup, GlobPattern
  28. from .importer import Importer, OrderedImporter, sys_importer
  29. __all__ = [
  30. "PackagingErrorReason",
  31. "EmptyMatchError",
  32. "PackagingError",
  33. "PackageExporter",
  34. ]
  35. _gate_torchscript_serialization = True
  36. ActionHook = Callable[["PackageExporter", str], None]
  37. class _ModuleProviderAction(Enum):
  38. """Represents one of the actions that :class:`PackageExporter` can take on a module.
  39. See :meth:`PackageExporter.extern` and friends for a description of what the actions do.
  40. """
  41. INTERN = 1
  42. EXTERN = 2
  43. MOCK = 3
  44. DENY = 4
  45. # Special case: when a module is mocked, PackageExporter writes out a
  46. # `_mock` module that implements our mocking stubs. If we re-package code,
  47. # we may encounter a `_mock` module from the original package. If we do,
  48. # just ignore it and write a `_mock` module once.
  49. REPACKAGED_MOCK_MODULE = 5
  50. # Special case: PackageImporter adds a fake module
  51. # (`torch_package_importer`) that allows packaged code to access it. Don't
  52. # re-export this.
  53. SKIP = 6
  54. class PackagingErrorReason(Enum):
  55. """Listing of different reasons a dependency may fail to package.
  56. This enum is used to provide good error messages when
  57. :class:`PackagingError` is raised.
  58. """
  59. def __repr__(self):
  60. return f"<{self.__class__.__name__}.{self.name}>"
  61. IS_EXTENSION_MODULE = (
  62. "Module is a C extension module. torch.package supports Python modules only."
  63. )
  64. NO_DUNDER_FILE = "Module had no __file__ defined."
  65. SOURCE_FILE_NOT_FOUND = (
  66. "Module had a __file__, but we could not find it in your filesystem."
  67. )
  68. DEPENDENCY_RESOLUTION_FAILED = "Dependency resolution failed."
  69. NO_ACTION = (
  70. "Module did not match against any action pattern. Extern, mock, or intern it."
  71. )
  72. DENIED = "Module was denied by a pattern."
  73. MOCKED_BUT_STILL_USED = (
  74. "Module was mocked out, but is still being used in the package. "
  75. "Please intern or extern the mocked modules if objects are supposed to be in "
  76. "the package."
  77. )
  78. @dataclass
  79. class _PatternInfo:
  80. """Holds :class:`PackageExporter`-specific info about how to execute matches against"""
  81. # What action to take on a module that matches this pattern.
  82. action: _ModuleProviderAction
  83. # The value of `allow_empty` the user gave when specifying the pattern.
  84. allow_empty: bool
  85. # Whether this pattern has been matched during packaging.
  86. was_matched: bool
  87. def __init__(self, action, allow_empty):
  88. self.action = action
  89. self.allow_empty = allow_empty
  90. self.was_matched = False
  91. class EmptyMatchError(Exception):
  92. """This is an exception that is thrown when a mock or extern is marked as
  93. ``allow_empty=False``, and is not matched with any module during packaging.
  94. """
  95. class PackagingError(Exception):
  96. """This exception is raised when there is an issue with exporting a package.
  97. ``PackageExporter`` will attempt to gather up all the errors and present
  98. them to you at once.
  99. """
  100. def __init__(self, dependency_graph: DiGraph, debug=False):
  101. # Group errors by reason.
  102. broken: dict[PackagingErrorReason, list[str]] = defaultdict(list)
  103. for module_name, attrs in dependency_graph.nodes.items():
  104. error = attrs.get("error")
  105. if error is None:
  106. continue
  107. if error == PackagingErrorReason.NO_ACTION:
  108. assert "action" not in attrs
  109. broken[error].append(module_name)
  110. message = io.StringIO()
  111. message.write("\n")
  112. for reason, module_names in broken.items():
  113. message.write(f"* {reason.value}\n")
  114. for module_name in module_names:
  115. message.write(f" {module_name}\n")
  116. # Print additional context if it's provided.
  117. error_context = dependency_graph.nodes[module_name].get("error_context")
  118. if error_context is not None:
  119. message.write(f" Context: {error_context}\n")
  120. if module_name in _DISALLOWED_MODULES:
  121. message.write(
  122. " Note: While we usually use modules in the python standard library "
  123. f"from the local environment, `{module_name}` has a lot of system "
  124. "level access and therefore can pose a security risk. We heavily "
  125. f"recommend removing `{module_name}` from your packaged code. However, if that "
  126. "is not possible, add it to the extern list by calling "
  127. f'PackageExporter.extern("`{module_name}`")\n'
  128. )
  129. if debug:
  130. module_path = dependency_graph.first_path(module_name)
  131. message.write(
  132. f" A path to {module_name}: {' -> '.join(module_path)}\n"
  133. )
  134. if not debug:
  135. message.write("\n")
  136. message.write(
  137. "Set debug=True when invoking PackageExporter for a visualization of where "
  138. "broken modules are coming from!\n"
  139. )
  140. # Save the dependency graph so that tooling can get at it.
  141. self.dependency_graph = dependency_graph
  142. super().__init__(message.getvalue())
  143. class PackageExporter:
  144. """Exporters allow you to write packages of code, pickled Python data, and
  145. arbitrary binary and text resources into a self-contained package.
  146. Imports can load this code in a hermetic way, such that code is loaded
  147. from the package rather than the normal Python import system. This allows
  148. for the packaging of PyTorch model code and data so that it can be run
  149. on a server or used in the future for transfer learning.
  150. The code contained in packages is copied file-by-file from the original
  151. source when it is created, and the file format is a specially organized
  152. zip file. Future users of the package can unzip the package, and edit the code
  153. in order to perform custom modifications to it.
  154. The importer for packages ensures that code in the module can only be loaded from
  155. within the package, except for modules explicitly listed as external using :meth:`extern`.
  156. The file ``extern_modules`` in the zip archive lists all the modules that a package externally depends on.
  157. This prevents "implicit" dependencies where the package runs locally because it is importing
  158. a locally-installed package, but then fails when the package is copied to another machine.
  159. When source code is added to the package, the exporter can optionally scan it
  160. for further code dependencies (``dependencies=True``). It looks for import statements,
  161. resolves relative references to qualified module names, and performs an action specified by the user
  162. (See: :meth:`extern`, :meth:`mock`, and :meth:`intern`).
  163. """
  164. """A importer that will be searched in order to find the modules referenced by other modules or by
  165. pickled objects. The default module environment just uses sys_importer, which searches the Python environment.
  166. """
  167. importer: Importer
  168. def __init__(
  169. self,
  170. f: FileLike,
  171. importer: Union[Importer, Sequence[Importer]] = sys_importer,
  172. debug: bool = False,
  173. ) -> None:
  174. """
  175. Create an exporter.
  176. Args:
  177. f: The location to export to. Can be a ``string``/``Path`` object containing a filename
  178. or a binary I/O object.
  179. importer: If a single Importer is passed, use that to search for modules.
  180. If a sequence of importers are passed, an ``OrderedImporter`` will be constructed out of them.
  181. debug: If set to True, add path of broken modules to PackagingErrors.
  182. """
  183. torch._C._log_api_usage_once("torch.package.PackageExporter")
  184. self.debug = debug
  185. if isinstance(f, (str, os.PathLike)):
  186. f = os.fspath(f)
  187. self.buffer: Optional[IO[bytes]] = None
  188. else: # is a byte buffer
  189. self.buffer = f
  190. self.zip_file = torch._C.PyTorchFileWriter(f)
  191. self.zip_file.set_min_version(6)
  192. self._written_files: set[str] = set()
  193. self.serialized_reduces: dict[int, Any] = {}
  194. # A graph tracking all the modules and pickle objects added to this
  195. # package and the dependencies between them.
  196. # - Each node is a module name (or a pickle name that looks like '<foo.obj.pkl>')
  197. # - Each directed edge (u, v) means u depends on v.
  198. # - Nodes may contain metadata that describe how to write the thing to the zipfile.
  199. self.dependency_graph = DiGraph()
  200. self.script_module_serializer = torch._C.ScriptModuleSerializer(self.zip_file)
  201. self.storage_context = self.script_module_serializer.storage_context()
  202. # These are OrderedDicts for compatibility with RemovableHandle.
  203. # Generic OrderedDict type annotations are not present until 3.7.
  204. # The real type signature is OrderedDict[int, Callable[[PackageExporter, str], None]]
  205. self._extern_hooks: OrderedDict = OrderedDict()
  206. self._mock_hooks: OrderedDict = OrderedDict()
  207. self._intern_hooks: OrderedDict = OrderedDict()
  208. if isinstance(importer, Importer):
  209. self.importer = importer
  210. else:
  211. if not isinstance(importer, collections.abc.Sequence):
  212. raise TypeError(
  213. "importer arg should be an Importer or a sequence of Importers, "
  214. f"got {type(importer)} instead."
  215. )
  216. self.importer = OrderedImporter(*importer)
  217. self.patterns: dict[GlobGroup, _PatternInfo] = {}
  218. self._unique_id = 0
  219. def save_source_file(
  220. self, module_name: str, file_or_directory: str, dependencies=True
  221. ):
  222. """Adds the local file system ``file_or_directory`` to the source package to provide the code
  223. for ``module_name``.
  224. Args:
  225. module_name (str): e.g. ``"my_package.my_subpackage"``, code will be saved to provide code for this package.
  226. file_or_directory (str): the path to a file or directory of code. When a directory, all python files in the directory
  227. are recursively copied using :meth:`save_source_file`. If a file is named ``"/__init__.py"`` the code is treated
  228. as a package.
  229. dependencies (bool, optional): If ``True``, we scan the source for dependencies.
  230. """
  231. path = Path(file_or_directory)
  232. if path.is_dir():
  233. to_save = [] # list of tuples with arguments to save_source_string
  234. module_path = module_name.replace(".", "/")
  235. for filename in path.glob("**/*.py"):
  236. relative_path = filename.relative_to(path).as_posix()
  237. archivename = module_path + "/" + relative_path
  238. submodule_name = None
  239. if filename.name == "__init__.py":
  240. submodule_name = archivename[: -len("/__init__.py")].replace(
  241. "/", "."
  242. )
  243. is_package = True
  244. else:
  245. submodule_name = archivename[: -len(".py")].replace("/", ".")
  246. is_package = False
  247. # we delay the call to save_source_string so that we record all the source files
  248. # being provided by this directory structure _before_ attempting to resolve the dependencies
  249. # on the source. This makes sure we don't try to copy over modules that will just get
  250. # overwritten by this directory blob
  251. to_save.append(
  252. (
  253. submodule_name,
  254. _read_file(str(filename)),
  255. is_package,
  256. dependencies,
  257. )
  258. )
  259. for item in to_save:
  260. self.save_source_string(*item)
  261. else:
  262. is_package = path.name == "__init__.py"
  263. self.save_source_string(
  264. module_name,
  265. _read_file(file_or_directory),
  266. is_package,
  267. dependencies,
  268. )
  269. def get_unique_id(self) -> str:
  270. """Get an id. This id is guaranteed to only be handed out once for this package."""
  271. ret = str(self._unique_id)
  272. self._unique_id += 1
  273. return ret
  274. def _get_dependencies(
  275. self, src: str, module_name: str, is_package: bool
  276. ) -> list[str]:
  277. """Return all modules that this source code depends on.
  278. Dependencies are found by scanning the source code for import-like statements.
  279. Arguments:
  280. src: The Python source code to analyze for dependencies.
  281. module_name: The name of the module that ``src`` corresponds to.
  282. is_package: Whether this module should be treated as a package.
  283. See :py:meth:`save_source_string` for more info.
  284. Returns:
  285. A list containing modules detected as direct dependencies in
  286. ``src``. The items in the list are guaranteed to be unique.
  287. """
  288. package_name = (
  289. module_name if is_package else module_name.rsplit(".", maxsplit=1)[0]
  290. )
  291. try:
  292. dep_pairs = find_files_source_depends_on(src, package_name)
  293. except Exception as e:
  294. self.dependency_graph.add_node(
  295. module_name,
  296. error=PackagingErrorReason.DEPENDENCY_RESOLUTION_FAILED,
  297. error_context=str(e),
  298. )
  299. return []
  300. # Use a dict to get uniquing but also deterministic order
  301. dependencies = {}
  302. for dep_module_name, dep_module_obj in dep_pairs:
  303. # handle the case where someone did something like `from pack import sub`
  304. # where `sub` is a submodule. In this case we don't have to save pack, just sub.
  305. # this ensures we don't pick up additional dependencies on pack.
  306. # However, in the case where `sub` is not a submodule but an object, then we do have
  307. # to save pack.
  308. if dep_module_obj is not None:
  309. possible_submodule = f"{dep_module_name}.{dep_module_obj}"
  310. if self._module_exists(possible_submodule):
  311. dependencies[possible_submodule] = True
  312. # we don't need to save `pack`
  313. continue
  314. if self._module_exists(dep_module_name):
  315. dependencies[dep_module_name] = True
  316. return list(dependencies.keys())
  317. def save_source_string(
  318. self,
  319. module_name: str,
  320. src: str,
  321. is_package: bool = False,
  322. dependencies: bool = True,
  323. ):
  324. """Adds ``src`` as the source code for ``module_name`` in the exported package.
  325. Args:
  326. module_name (str): e.g. ``my_package.my_subpackage``, code will be saved to provide code for this package.
  327. src (str): The Python source code to save for this package.
  328. is_package (bool, optional): If ``True``, this module is treated as a package. Packages are allowed to have submodules
  329. (e.g. ``my_package.my_subpackage.my_subsubpackage``), and resources can be saved inside them. Defaults to ``False``.
  330. dependencies (bool, optional): If ``True``, we scan the source for dependencies.
  331. """
  332. self.dependency_graph.add_node(
  333. module_name,
  334. source=src,
  335. is_package=is_package,
  336. provided=True,
  337. action=_ModuleProviderAction.INTERN,
  338. )
  339. if dependencies:
  340. deps = self._get_dependencies(src, module_name, is_package)
  341. for dep in deps:
  342. self.dependency_graph.add_edge(module_name, dep)
  343. self.add_dependency(dep)
  344. def _write_source_string(
  345. self,
  346. module_name: str,
  347. src: str,
  348. is_package: bool = False,
  349. ):
  350. """Write ``src`` as the source code for ``module_name`` in the zip archive.
  351. Arguments are otherwise the same as for :meth:`save_source_string`.
  352. """
  353. extension = "/__init__.py" if is_package else ".py"
  354. filename = module_name.replace(".", "/") + extension
  355. self._write(filename, src)
  356. def _import_module(self, module_name: str):
  357. try:
  358. return self.importer.import_module(module_name)
  359. except ModuleNotFoundError:
  360. if not is_mangled(module_name):
  361. raise
  362. msg = (
  363. f"Module not found: '{module_name}'. Make sure the PackageImporter that "
  364. "created this module is present in `self.importer`"
  365. )
  366. raise ModuleNotFoundError(msg) from None
  367. def _module_exists(self, module_name: str) -> bool:
  368. try:
  369. self._import_module(module_name)
  370. return True
  371. except Exception:
  372. return False
  373. def _get_source_of_module(self, module: types.ModuleType) -> Optional[str]:
  374. filename = None
  375. spec = getattr(module, "__spec__", None)
  376. if spec is not None:
  377. loader = getattr(spec, "loader", None)
  378. if loader is not None and isinstance(loader, SourceFileLoader):
  379. try:
  380. filename = loader.get_filename(module.__name__)
  381. except ImportError:
  382. pass
  383. if filename is None:
  384. filename = getattr(module, "__file__", None)
  385. if isinstance(filename, str) and filename.endswith(".py"):
  386. return "".join(linecache.getlines(filename, module.__dict__))
  387. return None
  388. def add_dependency(self, module_name: str, dependencies=True):
  389. """Given a module, add it to the dependency graph according to patterns
  390. specified by the user.
  391. """
  392. if (
  393. module_name in self.dependency_graph
  394. and self.dependency_graph.nodes[module_name].get("provided") is True
  395. ):
  396. return
  397. # Special case: PackageImporter provides a special module called
  398. # `torch_package_importer` that allows packaged modules to reference
  399. # their PackageImporter. We don't want to re-export this.
  400. if module_name == "torch_package_importer":
  401. self.dependency_graph.add_node(
  402. module_name,
  403. action=_ModuleProviderAction.SKIP,
  404. provided=True,
  405. )
  406. return
  407. if module_name == "_mock":
  408. self.dependency_graph.add_node(
  409. module_name,
  410. action=_ModuleProviderAction.REPACKAGED_MOCK_MODULE,
  411. provided=True,
  412. )
  413. return
  414. if self._can_implicitly_extern(module_name):
  415. self.dependency_graph.add_node(
  416. module_name, action=_ModuleProviderAction.EXTERN, provided=True
  417. )
  418. return
  419. for pattern, pattern_info in self.patterns.items():
  420. if pattern.matches(module_name):
  421. pattern_info.was_matched = True
  422. self.dependency_graph.add_node(
  423. module_name, action=pattern_info.action, provided=True
  424. )
  425. if pattern_info.action == _ModuleProviderAction.DENY:
  426. # Requiring a denied module just adds an error to the graph.
  427. self.dependency_graph.add_node(
  428. module_name, error=PackagingErrorReason.DENIED
  429. )
  430. # If we are interning this module, we need to retrieve its
  431. # dependencies and package those as well.
  432. if pattern_info.action == _ModuleProviderAction.INTERN:
  433. self._intern_module(module_name, dependencies)
  434. return
  435. # No patterns have matched. Explicitly add this as an error.
  436. self.dependency_graph.add_node(
  437. module_name, error=PackagingErrorReason.NO_ACTION
  438. )
  439. def save_module(self, module_name: str, dependencies=True):
  440. """Save the code for ``module`` into the package. Code for the module is resolved using the ``importers`` path to find the
  441. module object, and then using its ``__file__`` attribute to find the source code.
  442. Args:
  443. module_name (str): e.g. ``my_package.my_subpackage``, code will be saved to provide code
  444. for this package.
  445. dependencies (bool, optional): If ``True``, we scan the source for dependencies.
  446. """
  447. if not isinstance(module_name, str):
  448. raise TypeError(
  449. "save_module() expects a string input, did you perhaps mean to pass `__name__`?"
  450. )
  451. self._intern_module(module_name, dependencies)
  452. def _intern_module(
  453. self,
  454. module_name: str,
  455. dependencies: bool,
  456. ):
  457. """Adds the module to the dependency graph as an interned module,
  458. along with any metadata needed to write it out to the zipfile at serialization time.
  459. """
  460. module_obj = self._import_module(module_name)
  461. # Subtle: if the import above succeeded, either:
  462. # 1. The module name is not mangled, and this was just a regular import, or
  463. # 2. The module name is mangled, but one of the importers was able to
  464. # recognize the mangling and import it.
  465. # Either way, it is now safe to demangle this name so that we don't
  466. # serialize the mangled version to the package.
  467. module_name = demangle(module_name)
  468. # Find dependencies of this module and require them as well.
  469. is_package = hasattr(module_obj, "__path__")
  470. source = self._get_source_of_module(module_obj)
  471. if source is None:
  472. # Couldn't find a source! Add it to our dependency graph as broken
  473. # and continue.
  474. filename = getattr(module_obj, "__file__", None)
  475. error_context = None
  476. if filename is None:
  477. packaging_error = PackagingErrorReason.NO_DUNDER_FILE
  478. elif filename.endswith(tuple(importlib.machinery.EXTENSION_SUFFIXES)):
  479. packaging_error = PackagingErrorReason.IS_EXTENSION_MODULE
  480. else:
  481. packaging_error = PackagingErrorReason.SOURCE_FILE_NOT_FOUND
  482. error_context = f"filename: {filename}"
  483. self.dependency_graph.add_node(
  484. module_name,
  485. action=_ModuleProviderAction.INTERN,
  486. is_package=is_package,
  487. error=packaging_error,
  488. error_context=error_context,
  489. provided=True,
  490. )
  491. return
  492. self.dependency_graph.add_node(
  493. module_name,
  494. action=_ModuleProviderAction.INTERN,
  495. is_package=is_package,
  496. source=source,
  497. provided=True,
  498. )
  499. if dependencies:
  500. deps = self._get_dependencies(source, module_name, is_package)
  501. for dep in deps:
  502. self.dependency_graph.add_edge(module_name, dep)
  503. self.add_dependency(dep)
  504. def save_pickle(
  505. self,
  506. package: str,
  507. resource: str,
  508. obj: Any,
  509. dependencies: bool = True,
  510. pickle_protocol: int = 3,
  511. ):
  512. """Save a python object to the archive using pickle. Equivalent to :func:`torch.save` but saving into
  513. the archive rather than a stand-alone file. Standard pickle does not save the code, only the objects.
  514. If ``dependencies`` is true, this method will also scan the pickled objects for which modules are required
  515. to reconstruct them and save the relevant code.
  516. To be able to save an object where ``type(obj).__name__`` is ``my_module.MyObject``,
  517. ``my_module.MyObject`` must resolve to the class of the object according to the ``importer`` order. When saving objects that
  518. have previously been packaged, the importer's ``import_module`` method will need to be present in the ``importer`` list
  519. for this to work.
  520. Args:
  521. package (str): The name of module package this resource should go in (e.g. ``"my_package.my_subpackage"``).
  522. resource (str): A unique name for the resource, used to identify it to load.
  523. obj (Any): The object to save, must be picklable.
  524. dependencies (bool, optional): If ``True``, we scan the source for dependencies.
  525. """
  526. assert (pickle_protocol == 4) or (pickle_protocol == 3), (
  527. "torch.package only supports pickle protocols 3 and 4"
  528. )
  529. filename = self._filename(package, resource)
  530. # Write the pickle data for `obj`
  531. data_buf = io.BytesIO()
  532. pickler = create_pickler(data_buf, self.importer, protocol=pickle_protocol)
  533. pickler.persistent_id = self._persistent_id
  534. pickler.dump(obj)
  535. data_value = data_buf.getvalue()
  536. mocked_modules = defaultdict(list)
  537. name_in_dependency_graph = f"<{package}.{resource}>"
  538. self.dependency_graph.add_node(
  539. name_in_dependency_graph,
  540. action=_ModuleProviderAction.INTERN,
  541. provided=True,
  542. is_pickle=True,
  543. )
  544. def _check_mocked_error(module: Optional[str], field: Optional[str]):
  545. """
  546. checks if an object (field) comes from a mocked module and then adds
  547. the pair to mocked_modules which contains mocked modules paired with their
  548. list of mocked objects present in the pickle.
  549. We also hold the invariant that the first user defined rule that applies
  550. to the module is the one we use.
  551. """
  552. assert isinstance(module, str)
  553. assert isinstance(field, str)
  554. if self._can_implicitly_extern(module):
  555. return
  556. for pattern, pattern_info in self.patterns.items():
  557. if pattern.matches(module):
  558. if pattern_info.action == _ModuleProviderAction.MOCK:
  559. mocked_modules[module].append(field)
  560. return
  561. if dependencies:
  562. all_dependencies = []
  563. module = None
  564. field = None
  565. memo: defaultdict[int, str] = defaultdict(None)
  566. memo_count = 0
  567. # pickletools.dis(data_value)
  568. for opcode, arg, _pos in pickletools.genops(data_value):
  569. if pickle_protocol == 4:
  570. if (
  571. opcode.name == "SHORT_BINUNICODE"
  572. or opcode.name == "BINUNICODE"
  573. or opcode.name == "BINUNICODE8"
  574. ):
  575. assert isinstance(arg, str)
  576. module = field
  577. field = arg
  578. memo[memo_count] = arg
  579. elif (
  580. opcode.name == "LONG_BINGET"
  581. or opcode.name == "BINGET"
  582. or opcode.name == "GET"
  583. ):
  584. assert isinstance(arg, int)
  585. module = field
  586. field = memo.get(arg, None)
  587. elif opcode.name == "MEMOIZE":
  588. memo_count += 1
  589. elif opcode.name == "STACK_GLOBAL":
  590. if module is None:
  591. # If not module was passed on in the entries preceding this one, continue.
  592. continue
  593. assert isinstance(module, str)
  594. if module not in all_dependencies:
  595. all_dependencies.append(module)
  596. _check_mocked_error(module, field)
  597. elif (
  598. pickle_protocol == 3 and opcode.name == "GLOBAL"
  599. ): # a global reference
  600. assert isinstance(arg, str)
  601. module, field = arg.split(" ")
  602. if module not in all_dependencies:
  603. all_dependencies.append(module)
  604. _check_mocked_error(module, field)
  605. for module_name in all_dependencies:
  606. self.dependency_graph.add_edge(name_in_dependency_graph, module_name)
  607. """ If an object happens to come from a mocked module, then we collect these errors and spit them
  608. out with the other errors found by package exporter.
  609. """
  610. if module_name in mocked_modules:
  611. assert isinstance(module_name, str)
  612. fields = mocked_modules[module_name]
  613. self.dependency_graph.add_node(
  614. module_name,
  615. action=_ModuleProviderAction.MOCK,
  616. error=PackagingErrorReason.MOCKED_BUT_STILL_USED,
  617. error_context=f"Object(s) '{fields}' from module `{module_name}` was mocked out during packaging "
  618. f"but is being used in resource - `{resource}` in package `{package}`. ",
  619. provided=True,
  620. )
  621. else:
  622. self.add_dependency(module_name)
  623. self._write(filename, data_value)
  624. def save_text(self, package: str, resource: str, text: str):
  625. """Save text data to the package.
  626. Args:
  627. package (str): The name of module package this resource should go it (e.g. ``"my_package.my_subpackage"``).
  628. resource (str): A unique name for the resource, used to identify it to load.
  629. text (str): The contents to save.
  630. """
  631. return self.save_binary(package, resource, text.encode("utf-8"))
  632. def save_binary(self, package, resource, binary: bytes):
  633. """Save raw bytes to the package.
  634. Args:
  635. package (str): The name of module package this resource should go it (e.g. ``"my_package.my_subpackage"``).
  636. resource (str): A unique name for the resource, used to identify it to load.
  637. binary (str): The data to save.
  638. """
  639. filename = self._filename(package, resource)
  640. self._write(filename, binary)
  641. def register_extern_hook(self, hook: ActionHook) -> RemovableHandle:
  642. """Registers an extern hook on the exporter.
  643. The hook will be called each time a module matches against an :meth:`extern` pattern.
  644. It should have the following signature::
  645. hook(exporter: PackageExporter, module_name: str) -> None
  646. Hooks will be called in order of registration.
  647. Returns:
  648. :class:`torch.utils.hooks.RemovableHandle`:
  649. A handle that can be used to remove the added hook by calling
  650. ``handle.remove()``.
  651. """
  652. handle = RemovableHandle(self._extern_hooks)
  653. self._extern_hooks[handle.id] = hook
  654. return handle
  655. def register_mock_hook(self, hook: ActionHook) -> RemovableHandle:
  656. """Registers a mock hook on the exporter.
  657. The hook will be called each time a module matches against a :meth:`mock` pattern.
  658. It should have the following signature::
  659. hook(exporter: PackageExporter, module_name: str) -> None
  660. Hooks will be called in order of registration.
  661. Returns:
  662. :class:`torch.utils.hooks.RemovableHandle`:
  663. A handle that can be used to remove the added hook by calling
  664. ``handle.remove()``.
  665. """
  666. handle = RemovableHandle(self._mock_hooks)
  667. self._mock_hooks[handle.id] = hook
  668. return handle
  669. def register_intern_hook(self, hook: ActionHook) -> RemovableHandle:
  670. """Registers an intern hook on the exporter.
  671. The hook will be called each time a module matches against an :meth:`intern` pattern.
  672. It should have the following signature::
  673. hook(exporter: PackageExporter, module_name: str) -> None
  674. Hooks will be called in order of registration.
  675. Returns:
  676. :class:`torch.utils.hooks.RemovableHandle`:
  677. A handle that can be used to remove the added hook by calling
  678. ``handle.remove()``.
  679. """
  680. handle = RemovableHandle(self._intern_hooks)
  681. self._intern_hooks[handle.id] = hook
  682. return handle
  683. def intern(
  684. self,
  685. include: "GlobPattern",
  686. *,
  687. exclude: "GlobPattern" = (),
  688. allow_empty: bool = True,
  689. ):
  690. """Specify modules that should be packaged. A module must match some ``intern`` pattern in order to be
  691. included in the package and have its dependencies processed recursively.
  692. Args:
  693. include (Union[List[str], str]): A string e.g. "my_package.my_subpackage", or list of strings
  694. for the names of the modules to be externed. This can also be a glob-style pattern, as described in :meth:`mock`.
  695. exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the include string.
  696. allow_empty (bool): An optional flag that specifies whether the intern modules specified by this call
  697. to the ``intern`` method must be matched to some module during packaging. If an ``intern`` module glob
  698. pattern is added with ``allow_empty=False``, and :meth:`close` is called (either explicitly or via ``__exit__``)
  699. before any modules match that pattern, an exception is thrown. If ``allow_empty=True``, no such exception is thrown.
  700. """
  701. self.patterns[GlobGroup(include, exclude=exclude)] = _PatternInfo(
  702. _ModuleProviderAction.INTERN, allow_empty
  703. )
  704. def mock(
  705. self,
  706. include: "GlobPattern",
  707. *,
  708. exclude: "GlobPattern" = (),
  709. allow_empty: bool = True,
  710. ):
  711. """Replace some required modules with a mock implementation. Mocked modules will return a fake
  712. object for any attribute accessed from it. Because we copy file-by-file, the dependency resolution will sometimes
  713. find files that are imported by model files but whose functionality is never used
  714. (e.g. custom serialization code or training helpers).
  715. Use this function to mock this functionality out without having to modify the original code.
  716. Args:
  717. include (Union[List[str], str]): A string e.g. ``"my_package.my_subpackage"``, or list of strings
  718. for the names of the modules to be mocked out. Strings can also be a glob-style pattern
  719. string that may match multiple modules. Any required dependencies that match this pattern
  720. string will be mocked out automatically.
  721. Examples :
  722. ``'torch.**'`` -- matches ``torch`` and all submodules of torch, e.g. ``'torch.nn'``
  723. and ``'torch.nn.functional'``
  724. ``'torch.*'`` -- matches ``'torch.nn'`` or ``'torch.functional'``, but not
  725. ``'torch.nn.functional'``
  726. exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the include string.
  727. e.g. ``include='torch.**', exclude='torch.foo'`` will mock all torch packages except ``'torch.foo'``,
  728. Default: is ``[]``.
  729. allow_empty (bool): An optional flag that specifies whether the mock implementation(s) specified by this call
  730. to the :meth:`mock` method must be matched to some module during packaging. If a mock is added with
  731. ``allow_empty=False``, and :meth:`close` is called (either explicitly or via ``__exit__``) and the mock has
  732. not been matched to a module used by the package being exported, an exception is thrown.
  733. If ``allow_empty=True``, no such exception is thrown.
  734. """
  735. self.patterns[GlobGroup(include, exclude=exclude)] = _PatternInfo(
  736. _ModuleProviderAction.MOCK, allow_empty
  737. )
  738. def extern(
  739. self,
  740. include: "GlobPattern",
  741. *,
  742. exclude: "GlobPattern" = (),
  743. allow_empty: bool = True,
  744. ):
  745. """Include ``module`` in the list of external modules the package can import.
  746. This will prevent dependency discovery from saving
  747. it in the package. The importer will load an external module directly from the standard import system.
  748. Code for extern modules must also exist in the process loading the package.
  749. Args:
  750. include (Union[List[str], str]): A string e.g. ``"my_package.my_subpackage"``, or list of strings
  751. for the names of the modules to be externed. This can also be a glob-style pattern, as
  752. described in :meth:`mock`.
  753. exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the
  754. include string.
  755. allow_empty (bool): An optional flag that specifies whether the extern modules specified by this call
  756. to the ``extern`` method must be matched to some module during packaging. If an extern module glob
  757. pattern is added with ``allow_empty=False``, and :meth:`close` is called (either explicitly or via
  758. ``__exit__``) before any modules match that pattern, an exception is thrown. If ``allow_empty=True``,
  759. no such exception is thrown.
  760. """
  761. self.patterns[GlobGroup(include, exclude=exclude)] = _PatternInfo(
  762. _ModuleProviderAction.EXTERN, allow_empty
  763. )
  764. def deny(self, include: "GlobPattern", *, exclude: "GlobPattern" = ()):
  765. """Blocklist modules who names match the given glob patterns from the list of modules the package can import.
  766. If a dependency on any matching packages is found, a :class:`PackagingError` is raised.
  767. Args:
  768. include (Union[List[str], str]): A string e.g. ``"my_package.my_subpackage"``, or list of strings
  769. for the names of the modules to be externed. This can also be a glob-style pattern, as described in :meth:`mock`.
  770. exclude (Union[List[str], str]): An optional pattern that excludes some patterns that match the include string.
  771. """
  772. self.patterns[GlobGroup(include, exclude=exclude)] = _PatternInfo(
  773. _ModuleProviderAction.DENY, allow_empty=True
  774. )
  775. def _persistent_id(self, obj):
  776. if torch.is_storage(obj) or isinstance(obj, torch.storage.TypedStorage):
  777. storage: Storage
  778. if isinstance(obj, torch.storage.TypedStorage):
  779. # TODO: Once we decide to break serialization FC, we can
  780. # remove this case
  781. untyped_storage = obj._untyped_storage
  782. storage_type_str = obj.pickle_storage_type()
  783. storage_type = getattr(torch, storage_type_str)
  784. storage = cast(Storage, untyped_storage)
  785. storage_numel = obj.size()
  786. elif isinstance(obj, torch.UntypedStorage):
  787. untyped_storage = obj
  788. storage = cast(Storage, untyped_storage)
  789. storage_type = normalize_storage_type(type(storage))
  790. storage_numel = storage.nbytes()
  791. else:
  792. raise RuntimeError(f"storage type not recognized: {type(obj)}")
  793. location = location_tag(storage)
  794. # serialize storage if not already written
  795. storage_present = self.storage_context.has_storage(storage)
  796. storage_id = self.storage_context.get_or_add_storage(storage)
  797. if not storage_present:
  798. if storage.device.type != "cpu":
  799. storage = storage.cpu()
  800. num_bytes = storage.nbytes()
  801. self.zip_file.write_record(
  802. f".data/{storage_id}.storage", storage, num_bytes
  803. )
  804. return ("storage", storage_type, storage_id, location, storage_numel)
  805. if hasattr(obj, "__reduce_package__"):
  806. if _gate_torchscript_serialization and isinstance(
  807. obj, torch.jit.RecursiveScriptModule
  808. ):
  809. raise Exception( # noqa: TRY002
  810. "Serializing ScriptModules directly into a package is a beta feature. "
  811. "To use, set global "
  812. "`torch.package.package_exporter._gate_torchscript_serialization` to `False`."
  813. )
  814. if self.serialized_reduces.get(id(obj)) is None:
  815. self.serialized_reduces[id(obj)] = (
  816. "reduce_package",
  817. id(obj),
  818. *obj.__reduce_package__(self),
  819. )
  820. return self.serialized_reduces[id(obj)]
  821. return None
  822. def __enter__(self):
  823. return self
  824. def __exit__(self, exc_type, exc_value, traceback):
  825. # If __exit__ was called because an exception was raised, we do not
  826. # attempt to finalize the package. Instead, control is returned to the
  827. # caller to continue raising the exception.
  828. if exc_type is not None:
  829. # Do the bare minimum to leave the open buffer in a valid state.
  830. self._finalize_zip()
  831. return
  832. self.close()
  833. def _write(self, filename, str_or_bytes):
  834. if filename in self._written_files:
  835. raise AssertionError(
  836. f"Tried to write file '{filename}', but it already exists in this archive. "
  837. "Please file a bug."
  838. )
  839. self._written_files.add(filename)
  840. if is_mangled(filename):
  841. raise AssertionError(
  842. f"Tried to save a torch.package'd module as '{filename}'. "
  843. "Directly saving torch.package'd modules is not allowed."
  844. )
  845. if isinstance(str_or_bytes, str):
  846. str_or_bytes = str_or_bytes.encode("utf-8")
  847. self.zip_file.write_record(filename, str_or_bytes, len(str_or_bytes))
  848. def _validate_dependency_graph(self):
  849. # 1. Check the graph for any errors inserted during dependency analysis.
  850. for attrs in self.dependency_graph.nodes.values():
  851. if "error" in attrs:
  852. raise PackagingError(self.dependency_graph, debug=self.debug)
  853. # 2. Check that all patterns for which allow_empty=False have been matched at least once.
  854. for pattern, pattern_info in self.patterns.items():
  855. if not pattern_info.allow_empty and not pattern_info.was_matched:
  856. raise EmptyMatchError(
  857. f"Exporter did not match any modules to {pattern}, which was marked as allow_empty=False"
  858. )
  859. def _write_mock_file(self):
  860. if "_mock.py" not in self._written_files:
  861. mock_file = str(Path(__file__).parent / "_mock.py")
  862. self._write_source_string("_mock", _read_file(mock_file), is_package=False)
  863. def _execute_dependency_graph(self):
  864. """Takes a finalized dependency graph describing how to package all
  865. modules and executes it, writing to the ZIP archive.
  866. """
  867. self._validate_dependency_graph()
  868. extern_modules = []
  869. for module_name, attrs in self.dependency_graph.nodes.items():
  870. action = attrs["action"]
  871. if action == _ModuleProviderAction.EXTERN:
  872. for hook in self._extern_hooks.values():
  873. hook(self, module_name)
  874. extern_modules.append(module_name)
  875. elif action == _ModuleProviderAction.MOCK:
  876. for hook in self._mock_hooks.values():
  877. hook(self, module_name)
  878. self._write_mock_file()
  879. is_package = hasattr(self._import_module(module_name), "__path__")
  880. self._write_source_string(module_name, _MOCK_IMPL, is_package)
  881. elif action == _ModuleProviderAction.INTERN:
  882. for hook in self._intern_hooks.values():
  883. hook(self, module_name)
  884. # The node in the dependency graph contains metadata that tells us
  885. # how to intern the module.
  886. if "provided" not in attrs:
  887. raise AssertionError(
  888. f"Module was marked `intern` but not provided: {module_name}"
  889. )
  890. if attrs.get("is_pickle") is True:
  891. # This node came from save_pickle, we don't need to write any source for it.
  892. continue
  893. is_package = attrs["is_package"]
  894. source = attrs["source"]
  895. self._write_source_string(module_name, source, is_package)
  896. elif action == _ModuleProviderAction.REPACKAGED_MOCK_MODULE:
  897. self._write_mock_file()
  898. elif action == _ModuleProviderAction.SKIP:
  899. continue
  900. else:
  901. raise AssertionError(
  902. f"Invalid action: {module_name}, {action}. Please report a bug to PyTorch."
  903. )
  904. extern_file_contents = "\n".join(extern_modules) + "\n"
  905. self._write(".data/extern_modules", extern_file_contents)
  906. def _write_python_version(self):
  907. """Writes the python version that the package was created with to .data/python_version"""
  908. self._write(".data/python_version", platform.python_version())
  909. def close(self):
  910. """Write the package to the filesystem. Any calls after :meth:`close` are now invalid.
  911. It is preferable to use resource guard syntax instead::
  912. with PackageExporter("file.zip") as e:
  913. ...
  914. """
  915. self._execute_dependency_graph()
  916. self._write_python_version()
  917. self.script_module_serializer.write_files()
  918. self._finalize_zip()
  919. def _finalize_zip(self):
  920. """Called at the very end of packaging to leave the zipfile in a closed but valid state."""
  921. del self.zip_file
  922. if self.buffer:
  923. self.buffer.flush()
  924. def _filename(self, package, resource):
  925. package_path = package.replace(".", "/")
  926. resource = _normalize_path(resource)
  927. return f"{package_path}/{resource}"
  928. def _can_implicitly_extern(self, module_name: str):
  929. top_level_package_name = module_name.partition(".")[0]
  930. return top_level_package_name == "torch" or (
  931. top_level_package_name not in _DISALLOWED_MODULES
  932. and is_stdlib_module(top_level_package_name)
  933. )
  934. def dependency_graph_string(self) -> str:
  935. """Returns digraph string representation of dependencies in package.
  936. Returns:
  937. A string representation of dependencies in package.
  938. """
  939. return self.dependency_graph.to_dot()
  940. def _nodes_with_action_type(
  941. self, action: Optional[_ModuleProviderAction]
  942. ) -> list[str]:
  943. result = []
  944. for name, node_dict in self.dependency_graph.nodes.items():
  945. node_action = node_dict.get("action", None)
  946. if node_action == action and "is_pickle" not in node_dict:
  947. result.append(name)
  948. result.sort()
  949. return result
  950. def externed_modules(self) -> list[str]:
  951. """Return all modules that are currently externed.
  952. Returns:
  953. A list containing the names of modules which will be
  954. externed in this package.
  955. """
  956. return self._nodes_with_action_type(_ModuleProviderAction.EXTERN)
  957. def interned_modules(self) -> list[str]:
  958. """Return all modules that are currently interned.
  959. Returns:
  960. A list containing the names of modules which will be
  961. interned in this package.
  962. """
  963. return self._nodes_with_action_type(_ModuleProviderAction.INTERN)
  964. def mocked_modules(self) -> list[str]:
  965. """Return all modules that are currently mocked.
  966. Returns:
  967. A list containing the names of modules which will be
  968. mocked in this package.
  969. """
  970. return self._nodes_with_action_type(_ModuleProviderAction.MOCK)
  971. def denied_modules(self) -> list[str]:
  972. """Return all modules that are currently denied.
  973. Returns:
  974. A list containing the names of modules which will be
  975. denied in this package.
  976. """
  977. return self._nodes_with_action_type(_ModuleProviderAction.DENY)
  978. def get_rdeps(self, module_name: str) -> list[str]:
  979. """Return a list of all modules which depend on the module ``module_name``.
  980. Returns:
  981. A list containing the names of modules which depend on ``module_name``.
  982. """
  983. if module_name in self.dependency_graph._pred.keys():
  984. return list(self.dependency_graph._pred[module_name].keys())
  985. else:
  986. return []
  987. def all_paths(self, src: str, dst: str) -> str:
  988. """Return a dot representation of the subgraph
  989. that has all paths from src to dst.
  990. Returns:
  991. A dot representation containing all paths from src to dst.
  992. (https://graphviz.org/doc/info/lang.html)
  993. """
  994. return self.dependency_graph.all_paths(src, dst)
  995. # even though these are in the standard library, we do not allow them to be
  996. # automatically externed since they offer a lot of system level access
  997. _DISALLOWED_MODULES = ["sys", "io"]
  998. _MOCK_IMPL = """\
  999. from _mock import MockedObject
  1000. def __getattr__(attr: str):
  1001. return MockedObject(__name__ + '.' + attr, _suppress_err=True)
  1002. """
  1003. def _read_file(filename: str) -> str:
  1004. with open(filename, "rb") as f:
  1005. b = f.read()
  1006. return b.decode("utf-8")