Sub topic 7
Inside a PyTorch checkpoint
This chapter assumes you know the pickle opcode model from the earlier chapters, including GLOBAL, REDUCE and pickletools.dis. You should also be comfortable with nn.Module, state_dict() and torch.save. Here you will open a .pt or .pth file and see where pickle sits inside it. That tells you which part of the file is dangerous.
A checkpoint is a zip archive
A file written by torch.save is not one big pickle. Since PyTorch 1.6 the default is a zip archive, which PyTorch calls the "zipfile serialization". The archive holds the following entries:
| Entry (under a top-level folder named after the file) | Contents |
|---|---|
| `data.pkl` | A pickle describing the Python object structure: dict keys, tensor metadata, and references to storages |
| `data/0`, `data/1`, ... | Raw bytes of each tensor storage, one record per storage |
| `version` | The serialization format version |
| `byteorder` | `little` or `big`, recorded by newer releases |
| `.data/serialization_id` | An identifier added by newer releases |
The exact set of small metadata entries varies by PyTorch version. The split between data.pkl and the numbered storage records is stable.
This design keeps large numeric buffers out of the pickle stream. A pickle is slow and wasteful for gigabytes of floats, while a raw record can be read directly or memory-mapped.
Listing the archive and disassembling the pickle
The next script writes a tiny checkpoint, lists the archive entries, and disassembles data.pkl. pickletools.dis reads opcodes and never executes them, so it is safe to run on a file you do not trust.
import pickletools
import zipfile
import torch
torch.save({"weight": torch.zeros(2, 2), "bias": torch.zeros(2)}, "tiny.pth")
with zipfile.ZipFile("tiny.pth") as z:
for info in z.infolist():
print(info.filename, info.file_size)
pkl_name = next(n for n in z.namelist() if n.endswith("data.pkl"))
pickletools.dis(z.read(pkl_name))The listing shows data.pkl, one data/N record per tensor, and the metadata entries. In the disassembly you will see two kinds of import.
GLOBAL 'torch._utils _rebuild_tensor_v2'names the function that rebuilds a tensor from a storage, an offset, a shape and strides.GLOBAL 'torch FloatStorage'names the storage type. In recent releases this is a typed-storage class, but the idea is the same.
Each tensor is stored as a call to _rebuild_tensor_v2. The storage argument is not inline data. It is a persistent id, a tuple such as ('storage', torch.FloatStorage, '0', 'cpu', 4). The BINPERSID opcode tells the unpickler to ask persistent_load for the object. During torch.load, PyTorch's persistent_load reads the matching data/0 record and returns a storage.
That mechanism explains two behaviors:
- Views share storage. If two tensors are views of the same storage, the storage is written once and both tensors reference the same key. Saving a slice of a large tensor can write the whole parent buffer.
- Tied weights stay tied. Shared parameters, such as an embedding matrix reused as an output projection, point at one storage and remain shared after loading.
What gets pickled depends on what you pass to `torch.save`
torch.save(obj, path) pickles whatever obj is. In practice, three shapes of checkpoint appear.
- A
state_dict. This is anOrderedDictmapping names to tensors. The pickle referencescollections.OrderedDictand the tensor rebuild functions. It does not need your model code to load. - A training checkpoint. This is a dict holding
model,optimizer,epoch,schedulerand so on. Optimizer state adds more containers and tensors, and sometimes custom types. - A whole model, as in
torch.save(model, path). Pickle stores each class by reference, as module path plus class name. The file contains no class source code. Loading importsmypackage.models.Netand rebuilds the object by setting its__dict__. This breaks if you rename or move the module. It also means the load imports arbitrary module paths named in the file.
import torch
from torch import nn
model = nn.Linear(4, 2)
# Preferred: weights only, no class references
torch.save(model.state_dict(), "linear_state.pth")
# Fragile and riskier: pickles the class by reference
torch.save(model, "linear_full.pth")Prefer the state_dict form for sharing. It carries only names and tensors, and the loading code decides which architecture receives them.
Listing what a checkpoint will import
Before loading an unknown checkpoint, list every global its pickle references. Protocol 2, which torch.save uses by default, encodes imports with the GLOBAL opcode. Protocols 4 and later use STACK_GLOBAL, whose module and name are built from earlier stack values. A simple scan cannot resolve those, so the script flags them for manual review.
import pickletools
import zipfile
def list_globals(path):
found = set()
with zipfile.ZipFile(path) as z:
pkl_names = [n for n in z.namelist() if n.endswith("data.pkl")]
for name in pkl_names:
for opcode, arg, _pos in pickletools.genops(z.read(name)):
if opcode.name == "GLOBAL":
found.add(arg.replace(" ", "."))
elif opcode.name == "STACK_GLOBAL":
found.add("<STACK_GLOBAL: review manually>")
return sorted(found)
for g in list_globals("tiny.pth"):
print(g)For a plain tensor dict, expect only torch._utils._rebuild_tensor_v2 and a storage class. For a state_dict from a module, expect collections.OrderedDict as well. Anything else needs an explanation. Names such as os.system, builtins.eval, subprocess.Popen or posix.system in a model file are red flags.
A scan is a screening step and does not prove a file is safe. A hostile file can use opcodes your scanner does not model, or can reach dangerous behavior through a callable that looks innocent. The reliable control is to refuse to import anything outside a small allowlist, which the next chapters cover.
Older and neighboring formats
- Legacy format. Before 1.6,
torch.savewrote a sequence of separate pickles (a magic number, a protocol version, system info, the object, then storage keys) followed by raw storage data. It is not a zip.torch.loadstill reads it. Treat it as pickle from the first byte, because the object itself is a pickle stream. _use_new_zipfile_serialization=False. Passing this totorch.savewrites the legacy format. You may meet it in code written for old PyTorch versions.- TorchScript archives.
torch.jit.savealso writes a zip, but the contents differ. It holds serialized code and aconstants.pkl, so it is still a pickle-bearing container. mmap=True. For zipfile checkpoints,torch.load(path, mmap=True)maps storage records into memory instead of copying them. This helps with large checkpoints, but it does not change the security properties ofdata.pkl.
Recent PyTorch releases changed the default of torch.load so that weights_only is True (from version 2.6). Older versions defaulted to False, and a lot of existing tutorial code still passes nothing. Do not rely on the default. Pass weights_only=True explicitly, and check your installed version before assuming it behaves as described.
Failure modes and gotchas
- Several
data.pklentries. A normal checkpoint has one. A crafted archive may contain more than one, or entries whose names differ in subtle ways. Two tools can then disagree about which entry is "the" pickle. Scan every entry that ends indata.pkl, as the script above does. - Scanner and loader mismatch. A scanner that parses the zip one way while the loader parses it another way can miss a payload. Prefer running the real restricted loader over trusting a separate scanner.
- Whole-model pickles break across versions. Loading
torch.save(model)output requires the original module path to be importable. Renaming a package breaks old files, and adding a package tosys.pathjust to load a file widens what the file can import. - Big files from the hub. A checkpoint named
pytorch_model.binis usually this same zip format despite the.binextension. Extensions tell you nothing about format, so check the first bytes. A zip begins withPK.
Exercise
You download model.bin from an unknown source. Without calling torch.load, how can you check whether it is a zipfile checkpoint and see which Python globals its pickle would import? Name the two standard-library modules and one limitation of the result.
Show answer
Use zipfile to confirm it is a zip archive (zipfile.is_zipfile, or read the first bytes and look for PK) and to read the data.pkl entry. Use pickletools.genops or pickletools.dis on those bytes to list the GLOBAL and STACK_GLOBAL opcodes. None of these calls executes the pickle. One limitation is that STACK_GLOBAL imports are built from stack values, so a simple scan cannot always resolve them. A scan also does not prove safety, and a legacy-format file is not a zip and needs different handling.