torch.package#
Created On: Jun 10, 2025 | Last Updated On: Jul 15, 2025
torch.package adds support for creating packages containing both artifacts and arbitraryPyTorch code. These packages can be saved, shared, used to load and execute modelsat a later date or on a different machine, and can even be deployed to production usingtorch::deploy.
This document contains tutorials, how-to guides, explanations, and an API reference thatwill help you learn more abouttorch.package and how to use it.
Warning
This module depends on thepickle module which is not secure. Only unpackage data you trust.
It is possible to construct malicious pickle data which willexecute arbitrary code during unpickling.Never unpackage data that could have come from an untrusted source, or that could have been tampered with.
For more information, review thedocumentation for thepickle module.
Tutorials#
Packaging your first model#
A tutorial that guides you through packaging and unpackaging a simple model is availableon Colab.After completing this exercise, you will be familiar with the basic API for creating and usingTorch packages.
How do I…#
See what is inside a package?#
Treat the package like a ZIP archive#
The container format for atorch.package is ZIP, so any tools that work with standard ZIP files shouldwork for exploring the contents. Some common ways to interact with ZIP files:
unzipmy_package.ptwill unzip thetorch.packagearchive to disk, where you can freely inspect its contents.
$ unzip my_package.pt && tree my_packagemy_package├── .data│ ├── 94304870911616.storage│ ├── 94304900784016.storage│ ├── extern_modules│ └── version├── models│ └── model_1.pkl└── torchvision └── models ├── resnet.py └── utils.py~ cd my_package && cat torchvision/models/resnet.py...
The Python
zipfilemodule provides a standard way to read and write ZIP archive contents.
fromzipfileimportZipFilewithZipFile("my_package.pt")asmyzip:file_bytes=myzip.read("torchvision/models/resnet.py")# edit file_bytes in some waymyzip.writestr("torchvision/models/resnet.py",new_file_bytes)
vim has the ability to natively read ZIP archives. You can even edit files and :
writethem back into the archive!
# add thisto your .vimrcto treat `*.pt`filesas zipfilesauBufReadCmd *.ptcall zip#Browse(expand("<amatch>"))~vi my_package.pt
Use thefile_structure() API#
PackageImporter provides afile_structure() method, which will return a printableand queryableDirectory object. TheDirectory object is a simple directory structure that you can use to explore thecurrent contents of atorch.package.
TheDirectory object itself is directly printable and will print out a file tree representation. To filter what is returned,use the glob-styleinclude andexclude filtering arguments.
withPackageExporter('my_package.pt')aspe:pe.save_pickle('models','model_1.pkl',mod)importer=PackageImporter('my_package.pt')# can limit printed items with include/exclude argsprint(importer.file_structure(include=["**/utils.py","**/*.pkl"],exclude="**/*.storage"))print(importer.file_structure())# will print out all files
Output:
# filtered with glob pattern:# include=["**/utils.py", "**/*.pkl"], exclude="**/*.storage"─── my_package.pt ├── models │ └── model_1.pkl └── torchvision └── models └── utils.py# all files─── my_package.pt ├── .data │ ├── 94304870911616.storage │ ├── 94304900784016.storage │ ├── extern_modules │ └── version ├── models │ └── model_1.pkl └── torchvision └── models ├── resnet.py └── utils.py
You can also queryDirectory objects with thehas_file() method.
importer_file_structure=importer.file_structure()found:bool=importer_file_structure.has_file("package_a/subpackage.py")
See why a given module was included as a dependency?#
Say there is a given modulefoo, and you want to know why yourPackageExporter is pulling infoo as a dependency.
PackageExporter.get_rdeps() will return all modules that directly depend onfoo.
If you would like to see how a given modulesrc depends onfoo, thePackageExporter.all_paths() method willreturn a DOT-formatted graph showing all the dependency paths betweensrc andfoo.
If you would just like to see the whole dependency graph of your :class:PackageExporter, you can usePackageExporter.dependency_graph_string().
Include arbitrary resources with my package and access them later?#
PackageExporter exposes three methods,save_pickle,save_text andsave_binary that allow you to savePython objects, text, and binary data to a package.
withtorch.PackageExporter("package.pt")asexporter:# Pickles the object and saves to `my_resources/tensor.pkl` in the archive.exporter.save_pickle("my_resources","tensor.pkl",torch.randn(4))exporter.save_text("config_stuff","words.txt","a sample string")exporter.save_binary("raw_data","binary",my_bytes)
PackageImporter exposes complementary methods namedload_pickle,load_text andload_binary that allow you to loadPython objects, text and binary data from a package.
importer=torch.PackageImporter("package.pt")my_tensor=importer.load_pickle("my_resources","tensor.pkl")text=importer.load_text("config_stuff","words.txt")binary=importer.load_binary("raw_data","binary")
Customize how a class is packaged?#
torch.package allows for the customization of how classes are packaged. This behavior is accessed through defining the method__reduce_package__ on a class and by defining a corresponding de-packaging function. This is similar to defining__reduce__ forPython’s normal pickling process.
Steps:
Define the method
__reduce_package__(self,exporter:PackageExporter)on the target class. This method should do the work to save the class instance inside of the package, and should return a tuple of the corresponding de-packaging function with the arguments needed to invoke the de-packaging function. This method is called by thePackageExporterwhen it encounters an instance of the target class.Define a de-packaging function for the class. This de-packaging function should do the work to reconstruct and return an instance of the class. The function signature’s first parameter should be a
PackageImporterinstance, and the rest of the parameters are user defined.
# foo.py [Example of customizing how class Foo is packaged]fromtorch.packageimportPackageExporter,PackageImporterimporttimeclassFoo:def__init__(self,my_string:str):super().__init__()self.my_string=my_stringself.time_imported=0self.time_exported=0def__reduce_package__(self,exporter:PackageExporter):""" Called by ``torch.package.PackageExporter``'s Pickler's ``persistent_id`` when saving an instance of this object. This method should do the work to save this object inside of the ``torch.package`` archive. Returns function w/ arguments to load the object from a ``torch.package.PackageImporter``'s Pickler's ``persistent_load`` function. """# use this pattern to ensure no naming conflicts with normal dependencies,# anything saved under this module name shouldn't conflict with other# items in the packagegenerated_module_name=f"foo-generated._{exporter.get_unique_id()}"exporter.save_text(generated_module_name,"foo.txt",self.my_string+", with exporter modification!",)time_exported=time.clock_gettime(1)# returns de-packaging function w/ arguments to invoke withreturn(unpackage_foo,(generated_module_name,time_exported,))defunpackage_foo(importer:PackageImporter,generated_module_name:str,time_exported:float)->Foo:""" Called by ``torch.package.PackageImporter``'s Pickler's ``persistent_load`` function when depickling a Foo object. Performs work of loading and returning a Foo instance from a ``torch.package`` archive. """time_imported=time.clock_gettime(1)foo=Foo(importer.load_text(generated_module_name,"foo.txt"))foo.time_imported=time_importedfoo.time_exported=time_exportedreturnfoo
# example of saving instances of class Fooimporttorchfromtorch.packageimportPackageImporter,PackageExporterimportfoofoo_1=foo.Foo("foo_1 initial string")foo_2=foo.Foo("foo_2 initial string")withPackageExporter('foo_package.pt')aspe:# save as normal, no extra work necessarype.save_pickle('foo_collection','foo1.pkl',foo_1)pe.save_pickle('foo_collection','foo2.pkl',foo_2)pi=PackageImporter('foo_package.pt')print(pi.file_structure())imported_foo=pi.load_pickle('foo_collection','foo1.pkl')print(f"foo_1 string: '{imported_foo.my_string}'")print(f"foo_1 export time:{imported_foo.time_exported}")print(f"foo_1 import time:{imported_foo.time_imported}")
# output of running above script─── foo_package ├── foo-generated │ ├── _0 │ │ └── foo.txt │ └── _1 │ └── foo.txt ├── foo_collection │ ├── foo1.pkl │ └── foo2.pkl └── foo.pyfoo_1 string: 'foo_1 initial string, with reduction modification!'foo_1 export time: 9857706.650140837foo_1 import time: 9857706.652698385
Test in my source code whether or not it is executing inside a package?#
APackageImporter will add the attribute__torch_package__ to every module that it initializes. Your code can check for thepresence of this attribute to determine whether it is executing in a packaged context or not.
# In foo/bar.py:if"__torch_package__"indir():# true if the code is being loaded from a packagedefis_in_package():returnTrueUserException=Exceptionelse:defis_in_package():returnFalseUserException=UnpackageableException
Now, the code will behave differently depending on whether it’s imported normally through your Python environment or imported from atorch.package.
fromfoo.barimportis_in_packageprint(is_in_package())# Falseloaded_module=PackageImporter(my_package).import_module("foo.bar")loaded_module.is_in_package()# True
Warning: in general, it’s bad practice to have code that behaves differently depending on whether it’s packaged or not. This can lead tohard-to-debug issues that are sensitive to how you imported your code. If your package is intended to be heavily used, consider restructuringyour code so that it behaves the same way no matter how it was loaded.
Patch code into a package?#
PackageExporter offers asave_source_string() method that allows one to save arbitrary Python source code to a module of your choosing.
withPackageExporter(f)asexporter:# Save the my_module.foo available in your current Python environment.exporter.save_module("my_module.foo")# This saves the provided string to my_module/foo.py in the package archive.# It will override the my_module.foo that was previously saved.exporter.save_source_string("my_module.foo",textwrap.dedent("""\ def my_function(): print('hello world') """))# If you want to treat my_module.bar as a package# (e.g. save to `my_module/bar/__init__.py` instead of `my_module/bar.py)# pass is_package=True,exporter.save_source_string("my_module.bar","def foo(): print('hello')\n",is_package=True)importer=PackageImporter(f)importer.import_module("my_module.foo").my_function()# prints 'hello world'
Access package contents from packaged code?#
PackageImporter implements theimportlib.resourcesAPI for accessing resources from inside a package.
withPackageExporter(f)asexporter:# saves text to my_resource/a.txt in the archiveexporter.save_text("my_resource","a.txt","hello world!")# saves the tensor to my_pickle/obj.pklexporter.save_pickle("my_pickle","obj.pkl",torch.ones(2,2))# see below for module contentsexporter.save_module("foo")exporter.save_module("bar")
Theimportlib.resources API allows access to resources from within packaged code.
# foo.py:importimportlib.resourcesimportmy_resource# returns "hello world!"defget_my_resource():returnimportlib.resources.read_text(my_resource,"a.txt")
Usingimportlib.resources is the recommended way to access package contents from within packaged code, since it complieswith the Python standard. However, it is also possible to access the parent :class:PackageImporter instance itself from withinpackaged code.
# bar.py:importtorch_package_importer# this is the PackageImporter that imported this module.# Prints "hello world!", equivalent to importlib.resources.read_textdefget_my_resource():returntorch_package_importer.load_text("my_resource","a.txt")# You also do things that the importlib.resources API does not support, like loading# a pickled object from the package.defget_my_pickle():returntorch_package_importer.load_pickle("my_pickle","obj.pkl")
Distinguish between packaged code and non-packaged code?#
To tell if an object’s code is from atorch.package, use thetorch.package.is_from_package() function.Note: if an object is from a package but its definition is from a module markedextern or fromstdlib,this check will returnFalse.
importer=PackageImporter(f)mod=importer.import_module('foo')obj=importer.load_pickle('model','model.pkl')txt=importer.load_text('text','my_test.txt')assertis_from_package(mod)assertis_from_package(obj)assertnotis_from_package(txt)# str is from stdlib, so this will return False
Re-export an imported object?#
To re-export an object that was previously imported by aPackageImporter, you must make the newPackageExporteraware of the originalPackageImporter so that it can find source code for your object’s dependencies.
importer=PackageImporter(f)obj=importer.load_pickle("model","model.pkl")# re-export obj in a new packagewithPackageExporter(f2,importer=(importer,sys_importer))asexporter:exporter.save_pickle("model","model.pkl",obj)
Explanation#
torch.package Format Overview#
Atorch.package file is a ZIP archive which conventionally uses the.pt extension. Inside the ZIP archive, there are two kinds of files:
Framework files, which are placed in the
.data/.User files, which is everything else.
As an example, this is what a fully packaged ResNet model fromtorchvision looks like:
resnet├── .data # All framework-specific data is stored here.│ │ # It's named to avoid conflicts with user-serialized code.│ ├── 94286146172688.storage # tensor data│ ├── 94286146172784.storage│ ├── extern_modules # text file with names of extern modules (e.g. 'torch')│ ├── version # version metadata│ ├── ...├── model # the pickled model│ └── model.pkl└── torchvision # all code dependencies are captured as source files └── models ├── resnet.py └── utils.py
Framework files#
The.data/ directory is owned by torch.package, and its contents are considered to be a private implementation detail.Thetorch.package format makes no guarantees about the contents of.data/, but any changes made will be backward compatible(that is, newer version of PyTorch will always be able to load oldertorch.packages).
Currently, the.data/ directory contains the following items:
version: a version number for the serialized format, so that thetorch.packageimport infrastructures knows how to load this package.extern_modules: a list of modules that are consideredextern.externmodules will be imported using the loading environment’s system importer.*.storage: serialized tensor data.
.data├── 94286146172688.storage├── 94286146172784.storage├── extern_modules├── version├── ...
User files#
All other files in the archive were put there by a user. The layout is identical to a Pythonregular package. For a deeper dive in how Python packaging works,please consultthis essay (it’s slightly out of date, so double-check implementation detailswith thePython reference documentation.
<package root>├── model # the pickled model│ └── model.pkl├── another_package│ ├── __init__.py│ ├── foo.txt # a resource file , see importlib.resources│ └── ...└── torchvision └── models ├── resnet.py # torchvision.models.resnet └── utils.py # torchvision.models.utils
Howtorch.package finds your code’s dependencies#
Analyzing an object’s dependencies#
When you issue asave_pickle(obj,...) call,PackageExporter will pickle the object normally. Then, it uses thepickletools standard library module to parse the pickle bytecode.
In a pickle, an object is saved along with aGLOBAL opcode that describes where to find the implementation of the object’s type, like:
GLOBAL'torchvision.models.resnet Resnet`
The dependency resolver will gather up allGLOBAL ops and mark them as dependencies of your pickled object.For more information about pickling and the pickle format, please consultthe Python docs.
Analyzing a module’s dependencies#
When a Python module is identified as a dependency,torch.package walks the module’s python AST representation and looks for import statements withfull support for the standard forms:fromximporty,importz,fromwimportvasu, etc. When one of these import statements areencountered,torch.package registers the imported modules as dependencies that are then themselves parsed in the same AST walking way.
Note: AST parsing has limited support for the__import__(...) syntax and does not supportimportlib.import_module calls. In general, you shouldnot expect dynamic imports to be detected bytorch.package.
Dependency Management#
torch.package automatically finds the Python modules that your code and objects depend on. This process is called dependency resolution.For each module that the dependency resolver finds, you must specify anaction to take.
The allowed actions are:
intern: put this module into the package.extern: declare this module as an external dependency of the package.mock: stub out this module.deny: depending on this module will raise an error during package export.
Finally, there is one more important action that is not technically part oftorch.package:
Refactoring: remove or change the dependencies in your code.
Note that actions are only defined on entire Python modules. There is no way to package “just” a function or class from a module and leave the rest out.This is by design. Python does not offer clean boundaries between objects defined in a module. The only defined unit of dependency organization is amodule, so that’s whattorch.package uses.
Actions are applied to modules using patterns. Patterns can either be module names ("foo.bar") or globs (like"foo.**"). You associate a patternwith an action using methods onPackageExporter, e.g.
my_exporter.intern("torchvision.**")my_exporter.extern("numpy")
If a module matches a pattern, the corresponding action is applied to it. For a given module, patterns will be checked in the order that they were defined,and the first action will be taken.
intern#
If a module isintern-ed, it will be placed into the package.
This action is your model code, or any related code you want to package. For example, if you are trying to package a ResNet fromtorchvision,you will need tointern the module torchvision.models.resnet.
On package import, when your packaged code tries to import anintern-ed module, PackageImporter will look inside your package for that module.If it can’t find that module, an error will be raised. This ensures that eachPackageImporter is isolated from the loading environment—evenif you havemy_interned_module available in both your package and the loading environment,PackageImporter will only use the version in yourpackage.
Note: Only Python source modules can beintern-ed. Other kinds of modules, like C extension modules and bytecode modules, will raise an error ifyou attempt tointern them. These kinds of modules need to bemock-ed orextern-ed.
extern#
If a module isextern-ed, it will not be packaged. Instead, it will be added to a list of external dependencies for this package. You can find thislist onpackage_exporter.extern_modules.
On package import, when the packaged code tries to import anextern-ed module,PackageImporter will use the default Python importer to findthat module, as if you didimportlib.import_module("my_externed_module"). If it can’t find that module, an error will be raised.
In this way, you can depend on third-party libraries likenumpy andscipy from within your package without having to package them too.
Warning: If any external library changes in a backwards-incompatible way, your package may fail to load. If you need long-term reproducibilityfor your package, try to limit your use ofextern.
mock#
If a module ismock-ed, it will not be packaged. Instead a stub module will be packaged in its place. The stub module will allow you to retrieveobjects from it (so thatfrommy_mocked_moduleimportfoo will not error), but any use of that object will raise aNotImplementedError.
mock should be used for code that you “know” will not be needed in the loaded package, but you still want available for use in non-packaged contents.For example, initialization/configuration code, or code only used for debugging/training.
Warning: In general,mock should be used as a last resort. It introduces behavioral differences between packaged code and non-packaged code,which may lead to later confusion. Prefer instead to refactor your code to remove unwanted dependencies.
Refactoring#
The best way to manage dependencies is to not have dependencies at all! Often, code can be refactored to remove unnecessary dependencies. Here are someguidelines for writing code with clean dependencies (which are also generally good practices!):
Include only what you use. Do not leave unused imports in your code. The dependency resolver is not smart enough to tell that they are indeed unused,and will try to process them.
Qualify your imports. For example, instead of writing import foo and later usingfoo.bar.baz, prefer to writefromfoo.barimportbaz. This moreprecisely specifies your real dependency (foo.bar) and lets the dependency resolver know you don’t need all offoo.
Split up large files with unrelated functionality into smaller ones. If yourutils module contains a hodge-podge of unrelated functionality, any modulethat depends onutils will need to pull in lots of unrelated dependencies, even if you only needed a small part of it. Prefer instead to definesingle-purpose modules that can be packaged independently of one another.
Patterns#
Patterns allow you to specify groups of modules with a convenient syntax. The syntax and behavior of patterns follows the Bazel/Buckglob().
A module that we are trying to match against a pattern is called a candidate. A candidate is composed of a list of segments separated by aseparator string, e.g.foo.bar.baz.
A pattern contains one or more segments. Segments can be:
A literal string (e.g.
foo), which matches exactly.A string containing a wildcard (e.g.
torch, orfoo*baz*). The wildcard matches any string, including the empty string.A double wildcard (
**). This matches against zero or more complete segments.
Examples:
torch.**: matchestorchand all its submodules, e.g.torch.nnandtorch.nn.functional.torch.*: matchestorch.nnortorch.functional, but nottorch.nn.functionalortorchtorch*.**: matchestorch,torchvision, and all of their submodules
When specifying actions, you can pass multiple patterns, e.g.
exporter.intern(["torchvision.models.**","torchvision.utils.**"])
A module will match against this action if it matches any of the patterns.
You can also specify patterns to exclude, e.g.
exporter.mock("**",exclude=["torchvision.**"])
A module will not match against this action if it matches any of the exclude patterns. In this example, we are mocking all modules excepttorchvision and its submodules.
When a module could potentially match against multiple actions, the first action defined will be taken.
torch.package sharp edges#
Avoid global state in your modules#
Python makes it really easy to bind objects and run code at module-level scope. This is generally fine—after all, functions and classes are bound tonames this way. However, things become more complicated when you define an object at module scope with the intention of mutating it, introducing mutableglobal state.
Mutable global state is quite useful—it can reduce boilerplate, allow for open registration into tables, etc. But unless employed very carefully, it cancause complications when used withtorch.package.
EveryPackageImporter creates an independent environment for its contents. This is nice because it means we load multiple packages and ensurethey are isolated from each other, but when modules are written in a way that assumes shared mutable global state, this behavior can create hard-to-debugerrors.
Types are not shared between packages and the loading environment#
Any class that you import from aPackageImporter will be a version of the class specific to that importer. For example:
fromfooimportMyClassmy_class_instance=MyClass()withPackageExporter(f)asexporter:exporter.save_module("foo")importer=PackageImporter(f)imported_MyClass=importer.import_module("foo").MyClassassertisinstance(my_class_instance,MyClass)# worksassertisinstance(my_class_instance,imported_MyClass)# ERROR!
In this example,MyClass andimported_MyClass arenot the same type. In this specific example,MyClass andimported_MyClass have exactly thesame implementation, so you might think it’s okay to consider them the same class. But consider the situation whereimported_MyClass is coming from anolder package with an entirely different implementation ofMyClass — in that case, it’s unsafe to consider them the same class.
Under the hood, each importer has a prefix that allows it to uniquely identify classes:
print(MyClass.__name__)# prints "foo.MyClass"print(imported_MyClass.__name__)# prints <torch_package_0>.foo.MyClass
That means you should not expectisinstance checks to work when one of the arguments is from a package and the other is not. If you need thisfunctionality, consider the following options:
Doing duck typing (just using the class instead of explicitly checking that it is of a given type).
Make the typing relationship an explicit part of the class contract. For example, you can add an attribute tag
self.handler="handle_me_this_way"and have client code check for the value ofhandlerinstead of checking the type directly.
Howtorch.package keeps packages isolated from each other#
EachPackageImporter instance creates an independent, isolated environment for its modules and objects. Modules in a package can only importother packaged modules, or modules markedextern. If you use multiplePackageImporter instances to load a single package, you will getmultiple independent environments that do not interact.
This is achieved by extending Python’s import infrastructure with a custom importer.PackageImporter provides the same core API as theimportlib importer; namely, it implements theimport_module and__import__ methods.
When you invokePackageImporter.import_module(),PackageImporter will construct and return a new module, much as the system importer does.However,PackageImporter patches the returned module to useself (i.e. thatPackageImporter instance) to fulfill future importrequests by looking in the package rather than searching the user’s Python environment.
Mangling#
To avoid confusion (“is thisfoo.bar object the one from my package, or the one from my Python environment?”),PackageImporter mangles the__name__ and__file__ of all imported modules, by adding amangle prefix to them.
For__name__, a name liketorchvision.models.resnet18 becomes<torch_package_0>.torchvision.models.resnet18.
For__file__, a name liketorchvision/models/resnet18.py becomes<torch_package_0>.torchvision/modules/resnet18.py.
Name mangling helps avoid inadvertent punning of module names between different packages, and helps you debug by making stack traces and printstatements more clearly show whether they are referring to packaged code or not. For developer-facing details about mangling, consultmangling.md intorch/package/.
API Reference#
- classtorch.package.PackagingError(dependency_graph,debug=False)[source]#
This exception is raised when there is an issue with exporting a package.
PackageExporterwill attempt to gather up all the errors and presentthem to you at once.
- classtorch.package.EmptyMatchError[source]#
This is an exception that is thrown when a mock or extern is marked as
allow_empty=False, and is not matched with any module during packaging.
- classtorch.package.PackageExporter(f,importer=<torch.package.importer._SysImporterobject>,debug=False)[source]#
Exporters allow you to write packages of code, pickled Python data, andarbitrary binary and text resources into a self-contained package.
Imports can load this code in a hermetic way, such that code is loadedfrom the package rather than the normal Python import system. This allowsfor the packaging of PyTorch model code and data so that it can be runon a server or used in the future for transfer learning.
The code contained in packages is copied file-by-file from the originalsource when it is created, and the file format is a specially organizedzip file. Future users of the package can unzip the package, and edit the codein order to perform custom modifications to it.
The importer for packages ensures that code in the module can only be loaded fromwithin the package, except for modules explicitly listed as external using
extern().The fileextern_modulesin the zip archive lists all the modules that a package externally depends on.This prevents “implicit” dependencies where the package runs locally because it is importinga locally-installed package, but then fails when the package is copied to another machine.When source code is added to the package, the exporter can optionally scan itfor further code dependencies (
dependencies=True). It looks for import statements,resolves relative references to qualified module names, and performs an action specified by the user(See:extern(),mock(), andintern()).- __init__(f,importer=<torch.package.importer._SysImporterobject>,debug=False)[source]#
Create an exporter.
- Parameters:
f (str |PathLike[str]|IO[bytes]) – The location to export to. Can be a
string/Pathobject containing a filenameor a binary I/O object.importer (Importer |Sequence[Importer]) – If a single Importer is passed, use that to search for modules.If a sequence of importers are passed, an
OrderedImporterwill be constructed out of them.debug (bool) – If set to True, add path of broken modules to PackagingErrors.
- add_dependency(module_name,dependencies=True)[source]#
Given a module, add it to the dependency graph according to patternsspecified by the user.
- all_paths(src,dst)[source]#
- Return a dot representation of the subgraph
that has all paths from src to dst.
- Returns:
A dot representation containing all paths from src to dst.(https://graphviz.org/doc/info/lang.html)
- Return type:
- close()[source]#
Write the package to the filesystem. Any calls after
close()are now invalid.It is preferable to use resource guard syntax instead:withPackageExporter("file.zip")ase:...
- deny(include,*,exclude=())[source]#
Blocklist modules who names match the given glob patterns from the list of modules the package can import.If a dependency on any matching packages is found, a
PackagingErroris raised.- Parameters:
include (Union[List[str],str]) – A string e.g.
"my_package.my_subpackage", or list of stringsfor the names of the modules to be externed. This can also be a glob-style pattern, as described inmock().exclude (Union[List[str],str]) – An optional pattern that excludes some patterns that match the include string.
- dependency_graph_string()[source]#
Returns digraph string representation of dependencies in package.
- Returns:
A string representation of dependencies in package.
- Return type:
- extern(include,*,exclude=(),allow_empty=True)[source]#
Include
modulein the list of external modules the package can import.This will prevent dependency discovery from savingit in the package. The importer will load an external module directly from the standard import system.Code for extern modules must also exist in the process loading the package.- Parameters:
include (Union[List[str],str]) – A string e.g.
"my_package.my_subpackage", or list of stringsfor the names of the modules to be externed. This can also be a glob-style pattern, asdescribed inmock().exclude (Union[List[str],str]) – An optional pattern that excludes some patterns that match theinclude string.
allow_empty (bool) – An optional flag that specifies whether the extern modules specified by this callto the
externmethod must be matched to some module during packaging. If an extern module globpattern is added withallow_empty=False, andclose()is called (either explicitly or via__exit__) before any modules match that pattern, an exception is thrown. Ifallow_empty=True,no such exception is thrown.
- get_unique_id()[source]#
Get an id. This id is guaranteed to only be handed out once for this package.
- Return type:
- intern(include,*,exclude=(),allow_empty=True)[source]#
Specify modules that should be packaged. A module must match some
internpattern in order to beincluded in the package and have its dependencies processed recursively.- Parameters:
include (Union[List[str],str]) – A string e.g. “my_package.my_subpackage”, or list of stringsfor the names of the modules to be externed. This can also be a glob-style pattern, as described in
mock().exclude (Union[List[str],str]) – An optional pattern that excludes some patterns that match the include string.
allow_empty (bool) – An optional flag that specifies whether the intern modules specified by this callto the
internmethod must be matched to some module during packaging. If aninternmodule globpattern is added withallow_empty=False, andclose()is called (either explicitly or via__exit__)before any modules match that pattern, an exception is thrown. Ifallow_empty=True, no such exception is thrown.
- mock(include,*,exclude=(),allow_empty=True)[source]#
Replace some required modules with a mock implementation. Mocked modules will return a fakeobject for any attribute accessed from it. Because we copy file-by-file, the dependency resolution will sometimesfind files that are imported by model files but whose functionality is never used(e.g. custom serialization code or training helpers).Use this function to mock this functionality out without having to modify the original code.
- Parameters:
include (Union[List[str],str]) –
A string e.g.
"my_package.my_subpackage", or list of stringsfor the names of the modules to be mocked out. Strings can also be a glob-style patternstring that may match multiple modules. Any required dependencies that match this patternstring will be mocked out automatically.- Examples :
'torch.**'– matchestorchand all submodules of torch, e.g.'torch.nn'and'torch.nn.functional''torch.*'– matches'torch.nn'or'torch.functional', but not'torch.nn.functional'
exclude (Union[List[str],str]) – An optional pattern that excludes some patterns that match the include string.e.g.
include='torch.**',exclude='torch.foo'will mock all torch packages except'torch.foo',Default: is[].allow_empty (bool) – An optional flag that specifies whether the mock implementation(s) specified by this callto the
mock()method must be matched to some module during packaging. If a mock is added withallow_empty=False, andclose()is called (either explicitly or via__exit__) and the mock hasnot been matched to a module used by the package being exported, an exception is thrown.Ifallow_empty=True, no such exception is thrown.
- register_extern_hook(hook)[source]#
Registers an extern hook on the exporter.
The hook will be called each time a module matches against an
extern()pattern.It should have the following signature:hook(exporter:PackageExporter,module_name:str)->None
Hooks will be called in order of registration.
- Returns:
A handle that can be used to remove the added hook by calling
handle.remove().- Return type:
torch.utils.hooks.RemovableHandle
- register_intern_hook(hook)[source]#
Registers an intern hook on the exporter.
The hook will be called each time a module matches against an
intern()pattern.It should have the following signature:hook(exporter:PackageExporter,module_name:str)->None
Hooks will be called in order of registration.
- Returns:
A handle that can be used to remove the added hook by calling
handle.remove().- Return type:
torch.utils.hooks.RemovableHandle
- register_mock_hook(hook)[source]#
Registers a mock hook on the exporter.
The hook will be called each time a module matches against a
mock()pattern.It should have the following signature:hook(exporter:PackageExporter,module_name:str)->None
Hooks will be called in order of registration.
- Returns:
A handle that can be used to remove the added hook by calling
handle.remove().- Return type:
torch.utils.hooks.RemovableHandle
- save_module(module_name,dependencies=True)[source]#
Save the code for
moduleinto the package. Code for the module is resolved using theimporterspath to find themodule object, and then using its__file__attribute to find the source code.
- save_pickle(package,resource,obj,dependencies=True,pickle_protocol=3)[source]#
Save a python object to the archive using pickle. Equivalent to
torch.save()but saving intothe archive rather than a stand-alone file. Standard pickle does not save the code, only the objects.Ifdependenciesis true, this method will also scan the pickled objects for which modules are requiredto reconstruct them and save the relevant code.To be able to save an object where
type(obj).__name__ismy_module.MyObject,my_module.MyObjectmust resolve to the class of the object according to theimporterorder. When saving objects thathave previously been packaged, the importer’simport_modulemethod will need to be present in theimporterlistfor this to work.- Parameters:
package (str) – The name of module package this resource should go in (e.g.
"my_package.my_subpackage").resource (str) – A unique name for the resource, used to identify it to load.
obj (Any) – The object to save, must be picklable.
dependencies (bool,optional) – If
True, we scan the source for dependencies.
- save_source_file(module_name,file_or_directory,dependencies=True)[source]#
Adds the local file system
file_or_directoryto the source package to provide the codeformodule_name.- Parameters:
module_name (str) – e.g.
"my_package.my_subpackage", code will be saved to provide code for this package.file_or_directory (str) – the path to a file or directory of code. When a directory, all python files in the directoryare recursively copied using
save_source_file(). If a file is named"/__init__.py"the code is treatedas a package.dependencies (bool,optional) – If
True, we scan the source for dependencies.
- save_source_string(module_name,src,is_package=False,dependencies=True)[source]#
Adds
srcas the source code formodule_namein the exported package.- Parameters:
module_name (str) – e.g.
my_package.my_subpackage, code will be saved to provide code for this package.src (str) – The Python source code to save for this package.
is_package (bool,optional) – If
True, this module is treated as a package. Packages are allowed to have submodules(e.g.my_package.my_subpackage.my_subsubpackage), and resources can be saved inside them. Defaults toFalse.dependencies (bool,optional) – If
True, we scan the source for dependencies.
- classtorch.package.PackageImporter(file_or_buffer,module_allowed=<functionPackageImporter.<lambda>>)[source]#
Importers allow you to load code written to packages by
PackageExporter.Code is loaded in a hermetic way, using files from the packagerather than the normal python import system. This allowsfor the packaging of PyTorch model code and data so that it can be runon a server or used in the future for transfer learning.The importer for packages ensures that code in the module can only be loaded fromwithin the package, except for modules explicitly listed as external during export.The file
extern_modulesin the zip archive lists all the modules that a package externally depends on.This prevents “implicit” dependencies where the package runs locally because it is importinga locally-installed package, but then fails when the package is copied to another machine.- __init__(file_or_buffer,module_allowed=<functionPackageImporter.<lambda>>)[source]#
Open
file_or_bufferfor importing. This checks that the imported package only requires modulesallowed bymodule_allowed- Parameters:
file_or_buffer (str |PathLike[str]|IO[bytes]|PyTorchFileReader) – a file-like object (has to implement
read(),readline(),tell(), andseek()),a string, or anos.PathLikeobject containing a filename.module_allowed (Callable[[str],bool],optional) – A method to determine if a externally provided moduleshould be allowed. Can be used to ensure packages loaded do not depend on modules that the serverdoes not support. Defaults to allowing anything.
- Raises:
ImportError – If the package will use a disallowed module.
- file_structure(*,include='**',exclude=())[source]#
Returns a file structure representation of package’s zipfile.
- Parameters:
include (Union[List[str],str]) – An optional string e.g.
"my_package.my_subpackage", or optional list of stringsfor the names of the files to be included in the zipfile representation. This can also bea glob-style pattern, as described inPackageExporter.mock()exclude (Union[List[str],str]) – An optional pattern that excludes files whose name match the pattern.
- Returns:
- Return type:
- id()[source]#
Returns internal identifier that torch.package uses to distinguish
PackageImporterinstances.Looks like:<torch_package_0>
- import_module(name,package=None)[source]#
Load a module from the package if it hasn’t already been loaded, and then returnthe module. Modules are loaded locallyto the importer and will appear in
self.modulesrather thansys.modules.- Parameters:
- Returns:
The (possibly already) loaded module.
- Return type:
- load_pickle(package,resource,map_location=None)[source]#
Unpickles the resource from the package, loading any modules that are needed to construct the objectsusing
import_module().
- python_version()[source]#
Returns the version of python that was used to create this package.
Note: this function is experimental and not Forward Compatible. The plan is to move this into a lockfile later on.
- Returns:
Optional[str]a python version e.g. 3.8.9 or None if no version was stored with this package
- classtorch.package.Directory(name,is_dir)[source]#
A file structure representation. Organized as Directory nodes that have lists oftheir Directory children. Directories for a package are created by calling
PackageImporter.file_structure().