package_exporter.py 51 KB

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