This note describes how you can save and load PyTorch tensors and module states
in Python, and how to serialize Python modules so they can be loaded in C++.
By convention, PyTorch files are typically written with a ‘.pt’ or ‘.pth’ extension.
torch.save() and torch.load() use Python’s pickle by default,
so you can also save multiple tensors as part of Python objects like tuples,
lists, and dicts:
Behind the scenes, these tensors share the same “storage.” See
Tensor Views for more
on views and storage.
When PyTorch saves tensors it saves their storage objects and tensor
metadata separately. This is an implementation detail that may change in the
future, but it typically saves space and lets PyTorch easily
reconstruct the view relationships between the loaded tensors. In the above
snippet, for example, only a single storage is written to ‘tensors.pt’.
In some cases, however, saving the current storage objects may be unnecessary
and create prohibitively large files. In the following snippet a storage much
larger than the saved tensor is written to a file:
Instead of saving only the five values in the small tensor to ‘small.pt,’
the 999 values in the storage it shares with large were saved and loaded.
When saving tensors with fewer elements than their storage objects, the size of
the saved file can be reduced by first cloning the tensors. Cloning a tensor
produces a new tensor with a new storage object containing only the values
in the tensor:
>>> large=torch.arange(1,1000)>>> small=large[0:5]>>> torch.save(small.clone(),'small.pt')# saves a clone of small>>> loaded_small=torch
Since the cloned tensors are independent of each other, however, they have
none of the view relationships the original tensors did. If both file size and
view relationships are important when saving tensors smaller than their
storage objects, then care must be taken to construct new tensors that minimize
the size of their storage objects but still have the desired view relationships
before saving.
In PyTorch, a module’s state is frequently serialized using a ‘state dict.’
A module’s state dict contains all of its parameters and persistent buffers:
Instead of saving a module directly, for compatibility reasons it is recommended
to instead save only its state dict. Python modules even have a function,
load_state_dict(), to restore their states from a state dict:
data.pkl is the result of pickling the object passed to torch.save
excluding torch.Storage objects that it contains
byteorder contains a string with the sys.byteorder when saving (“little” or “big”)
data/ contains all the storages in the object, where each storage is a separate file
version contains a version number at save time that can be used at load time
When saving, PyTorch will ensure that the local file header of each file is padded
to an offset that is a multiple of 64 bytes, ensuring that the offset of each file
is 64-byte aligned.
Layout Control
The mmap argument in torch.load() allows for lazy loading of tensor storages.
In addition, there are some advanced features that allow for more fine-grained
control and manipulation of a torch.save checkpoint.
Saving a checkpoint with torch.save that includes empty space for data bytes
to be written later.
Loading a checkpoint with torch.load and filling in the data bytes of tensors later.
To inspect tensor metadata in a torch.save checkpoint without allocating memory for storage
data, use torch.load within the FakeTensorMode context manager. On top of skipping loading
storage data similar to skip_data above, it additionally tags storages with their offset within
the checkpoint, enabling direct checkpoint manipulation.
For more information, this tutorial
offers a comprehensive example of using these features to manipulate a checkpoint.
torch.load with weights_only=True
Starting in version 2.6, torch.load will use weights_only=True if the pickle_module
argument is not passed.
weights_only security
As discussed in the documentation for torch.load(), weights_only=True restricts
the unpickler used in torch.load to only executing functions/building classes required for
state_dicts of plain torch.Tensors as well as some other primitive types. Further,
unlike the default Unpickler provided by the pickle module, the weights_only Unpickler
is not allowed to dynamically import anything during unpickling.
weights_only=True narrows the surface of remote code execution attacks but has the following limitations:
weights_only=True does not guard against denial of service attacks.
We try to prevent memory corruptions during torch.load(weights_only=True) but they might still be possible.
Note that even if memory corruption does not occur during torch.load itself, loading CAN create
unexpected objects for the downstream code that can also lead to memory corruption (e.g. a Tensor of
indices and values made to a sparse Tensor in user code might write/read out of bounds).
weights_only allowlist
As mentioned above, saving a module’s state_dict is a best practice when using torch.save. If loading an old
checkpoint that contains an nn.Module, we recommend weights_only=False. When loading a checkpoint that contains
tensor subclasses, there will likely be functions/classes that need to be allowlisted, see below for further details.
If the weights_only Unpickler encounters a function or class that is not allowlisted
by default within the pickle file, you should see an actionable error like such
_pickle.UnpicklingError:Weights only load failed.This file can still be loaded,
to do so you have two options, do those steps only if you trust the source of the checkpoint
Registers callables for tagging and deserializing storage objects with an associated priority.
Tagging associates a device with a storage object at save time while deserializing moves a
storage object to an appropriate device at load time. tagger and deserializer
are run in the order given by their priority until a tagger/deserializer returns a
value that is not None.
To override the deserialization behavior for a device in the global registry, one can register a
tagger with a higher priority than the existing tagger.
This function can also be used to register a tagger and deserializer for new devices.
Parameters:
priority (int) – Indicates the priority associated with the tagger and deserializer, where a lower
value indicates higher priority.
tagger (Callable[[Storage | TypedStorage | UntypedStorage], str | None]) – Callable that takes in a storage object and returns its tagged device as a string
or None.
deserializer (Callable[[Storage) – Callable that takes in storage object and a device string and returns a storage
object on the appropriate device or None.
Marks the given globals as safe for weights_only load. For example, functions
added to this list can be called during unpickling, classes could be instantiated
and have state set.
Each item in the list can either be a function/class or a tuple of the form
(function/class, string) where string is the full path of the function/class.
Within the serialized format, each function is identified with its full
path as {__module__}.{__qualname__}. When calling this API, you can provide this
full path that should match the one in the checkpoint otherwise the default
{fn.__module__}.{fn.__qualname__} will be used.
Parameters:
safe_globals (List[Union[Callable, ) – list of globals to mark as safe
torch.serialization.clear_safe_globals()
Clears the list of globals that are safe for weights_only load.
torch.serialization.get_safe_globals()
Returns the list of user-added globals that are safe for weights_only load.
Returns a list of strings of functions/classes in a torch.save object that are not safe for weights_only.
For a given function or class f, the corresponding string will be of the form
{f.__module__}.{f.__name__}.
This function will return any GLOBALs in the checkpoint that are not in the set marked safe
for weights_only (either via add_safe_globals() or context or
allowlisted by by default).
Context-manager that skips writing/reading storage bytes for torch.save / torch.load calls.
For the save path, storages will still be saved, but the space that their bytes would usually be written to
will be empty space. The storage bytes can then be populated in a separate pass.
For the load path, tensors will be loaded per the checkpoint but their storages will not be populated with data.
Config
torch.utils.serialization.config provides a global config that can control the behavior of
torch.save and torch.load.
torch.utils.serialization.config.save contains options that control the behavior of torch.save.
compute_crc32: whether to compute and write the zip file checksum (Default : True).
See set_crc32_options().
use_pinned_memory_for_d2h: for storages that are on an accelerator when passed to torch.save, whether to
move storage to pinned memory or pageable memory on CPU within torch.save. (Default: False (i.e. pageable))
storage_alignment: alignment of storages in the checkpoint during torch.save in bytes. (Default 64)
torch.utils.serialization.config.load contains options that control the behavior of torch.load.
mmap: See the documentation for mmap argument in torch.load().
This config will set the behavior of mmap for torch.load if it is not
already explicitly passed to the torch.load call (Default : False).
WeightsUnpickler error: Can only build Tensor, Parameter, OrderedDict or types allowlisted via `add_safe_globals`,
but got <class 'numpy.dtype[float32]'>
This can be allowlisted via {add_}safe_globals([type(np.dtype(np.float32))]).
In numpy>=1.25 you would see
WeightsUnpickler error: Can only build Tensor, Parameter, OrderedDict or types allowlisted via `add_safe_globals`,
but got <class 'numpy.dtypes.Float32DType'>
This can be allowlisted via {add_}safe_globals([np.dtypes.Float32DType]).
Environment Variables
There are two environment variables that will influence the behavior of torch.load. These can be helpful
if one does not have access to the torch.load callsites.
TORCH_FORCE_WEIGHTS_ONLY_LOAD=1 will override all torch.load callsites to use weights_only=True.
TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1 will make torch.load callsites use weights_only=Falseonly
if weights_only was not passed as an argument.
>>> importtempfile>>> classMyTensor(torch.Tensor):... pass>>> t=MyTensor(torch.randn(2,3))>>> withtempfile.NamedTemporaryFile()asf:... torch.save(t,f.name)# Running `torch.load(f.name, weights_only=True)` will fail with# Unsupported global: GLOBAL __main__.MyTensor was not an allowed global by default.# Check the code and make sure MyTensor is safe to be used when loaded from an arbitrary checkpoint.... torch.serialization.add_safe_globals([MyTensor])... torch.load(f.name, weights_only=True)# MyTensor([[-0.5024, -1.8152, -0.5455],# [-0.8234, 2.0500, -0.3657]])
safe_globals
torch
Parameters:
f (str | PathLike[str] | IO[bytes]) – File-like object or string containing the checkpoint object saved via torch.save
Returns:
A list of strings of pickle GLOBALs in the checkpoint that are not allowlisted for weights_only.
>>> importtempfile>>> classMyTensor(torch.Tensor):... pass>>> t=MyTensor(torch.randn(2,3))>>> withtempfile.NamedTemporaryFile()asf:... torch.save(t,f.name)# Running `torch.load(f.name, weights_only=True)` will fail with# Unsupported global: GLOBAL __main__.MyTensor was not an allowed global by default.# Check the code and make sure MyTensor is safe to be used when loaded from an arbitrary checkpoint.... with torch.serialization.safe_globals([MyTensor]):... torch.load(f.name, weights_only=True)# MyTensor([[-0.5024, -1.8152, -0.5455],# [-0.8234, 2.0500, -0.3657]])>>> asserttorch.serialization.get_safe_globals()==[]
skip_data
Parameters:
materialize_fake_tensors (bool) – Whether to materialize FakeTensors during save. This is a no-op for the load path.
calculate_storage_offsets: If this config is set to True, offsets for storages will be
calculated rather than read via random reads when using torch.load(mmap=True). This minimizes
random reads, which can be helpful when the file is being loaded over a network. (Default : False)