PyTorch documents how to use torch.save but not the bytes; this page
describes what PyTorch’s own code writes and reads:
torch/serialization.py,
the ZIP writer in caffe2/serialize/inline_container.cc and
.h, versions.h and torch/_utils.py, all read
2026-11-12. Loading a .pt file runs a
pickle; PyTorch 2.6 changed the default of
torch.load’s weights_only argument from
False to True, and its own warning says that loading with
False can result in arbitrary code execution.
ZIP entries
Since PyTorch 1.6 the file is a ZIP archive (always written as ZIP64) with stored (uncompressed) entries, all inside one folder, the archive name:
| Entry | Holds |
|---|---|
data.pkl | The saved object, pickled with protocol 2, tensors replaced by persistent IDs. |
data/0, data/1… | The raw bytes of each storage, named by its key. |
version or .data/version | Text: the archive format version as a decimal number and a line feed. The writer starts at 3; it uses .data/version instead when the version is 6 or more. |
byteorder | Text: little or big. When it is missing, the reader falls back to a configurable byte order, native by default. |
.format_version | 1: storages are ordered numerically by key. |
.storage_alignment | The storage alignment used. |
.data/serialization_id | An ID the reader records with the file name. |
Every entry’s data starts at an offset aligned to 64 bytes by default (the Python
setting storage_alignment); the padding goes in the ZIP local header’s
extra field under the key FB, so the data can be memory-mapped.
Tensors in data.pkl
- A tensor is pickled as a call to
torch._utils._rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata=None). - The storage is a persistent ID, a tuple
('storage', storage_type, key, location, numel): the storage type (atorchattribute such as a typed storage class), the key namingdata/key, the location tag of its device, and its size: elements for a typed storage, bytes for an untyped one. - Several tensors can share one storage at different offsets and strides; saving two views of the same data as different types is an error.
- Parameters are rebuilt through
torch._utils._rebuild_parameter(or_rebuild_parameter_with_state).
The rebuild functions
A tensor's pickle is a call of one of these functions in torch._utils
(torch/_tensor.py _reduce_ex_internal chooses, in this order,
PyTorch main read 2026-11-13). A tensor of a Python subclass or with Python state is
wrapped as torch._tensor._rebuild_from_type_v2(func, type, args, state).
| Tensor kind | Function and arguments |
|---|---|
| Device without storage access (xla, maia, mtia, or a private-use backend with no storage) | _rebuild_device_tensor_from_cpu_tensor(data, dtype, device, requires_grad): the data is the tensor copied to the CPU, moved back to device (through _get_restore_location). The old _rebuild_xla_tensor and _rebuild_device_tensor_from_numpy (NumPy array data) are kept for old files. |
| Meta device | _rebuild_meta_tensor_no_storage(dtype, size, stride, requires_grad): no storage, so storage sharing is not kept. |
| Quantised | _rebuild_qtensor(storage, storage_offset, size, stride, quantizer_params, requires_grad, backward_hooks). quantizer_params is (torch.per_tensor_affine, scale, zero_point), or (qscheme, scales, zero_points, axis) for the per-channel schemes (per_channel_affine and per_channel_affine_float_qparams; the writer stores per-channel tensors with the first). The reader checks 0 ≤ axis < len(size) and that scales and zero points have size[axis] entries; per-channel affine scales are doubles and zero points longs, the float-qparams scheme floats for both. Other schemes are rejected on both sides. |
| Sparse COO | _rebuild_sparse_tensor(layout, (indices, values, size, is_coalesced)); a 3-tuple without is_coalesced is accepted for old files. Built without checking, then validated in bulk (always when weights_only is true). |
| Sparse CSR, CSC, BSR, BSC | _rebuild_sparse_tensor(layout, (compressed_indices, plain_indices, values, size)); the compressed indices are crow_indices for CSR and BSR and ccol_indices for CSC and BSC, the plain indices col_indices and row_indices. |
| Nested | _rebuild_nested_tensor(buffer, sizes, strides, storage_offsets) with the tensor's values() as the buffer. |
| Wrapper subclass without data, or fake tensors | _rebuild_wrapper_subclass(cls, dtype, size, stride, storage_offset, layout, device, requires_grad). |
| Ordinary dtypes | _rebuild_tensor_v2(storage, storage_offset, size, stride, requires_grad, backward_hooks, metadata=None) with a typed storage. metadata is a dict of whether the conj and neg bits are set. |
| The newer dtypes | _rebuild_tensor_v3(storage, storage_offset, size, stride, requires_grad, backward_hooks, dtype, metadata=None) with an untyped storage and the dtype explicit. The dtypes are float8_e5m2, float8_e4m3fn, float8_e5m2fnuz, float8_e4m3fnuz, float8_e8m0fnu, float8_e5m3fnu, float4_e2m1fn_x2, bits8, bits16, bits1x8, bits2x4, bits4x2, complex32, bcomplex32, uint16, uint32, uint64. |
| Old | _rebuild_tensor(storage, storage_offset, size, stride), the base of v2. |
| Parameters | _rebuild_parameter(data, requires_grad, backward_hooks); _rebuild_parameter_with_state(data, requires_grad, backward_hooks, state) also restores Python attributes (state is a dict, or a 2-tuple of dict and slots). |
Storage types
The storage entry of the persistent ID names a class of torch for the
legacy typed storages. torch/storage.py maps dtypes to these class names and
says this map must no longer grow (it is kept for compatibility); newer dtypes travel as an
untyped storage plus an explicit dtype in _rebuild_tensor_v3.
double DoubleStorage, float FloatStorage, half HalfStorage,
long LongStorage, int IntStorage, int16 ShortStorage,
int8 CharStorage, uint8 ByteStorage, bool BoolStorage,
bfloat16 BFloat16Storage, cdouble ComplexDoubleStorage, cfloat
ComplexFloatStorage, qint8 QInt8Storage, qint32 QInt32Storage,
quint8 QUInt8Storage, quint4x2 QUInt4x2Storage, quint2x4
QUInt2x4Storage.
TorchScript archives
TorchScript models (torch.jit.save) use the same ZIP container. The entries
below are what ScriptModuleSerializer::serialize in
torch/csrc/jit/serialization/export_module.cpp writes (PyTorch main, read
2026-11-13); each archive is a pickle named name.pkl with its
tensors next to it.
| Entry | Holds |
|---|---|
extra/name | Extra files the caller passed to save, and files an extra-files hook returns (a hook file whose name is already given is skipped with a warning). |
data.pkl, data/0, data/1… | The module object (its attributes) as an archive named data; the tensors are numbered in the order the pickler meets them. A meta tensor or a skipped-data save writes the record with no bytes. |
code/… | The serialised TorchScript source of the module's classes and methods (writeFiles("code/")). |
constants.pkl, constants/… | A tuple of the code's constant table, written as a separate archive so loading code does not depend on loading data. In a bytecode save the constants use the storage-context naming below. |
bytecode.pkl | Written only with the bytecode (mobile) format, after the constants; its archive is named bytecode. With mobile debug info a mobile_debug_handles archive is written too. |
traced_inputs.pkl | Written when the module has recorded traced inputs; its tensor records are empty (data skipped). |
.data/ts_code/… | The prefix the importer uses for code when a TorchScript module is stored inside a torch.package archive (the plain prefix is code/). |
With the storage context (bytecode saves), a tensor's key is the number a shared
storage table gives it plus .storage, for example 140245072983168.storage
(bytecode version 5 note in versions.h); otherwise the key is its index.
Archive version numbers
From caffe2/serialize/versions.h (PyTorch main, read 2026-11-13). The file
says the produced version describes how an archive is to be read, and that the version
written is at least the produced version but can be higher when a TorchScript module uses
an operator with a dynamic version (torch.save ignores dynamic
versions).
- Supported range: 1 (
kMinSupportedFileFormatVersion) to 10 (kMaxSupportedFileFormatVersion). Produced: 10 (kProducedFileFormatVersion); the minimum written is 3 (kMinProducedFileFormatVersion). - Reasons for each number (the file's own list): 1 initial; 2 removed op_version_set numbers; 3 type tags added to the pickle of container types; 4 (dynamic) stopped integer division with
torch.div; 5 (dynamic)torch.fullstopped inferring a float dtype from bool or integer fill values; 6 the version string moved to.data/versionfromversion(also used bytorch.package); 7 a new upgrader design, set on 15 December 2021 when the produced version was raised from 3 to 7; 8aten::linspaceerrors when steps is not given (24 January 2022); 9 the same foraten::logspace(30 January 2022); 10aten::gelugains theapproximateargument (11 February 2022). - Bytecode versions (
kProducedBytecodeVersionis 8, supported 4 to 9): 1 initial; 2 and 3 comments missing in the source; 4 schema added to the function tuple, forward compatible; 5 bytecode shares constant tensor files with TorchScript and the tensor storage root key changed from the index to the storage pointer value plus.storage; 6 implicit operator versioning by the number of specified arguments; 7 operators with default arguments plus out arguments; 8 promoted operators emitted as instructions; 9 serialisation format changed from pickle to flatbuffer, with v8 pickle and v9 flatbuffer being the same content.
Legacy format
Before 1.6 (and with _use_new_zipfile_serialization=False), the file
is several pickles one after another:
- The magic number
0x1950A86A20F9469CFC6C, pickled as an integer. - The protocol version, 1001.
- A dictionary of system information: the protocol version, whether the machine is little-endian, and the sizes of short, int and long.
- The object, with storages as persistent IDs
('storage', type, key, location, numel, view_metadata). - The sorted list of the storage keys.
- Then each storage’s data, written by the storage’s own
_write_file.
The persistent ID of a storage in this format is ('storage', storage_type, root_key,
location, numel, view_metadata); view_metadata is
None or (view_key, offset, view_size), a window (in elements) onto the
root storage. Sizes in bytes are elements times the dtype's element size. A pickled
('module', container, source_file, source) entry holds a module's source, which
the loader compares with the current source and warns if it changed (a
SourceChangeWarning). The magic number must equal MAGIC_NUMBER
and the protocol version PROTOCOL_VERSION, else the loader reports an invalid magic number or protocol
version. Storage data is read in the order of the key list.
torch.load also still reads an older tar
layout (PAX format, tried only when the file offset is 0 and the file has a file number;
weights_only=True refuses it). Its members, from _legacy_load
in torch/serialization.py (read 2026-11-13):
storages: a pickled count; then for each storage a pickled tuple(key, location, storage_type)followed immediately by that storage's raw data (read byUntypedStorage._new_with_filewith the dtype's element size); finally a pickled list of(target_cdata, root_cdata, offset, numel)views, each a slice of an earlier storage.tensors: a pickled count; then for each tensor a pickled(key, storage_id, original_tensor_type)followed by binary fields:ndimas a little-endian int32, 4 skipped bytes (the old encoding treated it as 8 bytes),ndimsizes andndimstrides as little-endian int64, then the storage offset as int64.pickle: the pickled object, in which persistent IDs are either a tuple (a module's container and source, returned as the first element) or an integer key of a storage or tensor above.