Containers · .pt

PyTorch torch.save checkpoint (.pt / .pth / .bin / .ckpt)

torch.save writes an uncompressed ZIP (PyTorch's own writer, "inline_container") with one top-level folder holding a pickle of the user's object (data.pkl) and one record per storage (data/<key>), each aligned to the file's storage alignment (default 64 bytes). Tensors in the pickle are reduce-calls to torch._utils._rebuild_tensor_v2/v3 whose storage argument is a persistent id resolved to a data/ record. Because the container is pickle, loading can run arbitrary code unless restricted to an allowlist (weights_only=True, default since torch 2.6). HF "pytorch_model.bin" is this format; sharding uses pytorch_model.bin.index.json (same schema as the safetensors index).

.pt .pth .bin .ckpt

What it is
many tensors
Byte order
file declared
Dimension order
row major
Compression
none
Metadata
pickle
Loading
executes code on load

How to read it

Uncompressed ZIP. Record order: data.pkl, .format_version, .storage_alignment, byteorder, data/0..data/n, version, .data/serialization_id, then the central directory.

<archive>/data.pklpickle protocol 2the saved object
<archive>/.format_versionascii
<archive>/.storage_alignmentasciidecimal text of config.save.storage_alignment; absent on load means 64
<archive>/byteorderascii'little' or 'big'
<archive>/data/<key>bytesraw storage bytes, key = persistent id key ('0','1',...)
<archive>/versionascii'3\n' for current writers
<archive>/.data/serialization_idasciirandom id string

One tensor

namepath of the tensor in the unpickled object (state_dict key)
dtypestorage_type (v2) or explicit dtype (v3)
shapesize tuple
stridesstride tuple (elements)
data_offsetzip data offset of data/<key> + storage_offset * itemsize
nbytescontiguous: prod(size)*itemsize; otherwise gather using strides
alignment64. start of every ZIP record's data (local header extra field 'FB' padding). yes: torch.utils.serialization.config.save.storage_alignment (default 64). The writer stores that value in .storage_alignment; the loader reads it and falls back to 64 when the record is absent

PersistentId

('storage', storage_type, key:str, location:str e.g. 'cpu'/'cuda:0', numel:int). numel counts elements of storage_type; for torch.storage.UntypedStorage it counts BYTES.

RebuildTensorV2

torch._utils._rebuild_tensor_v2(storage, storage_offset, size:tuple, stride:tuple, requires_grad:bool, backward_hooks:OrderedDict[, metadata]); offset and stride are in ELEMENTS. Used when the dtype has a legacy typed storage class. metadata is present only for a conj or neg bit (PT-010).

RebuildTensorV3

torch._utils._rebuild_tensor_v3(storage:UntypedStorage, storage_offset, size, stride, requires_grad, backward_hooks, dtype:torch.<dtype>[, metadata]). Used for dtypes in torch.storage._new_dtypes() (float8_*, uint16/32/64, float4_e2m1fn_x2, bits*, complex32, ...); offset and stride are in elements of dtype. metadata is present only for a conj or neg bit (PT-010); float8 tensors saved normally have none (small-pt-fp8.pt).

OtherRebuilds

Also allowlisted (weights_only): torch._utils._rebuild_parameter(data, requires_grad, backward_hooks), _rebuild_parameter_with_state, _rebuild_qtensor (quantized; qscheme + scale/zero_point), _rebuild_tensor, _rebuild_tensor_v2, _rebuild_tensor_v3, _rebuild_sparse_tensor, _rebuild_wrapper_subclass, _rebuild_device_tensor_from_numpy, _rebuild_device_tensor_from_cpu_tensor, _rebuild_meta_tensor_no_storage, torch._tensor._rebuild_from_type_v2 (tensor subclasses), plus collections.OrderedDict, collections.Counter, torch.Size, torch.Tensor, torch.device, torch.nn.parameter.Parameter, torch.serialization._get_layout, builtins set/complex/bytearray, _codecs.encode, and dtype objects.

Reader

The procedure that finds each tensor's bytes.

read

pseudo-python
def read_torch_zip(path):
    z = ZipFile(path)
    pkl = [n for n in z.namelist() if n.endswith("/data.pkl")]
    if len(pkl) != 1: raise Invalid("no data.pkl")
    P = pkl[0][:-len("data.pkl")]                    # '<archive>/'
    order = z.read(P + "byteorder").decode() if P + "byteorder" in z.namelist() else "little"
    storages = {}
    def persistent_load(pid):                         # ('storage', stype, key, location, numel)
        _, stype, key, loc, numel = pid
        if key not in storages:
            info = z.getinfo(P + "data/" + key)
            storages[key] = Storage(stype, zip_member_bytes_or_mmap(z, info))   # STORED -> mmap
        return storages[key]
    def find_class(module, name):                    # restricted unpickler (PT-002)
        q = module + "." + name
        if q in ALLOWED: return ALLOWED[q]          # rebuild fns -> functions building TensorRef
        raise Invalid("disallowed global " + q)
    obj = RestrictedUnpickler(z.open(P + "data.pkl"), find_class, persistent_load).load()
    return flatten_tensors(obj, byteorder=order)     # dict path -> TensorRef

# _rebuild_tensor_v2(storage, off, size, stride, ...) -> TensorRef(storage.bytes, dtype=STYPE[storage.stype], off, size, stride)
# _rebuild_tensor_v3(storage, off, size, stride, rg, hooks, dtype, ...) -> TensorRef(storage.bytes, dtype=TORCH_DTYPE[dtype], ...)
# TensorRef -> canonical: if stride == c_strides(size): bytes[off*isz : (off+prod(size))*isz] else strided gather
# optional last argument {'conj': True} / {'neg': True}: negate imaginary parts / every element (PT-010)

Number formats

The name in the file, and the canonical dtype it maps to.

In the fileCodeCanonicalBits
float32FloatStoragefloat3232
float64DoubleStoragefloat6464
float16HalfStoragefloat1616
bfloat16BFloat16Storagebfloat1616
int64LongStorageint6464
int32IntStorageint3232
int16ShortStorageint1616
int8CharStorageint88
uint8ByteStorageuint88
boolBoolStoragebool8
complex64ComplexFloatStoragecomplex6464
complex128ComplexDoubleStoragecomplex128128
float8_e4m3fnUntypedStorage + torch.float8_e4m3fnfloat8_e4m3fn8
float8_e5m2UntypedStorage + torch.float8_e5m2float8_e5m28
float8_e4m3fnuzUntypedStorage + torch.float8_e4m3fnuzfloat8_e4m3fnuz8
float8_e5m2fnuzUntypedStorage + torch.float8_e5m2fnuzfloat8_e5m2fnuz8
float8_e8m0fnuUntypedStorage + torch.float8_e8m0fnufloat8_e8m0fnu8
float4_e2m1fn_x2UntypedStorage + torch.float4_e2m1fn_x2float4_e2m1fn4
uint16UntypedStorage + torch.uint16uint1616
uint32UntypedStorage + torch.uint32uint3232
uint64UntypedStorage + torch.uint64uint6464
quantizedQInt8Storage/QUInt8Storage/QInt32Storage/QUInt4x2Storage/QUInt2x4Storagenone—

Reject the file when

Listed in the spec's order. Only rules marked MUST that reject the file are shown. The other IDs are warnings or implementation limits. A rule marked suggestion is the spec project's own decision where no official document decides. It is not the format's official behaviour.

RuleMust holdError
PT-001

zip contains exactly one '<prefix>/data.pkl'; every other record shares <prefix>. <prefix> is a non-empty top-level folder: a root-level data.pkl is rejected.

PT-002

untrusted files are unpickled with an allowlist (no GLOBAL outside OtherRebuilds/RebuildTensor*/storage types/dtypes)

PT-003

each persistent id key has a data/<key> record of at least numel*itemsize bytes

PT-004Suggestion SUG-013

storage_offset + sum((size_i-1)*stride_i) < storage numel for non-empty tensors

PT-007

A restricted unpickler for torch.save checkpoints handles exactly the opcodes _weights_only_unpickler.py (04df708bcc03) handles, and rejects every other opcode. Object building: GLOBAL, NEWOBJ, REDUCE, BUILD. Containers: EMPTY_TUPLE, TUPLE, TUPLE1, TUPLE2, TUPLE3, EMPTY_LIST, APPEND, APPENDS, EMPTY_DICT, SETITEM, SETITEMS, EMPTY_SET, MARK. Constants: NONE, NEWFALSE, NEWTRUE, BININT, BININT1, BININT2, LONG1, BINFLOAT, BINUNICODE, SHORT_BINSTRING. Memo: BINGET, LONG_BINGET, BINPUT, LONG_BINPUT. Storage: BINPERSID (only persistent ids whose first item is 'storage'). Framing: PROTO, STOP. BUILD is needed for a normal state_dict: the OrderedDict carries _metadata through BUILD, and the reference applies BUILD to an OrderedDict as __dict__.update(state). LONG1 appears for any int >= 2^31, for example a storage numel (bytes, for UntypedStorage) of 2 GiB or more. BINFLOAT appears for float values outside tensors.

PT-008

Reader. A data/ record starts at local header offset + 30 + filename length + extra length, read from that record's local header. PyTorchStreamReader::getRecordOffset (inline_container.cc at f164555cf648) computes exactly that and does not look at the extra field's header id or contents. The 'FB' id (0x4246) is what torch's writer uses (detail::getPadding); any extra field, or none, loads. Alignment is a writer SHOULD (64, or the .storage_alignment record) for mmap speed. A reader must not assume it: an unaligned data/ record is valid and torch.load reads it, with mmap on and off. Checked with tools/check_pytorch_zip_alignment.py: Python zipfile archives with no extra field, and with 64-byte alignment through header id 0xCAFE, load correctly under the default settings.

PT-010

Reader. The optional last argument of _rebuild_tensor_v2 / _rebuild_tensor_v3 is the dict from torch._utils.get_tensor_metadata, which carries only the conj and neg bits. Tensor.__reduce_ex__ appends it only when it is not empty. {'conj': True} means the stored bytes are the un-conjugated values: negate every imaginary part. {'neg': True} means negate every element, as torch's neg does it: flip the sign bit of float16, bfloat16, float32, float64, and both parts of complex32/64/128 (0 becomes -0, a NaN's sign flips). For int8, int16, int32, int64, and uint8, negate in two's complement with wraparound: int8 -128 stays -128, uint8 1 becomes 255. torch.save accepts the bit on every dtype through the private torch._neg_view, and torch.load sets it again. For bool, uint16, uint32, uint64, and every float8 type, torch then cannot resolve it ("neg_cpu" not implemented), so the tensor is unusable in torch too. A reader refuses those, and may refuse the integer cases. A reader never ignores the bit.

