5.6 Saving, Loading, and Pretrained Weights
A trained neural network is surprisingly fragile: it exists only in the memory of the process that trained it. The moment that process terminates (whether because your script finished, hit an error, tripped over a server's power cord, or ran on a preemptible cloud instance), every learned weight vanishes unless saved to disk. For the toy models of earlier chapters, losing progress costs minutes. At modern scale, it can erase weeks of compute, and hardware failures are not rare exceptions: they are routine. Over a 54-day window of pre-training Llama 3 405B on up to 16,384 GPUs, Meta recorded 419 unexpected interruptions, roughly one every three hours (Grattafiori et al., 2024). Without reliable checkpointing and resumption, a run of that scale could never complete.
Saving weights serves a second, equally ubiquitous purpose: sharing trained models so others can run inference or fine-tune them without training from scratch (Section 20.2). Both workflows raise the same practical questions: what exactly belongs on disk, which file formats are safe to load, and how should we verify that weights match our architecture?
The answer to what to save follows directly from Section 5.2. A model consists of code plus state: the code defines the architecture and forward pass, while the state is the collection of named tensors (parameters and buffers alike) produced by training. We serialize only the state, mapping names to tensors, and reconstruct the model by instantiating the architecture in code and loading those tensors back in. Resuming an interrupted training run demands still more: besides model weights, we must save optimizer state (such as Adam's running moments), random-number generator states, the step counter, and the architecture configuration, making a training checkpoint several times larger than an inference weight file.
In this hands-on section, we first inspect and serialize model state, then
contrast unsafe pickle files with the safe safetensors format, build an atomic
training checkpoint capable of bit-for-bit resumption, and finish by loading
pretrained ResNet-50 weights into a modified architecture while verifying
missing and unexpected keys.
import json
import os
import struct
from collections import Counter
from dataclasses import asdict, dataclass
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torchvision.models import resnet50, ResNet50_Weights
from safetensors.torch import load_file, save_file5.6.1 Model State#
Because a model contains dozens or hundreds of tensors, saving it requires storing a mapping from names to tensors. Each framework generates this mapping automatically by traversing the module tree (Section 5.1), keying every tensor by its path from the root. Below we inspect the state of a simple single-hidden-layer MLP with 256 hidden units.
collect_params() and state_dict() map dotted paths (hidden.weight, output.bias) to parameters and buffers:
class MLP(nn.Module):
def __init__(self):
super().__init__()
self.hidden = nn.Linear(20, 256)
self.output = nn.Linear(256, 10)
def forward(self, x):
return self.output(F.relu(self.hidden(x)))
net = MLP()
X = torch.randn(2, 20)
Y = net(X)
{name: tuple(t.shape) for name, t in net.state_dict().items()}{'hidden.weight': (256, 20),
'hidden.bias': (256,),
'output.weight': (10, 256),
'output.bias': (10,)}
Notice that this state dictionary records names, shapes, and numerical values, and
nothing else. It contains no trace of the MLP class, its forward logic, or its
activation function. Restoring the model therefore requires Python code that
recreates the exact matching names and shapes: even renaming an attribute from
output to head breaks the mapping despite computing the identical function.
We show how to catch and diagnose such mismatches later in this section.
5.6.2 Pickle and safetensors#
When checkpoint files never leave your own disk, almost any serialization format suffices. The moment you download pretrained weights from a public hub or accept a checkpoint from someone else, however, a security question arises: can loading that file execute arbitrary code on your machine? Unfortunately, with Python's default serialization format, the answer is yes.
5.6.2.1 Code Execution on Load#
Python's built-in pickle module does not store passive data: it stores a
bytecode program that reconstructs Python objects, and unpickling executes
that program, allowing it to call any importable function. Any class can
customize what pickle executes via __reduce__, returning a callable and its
arguments. Our Tripwire example below benignly invokes print; a malicious
checkpoint could just as easily invoke os.system.
class Tripwire:
def __reduce__(self): # pickle calls print(...) to rebuild the object
return (print, ('*** payload executed while loading ***',))
torch.save writes a pickle archive; loading with weights_only=False (the default prior to PyTorch 2.6) executes the payload immediately:
torch.save(Tripwire(), 'tripwire.pt')
_ = torch.load('tripwire.pt', weights_only=False) # the payload runs here*** payload executed while loading ***
By default, the loaders reject arbitrary Python objects:
torch.load defaults to weights_only=True since PyTorch 2.6.
try:
torch.load('tripwire.pt') # weights_only=True, the default
except Exception as e:
print(type(e).__name__, str(e).split('.')[0])UnpicklingError Weights only load failed
Restricted unpicklers only protect you insofar as their allowlists have no bugs, and historical vulnerabilities have bypassed even hardened restricted loaders. A file format that simply cannot encode executable instructions eliminates the entire attack surface by design.
PyTorch's weights_only mode is such a restricted loader.
5.6.2.2 The safetensors Format#
The safetensors format stores strictly raw tensor data and metadata—never
code. Its binary layout has just three contiguous segments
(Figure 5.6.1): an 8-byte little-endian integer giving
the header length, a UTF-8 JSON header mapping each tensor name to its dtype,
shape, and byte offsets, and the raw tensor buffers packed back to back. Loading
executes zero code; the reader merely validates the JSON header and checks that
every byte range stays within the file. As an added systems bonus, knowing exact
byte offsets upfront enables memory-mapping (mmap) and random access to
individual tensors without reading the entire file. Framework-agnostic and fast,
safetensors has become the standard weight distribution format on the Hugging
Face Hub.
The safetensors file of the MLP below as one strip of bytes: an 8-byte length, the JSON header with each tensor's dtype, shape, and byte range, and the raw bytes of the four tensors back to back, in the order of their names. The offsets under the data are the ranges that the header records.
We save our MLP's state to mlp.safetensors, load it into a fresh clone, and
verify that both instances produce identical outputs.
save_file(net.state_dict(), 'mlp.safetensors')
clone = MLP()
clone.load_state_dict(load_file('mlp.safetensors'))
torch.equal(clone(X), Y)True
The round trip is bit-for-bit exact. Even better, because the header is plain JSON at a fixed offset, we can inspect the file's contents using nothing beyond Python's standard library:
with open('mlp.safetensors', 'rb') as f:
n = struct.unpack('<Q', f.read(8))[0] # header length, little-endian
header = json.loads(f.read(n))
print('header length:', n, 'bytes')
for name, entry in sorted(header.items(), key=lambda e: e[1]['data_offsets']):
print(f"{name:18s} {entry['dtype']} {str(entry['shape']):10s} "
f"bytes {entry['data_offsets']}")header length: 296 bytes
hidden.bias F32 [256] bytes [0, 1024]
hidden.weight F32 [256, 20] bytes [1024, 21504]
output.bias F32 [10] bytes [21504, 21544]
output.weight F32 [10, 256] bytes [21544, 31784]
Every byte interval equals the tensor's element count times 4 bytes (F32 =
float32): the 256-entry hidden bias occupies the first 1,024 bytes, the
-entry hidden weight occupies the next 20,480 bytes,
and each block begins immediately where the previous one ends—pure tensor data
with zero hidden code.
For private scratch checkpoints on your own machine, native framework formats are perfectly fine. Whenever weights cross a trust boundary—published to users or downloaded from the web—use a code-free format like safetensors paired with a cryptographic checksum so recipients can verify integrity.
5.6.3 Training Checkpoints#
A bare weights file suffices for inference, but not for resuming training. The reason is stateful optimization. Most modern deep learning runs use Adam (Section 9.5), which tracks two per-parameter running averages (Section 5.2): for the gradient and for its elementwise square , updating each parameter opposite its smoothed gradient scaled down where recent gradients have been large:
Here is the learning rate, is a small constant (typically ), division and square root act elementwise, and the hats indicate bias-correction factors compensating for zero initialization (derived in Section 9.5). Crucially, and encode the optimization history: discard them, and Adam behaves as if training had just started from scratch.
A truly resumable training checkpoint therefore packs five distinct components (Figure 5.6.2): (1) model state (parameters and buffers), (2) optimizer state ( and ), (3) random-number generator states so minibatch shuffling and dropout continue seamlessly, (4) the step counter governing Adam's bias correction and any learning-rate schedule, and (5) the model configuration needed to rebuild the architecture. Gradients are omitted because the next step recomputes them immediately. That leaves 12 of the 16 bytes per parameter held during fp32 Adam training (Section 5.2), namely weights plus two moments, so a resumable checkpoint for an 8-billion-parameter model weighs in at 96 GB: three times its 32 GB fp32 weights and six times its 16 GB bf16 inference file (Section 5.5).
A checkpoint file's five compartments, each paired by an arrow with what it restores on resume: model state with the weights, optimizer state with Adam's two running averages, RNG state with the data order and dropout, step with the position in the schedule, and config with the architecture.
Checkpointing must also be crash-safe: overwriting an existing checkpoint in
place risks losing both old and new versions if the job dies mid-write. Instead,
we write to a temporary file and atomically rename it over the destination once
finished, guaranteeing that any reader sees either the complete previous
checkpoint or the complete new one. The rename protects against a crash of the
process. Surviving a power loss also takes an os.fsync on the file and on its
directory, which the exercises work out.
We pack model state, optimizer state, step, asdict(cfg), and CPU/CUDA/torch.Generator RNG states into a pure-tensor/primitive dict compatible with weights_only=True, saving via a .tmp file and os.replace:
def save_checkpoint(path, model, optimizer, step, cfg=None, rng=None):
"""Atomically write a resumable training checkpoint."""
ckpt = {'model': model.state_dict(),
'optimizer': optimizer.state_dict(),
'step': step,
'cpu_rng': torch.get_rng_state()}
if cfg is not None:
ckpt['cfg'] = asdict(cfg)
if rng is not None: # a torch.Generator
ckpt['rng'] = rng.get_state()
if torch.cuda.is_available():
ckpt['cuda_rng'] = torch.cuda.get_rng_state_all()
tmp = path + '.tmp'
torch.save(ckpt, tmp)
os.replace(tmp, path)
def load_checkpoint(path, model, optimizer=None, rng=None):
"""Restore the state written by save_checkpoint; return the raw dict."""
ckpt = torch.load(path, weights_only=True)
model.load_state_dict(ckpt['model'])
if optimizer is not None:
optimizer.load_state_dict(ckpt['optimizer'])
if rng is not None:
rng.set_state(ckpt['rng'])
torch.set_rng_state(ckpt['cpu_rng'])
if torch.cuda.is_available() and 'cuda_rng' in ckpt:
torch.cuda.set_rng_state_all(ckpt['cuda_rng'])
return ckptTo test checkpoint resumption, we train a small 64-hidden-unit MLP regressor
with Adam () on 256 noisy linear examples in 20 dimensions, drawing
minibatches of 64 examples using a dedicated random generator seeded at 0 so
that minibatch ordering becomes part of the checkpointed state. As in
Section 5.1, a Config dataclass captures all
architectural and training hyperparameters so they travel directly inside the
checkpoint.
@dataclass
class Config:
num_inputs: int = 20
num_hiddens: int = 64
num_outputs: int = 1
batch_size: int = 64
lr: float = 0.05
We train for 200 steps, write a checkpoint, and immediately continue the same
run for 5 more steps to create our uninterrupted 205-step ground truth. Each
call to train records the minibatch loss before each update step.
def build(cfg):
net = nn.Sequential(nn.Linear(cfg.num_inputs, cfg.num_hiddens),
nn.ReLU(),
nn.Linear(cfg.num_hiddens, cfg.num_outputs))
for layer in (net[0], net[2]):
nn.init.xavier_uniform_(layer.weight)
nn.init.zeros_(layer.bias)
return net
cfg = Config()
data = torch.randn(256, cfg.num_inputs)
target = data @ torch.randn(cfg.num_inputs, 1) + 0.1 * torch.randn(256, 1)
loss = nn.MSELoss()
def train(model, opt, rng, num_steps):
losses = []
for _ in range(num_steps):
idx = torch.randint(len(data), (cfg.batch_size,), generator=rng)
opt.zero_grad()
l = loss(model(data[idx]), target[idx])
l.backward()
opt.step()
losses.append(l.detach())
return [l.item() for l in losses]
net = build(cfg)
opt = torch.optim.Adam(net.parameters(), lr=cfg.lr)
rng = torch.Generator().manual_seed(0) # draws the minibatches
train(net, opt, rng, 200)
path = 'run.pt'
save_checkpoint(path, net, opt, step=200, cfg=cfg, rng=rng)
uninterrupted = train(net, opt, rng, 5)Now we simulate restarting in a fresh process: resume rebuilds the model and optimizer from the saved config, optionally restores the optimizer and RNG states alongside the weights, and runs the remaining steps up to num_steps, while max_diff reports the largest elementwise weight discrepancy between two models:
def resume(path, num_steps, restore_optimizer=True, restore_rng=True):
cfg = Config(**torch.load(path, weights_only=True)['cfg']) # saved config
model = build(cfg)
opt = torch.optim.Adam(model.parameters(), lr=cfg.lr)
rng = torch.Generator().manual_seed(0) # seeded as at the start
ckpt = load_checkpoint(path, model, opt if restore_optimizer else None,
rng=rng if restore_rng else None)
return model, train(model, opt, rng, num_steps - ckpt['step'])
def max_diff(a, b):
return max((p - q).abs().max().item()
for p, q in zip(a.parameters(), b.parameters()))We compare restoring the full checkpoint against omitting only the random generator (restore_rng=False, as if a script simply re-seeded from 0) and measure the maximum weight discrepancy against the uninterrupted 205-step net:
for name, kwargs in (('full checkpoint', {}),
('without the generator', {'restore_rng': False})):
resumed, _ = resume(path, 205, **kwargs)
print(f'{name:22s} max |difference| {max_diff(resumed, net):.3g}')full checkpoint max |difference| 0
without the generator max |difference| 0.00397
Restoring the full checkpoint reproduces the uninterrupted weights with zero error (bit for bit). Omitting the RNG state causes the resumed loop to replay the very first minibatches instead of drawing the next ones, introducing weight differences of roughly 0.004 to 0.02 (note that bit-for-bit equality also assumes deterministic operations, which we examine in Section 5.8).
Dropping the optimizer state is far more destructive. Below we resume with the saved weights and RNG state intact, but with a freshly constructed Adam optimizer, and compare the five post-resume minibatch losses side by side:
_, full = resume(path, 205)
_, fresh = resume(path, 205, restore_optimizer=False)
print('saved optimizer:', [round(l, 4) for l in full])
print('fresh optimizer:', [round(l, 4) for l in fresh])saved optimizer: [0.0009, 0.0017, 0.0022, 0.001, 0.0019]
fresh optimizer: [0.0009, 2.1294, 0.6979, 0.7146, 0.9511]
With the saved optimizer state, training picks up smoothly with losses hovering near 0.01 or below. With a fresh Adam optimizer, a single step blows the loss up roughly a thousandfold, and even four steps later it remains over a hundred times higher than before.
Why does one step of a fresh Adam wreck a nearly converged model? Equation (5.6.1) tells the whole story. Starting from and , Adam's bias correction on step 1 divides out the exact initialization factor, leaving and . Every parameter with any nonzero gradient therefore steps by : the full learning rate, no matter how tiny its gradient. By contrast, the saved remembers the much larger squared gradients from earlier in training, keeping large relative to the tiny late-stage gradients so updates remain gentle. The closer a model is to convergence, the more violent an uninitialized Adam restart becomes. Weights alone are never enough to resume training.
5.6.4 Pretrained Weights#
We now turn to the second major use of saved state: initializing from weights trained by someone else. A backbone trained on ImageNet (1.2 million images across 1,000 categories) learns rich visual representations that transfer cleanly to new tasks. Adapting it to a 10-class problem is simple: load every layer except the final classifier head, and swap in a fresh 10-output linear layer. Below we demonstrate this with ResNet-50 (~25 million parameters, or 23.5 million excluding its 1,000-class head). We will study convolutional networks in Chapter 6 and Chapter 7; for weight loading, ResNet-50 is simply a state dictionary of a few hundred named tensors.
net = resnet50(weights=ResNet50_Weights.DEFAULT) # ~100 MB once
net.fc = nn.Linear(net.fc.in_features, 10) # new 10-class head
net.fcLinear(in_features=2048, out_features=10, bias=True)
External weight files rarely match a custom target model one-to-one, and silently ignoring mismatches is a notorious source of bugs. To see how a careful loader audits partial transfers, we strip two groups of tensors from our pretrained ResNet-50 state: the classification head (which we intend to replace) and the entire final stage of the backbone (simulating a corrupted or mismatched checkpoint). Loading the remaining tensors into a fresh 10-class ResNet-50 lets us inspect two diagnostic sets: missing keys (model parameters absent from the file, left randomly initialized) and unexpected keys (file entries unused by the model).
load_state_dict(..., strict=False) loads matching keys and returns (missing_keys, unexpected_keys) directly:
damaged = {k: v for k, v in net.state_dict().items()
if not k.startswith(('fc.', 'layer4.'))}
target = resnet50(weights=None)
target.fc = nn.Linear(target.fc.in_features, 10)
report = target.load_state_dict(damaged, strict=False)
print('missing by block:', dict(Counter(
k.split('.')[0] for k in report.missing_keys)))
print('unexpected:', report.unexpected_keys)missing by block: {'layer4': 50, 'fc': 2}
unexpected: []
Missing keys for the new 10-class head's weight and bias are expected, since that head starts from random initialization. The missing keys from the final backbone stage are a red flag: had we loaded blindly with partial matching, a huge chunk of our "pretrained" ResNet-50 would silently remain random noise. Here the unexpected set is empty; a nonempty unexpected set typically signals a renamed module whose weights were never loaded. In production code, always assert explicitly that the missing and unexpected sets match only the layers you intended to replace or drop, raising an error on anything else.
Once verified, transfer learning typically begins by freezing the pretrained backbone (Section 5.2.3.2) so initial updates train only the new head, before selectively unfreezing deeper layers (Section 20.2).
Everything in this chapter so far has lived in host CPU memory. In Section 5.7, we move both state and computation onto GPUs.
5.6.5 Summary#
Persisting a model saves its state (a dictionary mapping module-tree paths to
parameter and buffer tensors), while the architecture itself lives in code.
Because Python's pickle executes arbitrary code on load, weights shared across
trust boundaries should use a code-free format such as safetensors (an 8-byte
length prefix, a JSON header, and packed tensor bytes). Crash-safe training
checkpoints write atomically via temporary files and capture five components:
model state, optimizer state, RNG state, step counter, and config. Restoring all
five resumes training bit for bit; dropping RNG state drifts the data stream,
and dropping Adam's moments causes the first resumed step to move every
parameter by the full learning rate, spiking the loss by orders of magnitude.
When loading pretrained weights into a modified architecture, always audit the
missing and unexpected key sets against your expectations rather than ignoring
mismatches silently.
5.6.6 Exercises#
- [code] Safetensors header. The header length of the MLP's
safetensors file is the 8-byte little-endian integer at the start of the
file (Figure 5.6.1).
- Predict, then measure, how that length changes when the hidden width is doubled and when a third layer is added. Explain which parts of the header depend on tensor sizes at all.
- Read the hidden layer's bias from the file using only the header and
file seeks, without the safetensors library. Decode the bytes with
the dtype and shape that the header records, and check that the
result equals the tensor that
load_filereturns. - Explain why a pickle-based checkpoint cannot offer the same single-tensor read without deserializing the whole object graph.
-
[code] Partial loading. Define
MLP2, a copy ofMLPthat inserts a second hidden layerhidden2of width 256 before the output layer and renames the attributeoutputtohead.- Load
mlp.safetensorsintoMLP2withload_state_dict(..., strict=False). Read the returned report and explain each missing and each unexpected key. - Rename the file's keys to the names that
MLP2uses before loading. Confirm that onlyhidden2keeps its fresh initialization, and make the load raise on any unexpected key and on any missing key outsidehidden2.
Adapted from Matthew Inkawhich, Saving and Loading Models, "Warmstarting Model Using Parameters from a Different Model".
- Load
- [code] Dtype round trip. ● A
float16number stores 5 exponent bits and 10 mantissa bits, against 8 and 23 infloat32(Section 5.5). Cast the parameters of anMLPtofloat16, save them, and load them back into afloat32MLP.- Predict the largest relative error of a restored parameter from the mantissa width. Measure the maximum absolute difference and, over the nonzero parameters, the maximum relative difference between the restored and the original values. Explain any parameter whose relative error exceeds the prediction.
- Compare the outputs of the original and the restored
MLPonX, and decide whether the round trip is acceptable for inference. - Adam keeps a running average of squared gradients.
Compute what
float16stores for the square of a gradient entry of , and explain why a resumable checkpoint keeps the optimizer state infloat32.
- [extended] Crash-safe manifest. ●
- Build a utility that writes model state, optimizer state, and a JSON metadata file under a fresh step-numbered prefix, then publishes the three by renaming into place one manifest that records each file's name, size, and checksum.
- Simulate two failures: a crash after the three files are written but before the manifest rename, and the truncation of one file of a published checkpoint. Show that reloading resumes from the previous complete checkpoint in the first case and rejects the corrupt checkpoint in the second.
- A rename is atomic, so a reader sees either the old manifest or the
new one. POSIX does not require the data of the renamed files to
reach the disk before the rename does.
os.fsyncforces the buffered writes of a file, or of a directory's entries, to disk. State where the utility must callos.fsyncso that a power loss leaves either the previous checkpoint or the new one intact, and explain each call.