package_exporter.py 50 KB

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