The only public way to get the bit is c.conj().imag on complex32, complex64, or complex128, which gives a float16, float32, or float64 view of a complex storage. torch.load applies both (weights_only=True accepts the dict). A reader that ignores them returns wrong values without an error.

Plain float8, uint16/32/64, and other v3 dtypes carry no metadata in normal saves, so a writer of canonical data never needs the argument: it writes resolved values (resolve_conj, resolve_neg) and leaves the dict out. Checked by tools/check_rewrite_rules.py (torch 2.15.0). Test file: small-pt-fp8.pt (c64_conj, imag_neg; f8e4m3 and f8e5m2 without metadata).

Example

Example file. torch.save (torch 2.14.1+cu130) wrote an uncompressed ZIP. This viewer reads the archive records and does not unpickle data.pkl. The specs record that a weights_only round trip matched w_f32, b_f16, e_bf16, i_i32, and s_f32.

small.pt3,587 bytes

byteorderlittle
.format_version1
.storage_alignment64
version3
memberssmall/data.pkl 477 bytes small/.format_version 1 bytes small/.storage_alignment 2 bytes small/byteorder 6 bytes small/data/0 1024 bytes small/data/1 16 bytes small/data/2 12 bytes small/data/3 24 bytes small/data/4 4 bytes small/version 2 bytes small/.data/serialization_id 40 bytes
serialization_id0055190185320359078712506378669613723131

Sources

Tensref rev 3.1