Checkpoints, Seeds and Reproducibility
Two questions come up in every real training project. Can I stop and continue? Jobs get pre-empted, machines reboot, and a run of several days must survive that. Can I get the same result again? A colleague must be able to reproduce your numbers, and you must be able to tell whether a change helped or whether the run was merely lucky. Both questions have the same answer at their core: control every source of state and randomness, and save it.
The training course already covered the principles: what goes into a checkpoint and why, in early stopping and checkpointing, and resuming a distributed run, with rank 0 saving and every rank restoring its RNG, in DDP and checkpointing. Both prove a resume at an epoch boundary. This lesson adds the PyTorch details that those lessons leave out: resuming in the middle of an epoch, loading checkpoints safely, and what determinism settings can and cannot promise.
What a PyTorch checkpoint holds
| Key | Saved with | Restored with |
|---|---|---|
| model weights and buffers | model.state_dict() |
model.load_state_dict(...) |
| optimizer state (momentum, Adam moments, step counts) | optimizer.state_dict() |
optimizer.load_state_dict(...) |
| scheduler position | scheduler.state_dict() |
scheduler.load_state_dict(...) |
| gradient scaler (float16 training) | scaler.state_dict() |
scaler.load_state_dict(...) |
| where you are | epoch and step counters, best score, early-stopping counter | plain numbers |
| the data order | the DataLoader generator's state at the start of the epoch |
generator.set_state(...), then skip the batches already done |
| other randomness | torch.get_rng_state(), torch.cuda.get_rng_state_all(), random.getstate(), a NumPy Generator's bit_generator.state |
the matching setters |
| what produced it | config, code commit, data version | read by you |
The data-order row is the subtle one. A shuffling DataLoader draws its whole permutation from its generator when the epoch's iterator is created, so the state at the crash is already past that draw. Save the state from the start of the epoch, restore it, create the iterator again, and skip the batches that were already trained on.
Resume in the middle of an epoch
A 64-64-10 MLP with dropout on 512 Digits images, AdamW and a learning rate halved every epoch, 3 epochs of 8 steps. One run goes straight through. A second run "crashes" after step 5 of epoch 1 (the 13th step), saves a checkpoint into an in-memory buffer, and a third run starts from scratch with a different seed, loads the checkpoint over everything and continues.
import io, random
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
X, y = load_digits(return_X_y=True)
ds = TensorDataset(torch.tensor(X[:512] / 16.0, dtype=torch.float32), torch.tensor(y[:512]))
EPOCHS, CRASH = 3, (1, 5) # crash after step 5 of epoch 1 (epochs count from 0)
def build(seed):
torch.manual_seed(seed)
model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Dropout(0.3), nn.Linear(64, 10))
opt = torch.optim.AdamW(model.parameters(), lr=1e-2)
sched = torch.optim.lr_scheduler.StepLR(opt, step_size=1, gamma=0.5)
gen = torch.Generator().manual_seed(seed)
return model, opt, sched, gen, DataLoader(ds, batch_size=64, shuffle=True, generator=gen)
def train(model, opt, sched, gen, loader, start=(0, 0), stop=None, epoch_gen_state=None):
losses = []
for epoch in range(start[0], EPOCHS):
if epoch == start[0] and epoch_gen_state is not None:
gen.set_state(epoch_gen_state) # replay this epoch's shuffle
gen_state = gen.get_state() # the state the epoch's permutation comes from
for step, (xb, yb) in enumerate(loader):
if epoch == start[0] and step < start[1]:
continue # already done before the crash
loss = nn.functional.cross_entropy(model(xb), yb)
opt.zero_grad(); loss.backward(); opt.step()
losses.append(round(loss.item(), 6))
if (epoch, step + 1) == stop:
return losses, {"model": model.state_dict(), "optimizer": opt.state_dict(),
"scheduler": sched.state_dict(), "epoch": epoch, "step": step + 1,
"loader_gen": gen_state, "torch_rng": torch.get_rng_state(),
"python_rng": random.getstate()}
sched.step()
return losses, None
full, _ = train(*build(0))
first, ckpt = train(*build(0), stop=CRASH)
buf = io.BytesIO(); torch.save(ckpt, buf); buf.seek(0)
# "new process": everything rebuilt with another seed, then overwritten from the checkpoint
model, opt, sched, gen, loader = build(123)
ck = torch.load(buf) # weights_only=True: tensors, numbers, tuples only
model.load_state_dict(ck["model"]); opt.load_state_dict(ck["optimizer"]); sched.load_state_dict(ck["scheduler"])
torch.set_rng_state(ck["torch_rng"]); random.setstate(ck["python_rng"])
rest, _ = train(model, opt, sched, gen, loader, start=(ck["epoch"], ck["step"]), epoch_gen_state=ck["loader_gen"])
print("steps: uninterrupted", len(full), "| before crash", len(first), "+ after resume", len(rest))
print("resumed losses identical:", first + rest == full)
print("last 3 losses:", full[-3:], "vs", rest[-3:])
# the same resume without the RNG states: dropout masks differ from the crash point on
model, opt, sched, gen, loader = build(123)
model.load_state_dict(ck["model"]); opt.load_state_dict(ck["optimizer"]); sched.load_state_dict(ck["scheduler"])
rest2, _ = train(model, opt, sched, gen, loader, start=(ck["epoch"], ck["step"]), epoch_gen_state=ck["loader_gen"])
print("without torch RNG state identical:", first + rest2 == full, "| first resumed loss", rest2[0], "vs", full[len(first)])steps: uninterrupted 24 | before crash 13 + after resume 11
resumed losses identical: True
last 3 losses: [1.236183, 1.237977, 1.308771] vs [1.236183, 1.237977, 1.308771]
without torch RNG state identical: False | first resumed loss 1.475861 vs 1.472381
The 13 steps before the crash and the 11 after the resume reproduce all 24 losses of the uninterrupted run, to the six printed decimals and in fact bit for bit (the comparison is on the rounded values, and the weights would compare equal too). The same resume without restoring the torch RNG state already differs at the first resumed step, 1.475861 instead of 1.472381: dropout drew different masks. Every piece of state matters, and the test that proves a checkpoint complete is exactly this comparison. Run it once whenever you change the training code.
Note that the resume rebuilds everything first (with seed 123, to make sure nothing leaks from the original seed) and then overwrites it. That is the normal pattern: construct model, optimizer, scheduler and loader as for a fresh run, then load their states.
Loading safely: weights_only
torch.save uses Python's pickle, and unpickling can call any function the file names. A checkpoint from the internet can therefore run code on your machine the moment you load it. Since PyTorch 2.6, torch.load defaults to weights_only=True: it only rebuilds tensors, primitive types (numbers, strings, None), and lists, tuples and dicts of them, and refuses everything else.
import io
import random
import numpy as np
import torch
from torch import nn
def culprit(e): # the line of the error that names the rejected object
return [l.strip().split(" was not")[0] for l in str(e).splitlines() if "Unsupported global" in l][0]
class Payload:
def __reduce__(self): # pickle calls this; on load it runs print(...)
return (print, ("!!! code from inside the checkpoint just ran",))
model = nn.Linear(3, 2)
evil = io.BytesIO(); torch.save({"model": model.state_dict(), "extra": Payload()}, evil)
evil.seek(0)
try:
torch.load(evil) # default since PyTorch 2.6: weights_only=True
except Exception as e:
print(type(e).__name__ + ":", culprit(e))
evil.seek(0)
torch.load(evil, weights_only=False) # full unpickling: runs the payload
legacy = io.BytesIO(); torch.save({"numpy_rng": np.random.get_state()}, legacy)
legacy.seek(0)
try:
torch.load(legacy)
except Exception as e:
print(type(e).__name__ + ":", culprit(e))
rng = np.random.default_rng(0)
safe = io.BytesIO()
torch.save({"model": model.state_dict(), "epoch": 3, "best_val": 0.1218,
"torch_rng": torch.get_rng_state(), # a uint8 tensor
"numpy_rng": rng.bit_generator.state, # a dict of str and int
"python_rng": random.getstate()}, safe) # a tuple of ints
safe.seek(0)
ck = torch.load(safe) # weights_only=True
print("weights_only load ok:", sorted(ck))
rng2 = np.random.default_rng(); rng2.bit_generator.state = ck["numpy_rng"]
print("restored NumPy generator continues identically:", rng2.random() == rng.random())UnpicklingError: WeightsUnpickler error: Unsupported global: GLOBAL print
!!! code from inside the checkpoint just ran
UnpicklingError: WeightsUnpickler error: Unsupported global: GLOBAL numpy._core.multiarray._reconstruct
weights_only load ok: ['best_val', 'epoch', 'model', 'numpy_rng', 'python_rng', 'torch_rng']
restored NumPy generator continues identically: True
The harmless payload here only prints, but it could as easily delete files or send your credentials somewhere. With the default weights_only=True it is rejected; with weights_only=False it runs during loading, before you can inspect anything. The practical consequences:
- Store your own checkpoints in plain types, so they load with the safe default: tensors, numbers, strings, lists, dicts. The legacy
np.random.get_state()contains a NumPy array and is rejected (third line); a NumPyGenerator'sbit_generator.stateis a plain dict and loads fine, as dotorch.get_rng_state()(a tensor) andrandom.getstate()(a tuple of ints). - Never pass
weights_only=Falsefor a file you did not create. If a trusted file needs one extra class, allow exactly that class withtorch.serialization.add_safe_globals([...]). - For publishing weights, prefer
safetensors: a format that holds only tensors and a JSON header, with no code path at all. The Hugging Face Hub uses it by default.
Seeds and deterministic algorithms
Reproducing a run from scratch needs the same seeds for every generator the code uses and the same algorithms. A typical setup at the top of a training script:
import os, random
import numpy as np
import torch
def seed_everything(seed):
random.seed(seed)
np.random.seed(seed) # legacy global RNG, still used by some libraries
torch.manual_seed(seed) # CPU and all CUDA devices
return np.random.default_rng(seed) # pass this Generator to your own code
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8" # needed by deterministic cuBLAS (set before CUDA starts)
torch.use_deterministic_algorithms(True) # error on operations without a deterministic version
torch.backends.cudnn.benchmark = False # do not time and pick convolution algorithms per run
torch.backends.cudnn.deterministic = True # only deterministic cuDNN convolution algorithmsWhat each line buys:
- Seeds fix initial weights, dropout masks, augmentation and shuffling, provided every source is seeded: the
DataLoadergenerator and worker seeds (Dataset and DataLoader) are part of it. torch.use_deterministic_algorithms(True)makes PyTorch choose deterministic implementations and raise an error for operations that have none (some scatter-add and index-add kernels on CUDA use atomic additions, whose order varies). Withwarn_only=Trueit warns instead; the recordings in this course run with that setting.- cuDNN flags. With
benchmark=True, cuDNN times several convolution algorithms on the first batch of each shape and keeps the fastest. That is often a large speed-up, but the choice can differ between runs and the algorithms differ in rounding.deterministic=Truerestricts cuDNN to deterministic algorithms. Both only affect NVIDIA GPUs; they cannot be demonstrated on the CPU used for this course's recordings. - The cost: deterministic kernels can be noticeably slower. A common compromise is determinism while debugging and for final reference runs, and speed for exploration.
What still varies across machines
Floating-point addition is not associative: (a + b) + c and a + (b + c) can round differently. Every parallel reduction, a sum split across CPU threads or GPU blocks, fixes some order of additions, and that order depends on the hardware, the library version, the number of threads and the kernel chosen. This example runs in the browser and sums the same 100 000 float32 numbers in four orders:
import math
import numpy as np
rng = np.random.default_rng(0)
x = rng.normal(size=100_000).astype(np.float32)
exact = math.fsum(x.astype(np.float64)) # correctly rounded reference
pairwise = float(x.sum()) # NumPy: pairwise summation
sequential = float(np.cumsum(x)[-1]) # one running total, left to right
chunks = float(sum(c.sum() for c in np.array_split(x, 4))) # four "threads", then combine
reverse = float(x[::-1].sum())
for name, v in [("exact (float64 fsum)", exact), ("pairwise", pairwise), ("sequential", sequential),
("4 chunks", chunks), ("reversed", reverse)]:
print(f"{name:21s} {v:.6f}")
print("all float32 results equal:", len({pairwise, sequential, chunks, reverse}) == 1)
exact (float64 fsum) -90.825078
pairwise -90.825111
sequential -90.824966
4 chunks -90.825027
reversed -90.825119
all float32 results equal: False
All four float32 sums are close to the exact value -90.825078 and all four differ from each other, already in the fourth decimal. A neural network performs billions of such reductions, and training amplifies tiny differences: two runs that agree to seven digits after the first step can disagree in the third digit after a few thousand. So, honestly stated:
- Same machine, same software, same settings, fixed seeds, deterministic algorithms: bit-identical results, as in the resume example above.
- Different GPU model, different number of threads, different PyTorch, CUDA or cuDNN version: close but not identical results. PyTorch documents that reproducibility is not guaranteed across releases or platforms.
- Different batch size or number of data-parallel workers: a different computation, not just a different rounding.
The scientific consequence: a difference between two models is only meaningful if it is larger than the spread between seeds. Report the mean and the spread over several seeds rather than a single run.
Pitfalls
- Saving only
model.state_dict()and calling it a checkpoint. Enough for inference, not for resuming: the optimizer moments, the schedule and the RNG states are lost, and the resumed curve visibly jumps. - Saving the loader generator at the crash instead of at the epoch start. The epoch's permutation was drawn at the start; replay it from there and skip the finished batches.
weights_only=Falseon downloaded files. It executes whatever the file contains.- Putting NumPy arrays or custom objects into checkpoints. They break the safe default; convert to tensors or plain types.
- Writing the checkpoint in place. A crash during
torch.saveleaves a corrupt file and no good one. Save to a temporary name and rename it (an atomic operation), and keep the previous checkpoint (DDP and checkpointing covers this and how often to save). - Expecting identical numbers on a different machine. Expect agreement within the seed-to-seed spread.
Practice
- A run saves
model,optimizerandepochat the end of each epoch and nothing else. After resuming, the training loss curve matches the old one only roughly. Name three things that differ after the resume.
Answer
The learning-rate schedule restarts (scheduler state missing), the data order differs (loader generator not restored), and dropout masks and augmentation differ (torch, Python and NumPy RNG states not restored). With float16 training, the gradient scaler's scale also restarts.
- Why does the mid-epoch resume restore the generator state from the start of the epoch and then skip 5 batches, instead of saving the generator state at the crash?
Answer
RandomSampler draws the permutation for the whole epoch when the epoch's iterator is created, so the generator state at the crash has already moved past that draw. Restoring it would produce the permutation of a different epoch. Restoring the start-of-epoch state reproduces the same permutation, and skipping the first 5 batches continues where training stopped.
- A teammate shares
model.ptand says "load it withweights_only=False, otherwise it fails". What do you do?
Answer
Do not load it that way unless you trust the source as much as running their code. Ask which extra objects the file contains; if it is a known class, allow just that class with torch.serialization.add_safe_globals, or ask for a state_dict of tensors (or a safetensors file) instead of a pickled object.
Test yourself
Which part of the state did the failed resume in the recording leave out?
- The optimizer state
- The torch RNG state, so dropout drew different masks
- The scheduler
- The data order
What does torch.load(path) with the default weights_only=True refuse?
- Tensors on the GPU
- Dicts of tensors
- Arbitrary pickled objects and functions, which could execute code
- Files larger than 2 GB
Why can two runs with the same seed give slightly different losses on two different GPUs?
- Seeds are ignored on GPUs
- Parallel reductions add floating-point numbers in a hardware-dependent order, and rounding depends on the order
- GPUs use a different random generator
- Dropout is disabled on GPUs
What does torch.backends.cudnn.benchmark = True trade away?
- Memory
- Run-to-run reproducibility, because the fastest convolution algorithm is chosen by timing
- Accuracy of the model
- Support for mixed precision