Experiments and reproducibility
Last updated
Training a network is an experiment: you change something, run it, and compare. That only works if a run can be repeated, every run is written down, and the model you liked can be loaded again tomorrow. This lesson fixes the randomness with seeds, records a small experiment in a table, saves and loads models with state_dict, and shows what happens when the code that loads a model doesn't match the code that saved it.
By the end of this lesson you can
- Make a training run repeatable with torch.manual_seed
- Record every run's settings and scores, and compare settings across seeds
- Save and load a model's weights, and a checkpoint to resume training from
- Read and fix a state_dict mismatch error
Seeds and determinism
Training is full of random choices: the starting weights, the order of the batches, which units dropout switches off. Run the same script twice and you get two different models. That makes a comparison between two settings hard to trust: was the difference the setting, or the dice?
PyTorch's random numbers come from a generator that starts from a number, the seed. Fix the seed and every "random" number after it is the same, in the same order (lesson 0.7 did the same for NumPy):
"""The same training run twice without a seed, then twice with one.""" import torch from sklearn.datasets import load_digits from torch import nn from torch.nn import functional as F X, y = load_digits(return_X_y=True) X, y = torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y) def train(seed=None): if seed is not None: torch.manual_seed(seed) # fixes the starting weights and the shuffling model = nn.Sequential(nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 10)) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) for epoch in range(3): for idx in torch.randperm(len(X)).split(32): loss = F.cross_entropy(model(X[idx]), y[idx]) optimizer.zero_grad() loss.backward() optimizer.step() return loss.item() a, b = train(), train() # different every time the script runs print("no seed: the two final losses are equal:", a == b) print("seed 0: ", f"{train(0):.10f}", f"{train(0):.10f}") print("seed 1: ", f"{train(1):.10f}")
(.venv) $ python seeds.py no seed: the two final losses are equal: False seed 0: 0.9143720865 0.9143720865 seed 1: 0.8685278893
Without a seed, the two runs end with different losses. With seed 0, both end at 0.9143720865, identical to every digit. Seed 1 is a different run again. (The loss printed is the last batch's, which holds the 5 digits left over after 56 batches of 32, so it's noisy.)
Three limits on this:
- Seed every generator you use.
torch.manual_seedcovers PyTorch. If your code also uses NumPy's or Python'srandom, seed those too. - Same machine, same versions. Different hardware, a GPU instead of a CPU, or a different PyTorch version can change results in the last digits, and over thousands of steps those differences grow. Your numbers from these scripts may not match the ones here exactly, though they should be close.
- Some GPU operations aren't deterministic even with a seed, because they add numbers in whatever order threads finish.
torch.use_deterministic_algorithms(True)makes PyTorch use deterministic versions, or raise an error where it has none; it can be slower.
Recording and comparing runs
A seed makes one run repeatable. It doesn't make it typical: seed 1 was a different model, and might score differently. So when you compare settings, run each one with several seeds and compare the spread as well as the score.
This script tries 8 settings (two widths, two learning rates, with and without dropout), each with seeds 0, 1 and 2. Every run becomes a row of runs/results.csv: the settings, the seed, the score and the time it took. The best model is saved too:
"""A small experiment, recorded: 8 settings x 3 seeds, every run saved as a row of runs/results.csv.""" import csv import itertools import os import statistics import time import torch from sklearn.datasets import load_digits from sklearn.model_selection import train_test_split from torch import nn from torch.nn import functional as F X, y = load_digits(return_X_y=True) X_train, X_val, y_train, y_val = train_test_split(X / 16, y, test_size=500, stratify=y, random_state=0) X_train, X_val = torch.tensor(X_train, dtype=torch.float32), torch.tensor(X_val, dtype=torch.float32) y_train, y_val = torch.tensor(y_train), torch.tensor(y_val) def run(width, lr, dropout, seed, epochs=20): torch.manual_seed(seed) model = nn.Sequential(nn.Linear(64, width), nn.ReLU(), nn.Dropout(dropout), nn.Linear(width, 10)) optimizer = torch.optim.Adam(model.parameters(), lr=lr) for epoch in range(epochs): model.train() for idx in torch.randperm(len(X_train)).split(32): loss = F.cross_entropy(model(X_train[idx]), y_train[idx]) optimizer.zero_grad() loss.backward() optimizer.step() model.eval() with torch.no_grad(): return (model(X_val).argmax(1) == y_val).float().mean().item(), model os.makedirs("runs", exist_ok=True) rows, best = [], (0.0, None, None) for width, lr, dropout in itertools.product((32, 256), (1e-3, 1e-2), (0.0, 0.3)): for seed in (0, 1, 2): start = time.perf_counter() acc, model = run(width, lr, dropout, seed) rows.append({"width": width, "lr": lr, "dropout": dropout, "seed": seed, "val_acc": round(acc, 4), "seconds": round(time.perf_counter() - start, 2)}) if acc > best[0]: best = (acc, model.state_dict(), rows[-1]) with open("runs/results.csv", "w", newline="") as f: writer = csv.DictWriter(f, fieldnames=rows[0].keys()) writer.writeheader() writer.writerows(rows) torch.save(best[1], "runs/best.pt") print(f"{len(rows)} runs saved to runs/results.csv") print("width lr dropout val acc, seeds 0 1 2 mean spread") for width, lr, dropout in itertools.product((32, 256), (1e-3, 1e-2), (0.0, 0.3)): accs = [r["val_acc"] for r in rows if (r["width"], r["lr"], r["dropout"]) == (width, lr, dropout)] print(f"{width:5} {lr:6} {dropout:8} {accs[0]:.3f} {accs[1]:.3f} {accs[2]:.3f} {statistics.mean(accs):.3f} {max(accs) - min(accs):.3f}") b = best[2] print(f"best single run: width {b['width']}, lr {b['lr']}, dropout {b['dropout']}, seed {b['seed']}: {b['val_acc']:.3f}, saved to runs/best.pt")
(.venv) $ python runs.py 24 runs saved to runs/results.csv width lr dropout val acc, seeds 0 1 2 mean spread 32 0.001 0.0 0.950 0.952 0.950 0.951 0.002 32 0.001 0.3 0.940 0.940 0.938 0.939 0.002 32 0.01 0.0 0.976 0.974 0.976 0.975 0.002 32 0.01 0.3 0.964 0.956 0.960 0.960 0.008 256 0.001 0.0 0.974 0.974 0.966 0.971 0.008 256 0.001 0.3 0.968 0.970 0.972 0.970 0.004 256 0.01 0.0 0.978 0.976 0.976 0.977 0.002 256 0.01 0.3 0.976 0.970 0.962 0.969 0.014 best single run: width 256, lr 0.01, dropout 0.0, seed 0: 0.978, saved to runs/best.pt
| seeds 0, 1, 2 0.93 … 0.98 | |||||
|---|---|---|---|---|---|
| 256 | 0.01 | 0 | 0.977 | 0.002 | |
| 32 | 0.01 | 0 | 0.975 | 0.002 | |
| 256 | 0.001 | 0 | 0.971 | 0.008 | |
| 256 | 0.001 | 0.3 | 0.970 | 0.004 | |
| 256 | 0.01 | 0.3 | 0.969 | 0.014 | |
| 32 | 0.01 | 0.3 | 0.960 | 0.008 | |
| 32 | 0.001 | 0 | 0.951 | 0.002 | |
| 32 | 0.001 | 0.3 | 0.939 | 0.002 |
Best mean: width 256, learning rate 0.01, dropout 0, at 0.977. The same setting's three seeds differ by 0.002; differences between settings smaller than their spreads could be luck. Sorted by mean, highest first.
What the table says, and doesn't:
- The best mean is width 256, learning rate 0.01, no dropout: 0.977. But width 32 with the same learning rate scores 0.975, and each setting's own seeds spread over 0.002. With 500 validation digits, 0.002 is one digit. These two can't be told apart.
- Some differences are real. A learning rate of 0.01 beats 0.001 in three of the four pairs, and dropout 0.3 lowers the mean in all four, clearly so at width 32, where it costs 0.012 and 0.015 against spreads of 0.008 or less. (Dropout's benefit needs longer training on less data, as in lesson 7.8.)
- One seed can mislead. The setting with the largest spread, width 256 with learning rate 0.01 and dropout 0.3, ranges from 0.962 to 0.976. With only seed 2 it would look worse than every other width-256 setting; with only seed 0, as good as the best.
Write every run down, including the bad ones, in a file the code writes, not by hand. A CSV like this opens in pandas (pd.read_csv("runs/results.csv")) or a spreadsheet. Bigger projects use tools such as TensorBoard or MLflow to log curves as well, but the habit is the same: settings and results together, for every run.
Saving and loading models
A model's state_dict is a dictionary of its learned numbers: one tensor per weight and bias, named by where it sits in the model. torch.save writes it to a file; load_state_dict copies it into a model:
"""Saving a model's weights with state_dict, and a checkpoint to carry on training from.""" import torch from sklearn.datasets import load_digits from torch import nn from torch.nn import functional as F X, y = load_digits(return_X_y=True) X, y = torch.tensor(X / 16, dtype=torch.float32), torch.tensor(y) def make_model(): return nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10)) torch.manual_seed(0) model = make_model() optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) for epoch in range(5): for idx in torch.randperm(len(X)).split(32): loss = F.cross_entropy(model(X[idx]), y[idx]) optimizer.zero_grad() loss.backward() optimizer.step() state = model.state_dict() # a dictionary: one tensor per weight and bias print("state_dict:", {name: tuple(t.shape) for name, t in state.items()}) torch.save(state, "digits.pt") loaded = make_model() # the same code builds the same shapes... loaded.load_state_dict(torch.load("digits.pt")) # ...and the saved numbers fill them in loaded.eval() model.eval() with torch.no_grad(): same = torch.equal(model(X), loaded(X)) acc = (loaded(X).argmax(1) == y).float().mean().item() print(f"loaded model gives identical outputs: {same}; accuracy {acc:.3f}") # to carry on training later, save the optimiser's state and the epoch too torch.save({"epoch": 5, "model": model.state_dict(), "optimizer": optimizer.state_dict()}, "checkpoint.pt") checkpoint = torch.load("checkpoint.pt") print("checkpoint keys:", list(checkpoint), " resume at epoch", checkpoint["epoch"] + 1)
(.venv) $ python save_load.py state_dict: {'0.weight': (128, 64), '0.bias': (128,), '2.weight': (10, 128), '2.bias': (10,)} loaded model gives identical outputs: True; accuracy 0.937 checkpoint keys: ['epoch', 'model', 'optimizer'] resume at epoch 6
The names come from the model's structure: 0.weight is the weight of layer 0 of the Sequential, the first Linear; 2.weight is layer 2, the second Linear (layer 1 is the ReLU, which has no weights). The file holds numbers, not code, so loading needs a model built by the same code: make_model() makes the empty shapes and the file fills them in. The loaded model gives identical outputs.
To pause training and carry on later, save a checkpoint: the model's state_dict, the optimiser's state_dict (Adam's running averages from lesson 7.3, which it would otherwise have to rebuild) and the epoch number. Load all three and the next epoch carries on as if nothing happened.
Two habits:
- Save the
state_dict, not the whole model.torch.save(model)also works, but it pickles the model's class by name, and breaks when you rename or move that code. - Only load files you trust.
torch.loadreads only tensors and plain values by default (weights_only=True). Don't turn that off for a file from someone else: a pickle can run any code when it's loaded.
Wrong way: loading into a different architecture
The file was saved from one model; the loading code builds another. This happens all the time: you widened a layer, or added dropout, after saving.
"""The wrong way: loading saved weights into a model built differently from the one that saved them.""" import torch from torch import nn torch.manual_seed(0) saved = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10)) torch.save(saved.state_dict(), "saved.pt") attempts = { "a wider hidden layer": nn.Sequential(nn.Linear(64, 256), nn.ReLU(), nn.Linear(256, 10)), "a Dropout layer added": nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Dropout(0.3), nn.Linear(128, 10)), } for name, model in attempts.items(): print(f"--- {name}") try: model.load_state_dict(torch.load("saved.pt")) except RuntimeError as e: print(f"RuntimeError: {e}")
(.venv) $ python mismatch.py --- a wider hidden layer RuntimeError: Error(s) in loading state_dict for Sequential: size mismatch for 0.weight: copying a param with shape torch.Size([128, 64]) from checkpoint, the shape in current model is torch.Size([256, 64]). size mismatch for 0.bias: copying a param with shape torch.Size([128]) from checkpoint, the shape in current model is torch.Size([256]). size mismatch for 2.weight: copying a param with shape torch.Size([10, 128]) from checkpoint, the shape in current model is torch.Size([10, 256]). --- a Dropout layer added RuntimeError: Error(s) in loading state_dict for Sequential: Missing key(s) in state_dict: "3.weight", "3.bias". Unexpected key(s) in state_dict: "2.weight", "2.bias".
Read the error; it says exactly what's wrong.
- A wider hidden layer: every name matches, but three shapes don't. The file's
0.weightis 128 × 64; the new model's is 256 × 64. - A Dropout layer added: the shapes would all fit, but the names don't. Dropout became layer 2 of the
Sequential, which pushed the lastLinearfrom2to3. The new model is missing3.weightand3.bias; the file has2.weightand2.biasthat nothing wants.
The second is the sneaky one, because dropout has no weights at all. Adding it still renumbers everything after it.
The fix is to save, along with the weights, whatever you need to rebuild the model: torch.save({"config": {"width": 128, "dropout": 0.0}, "model": model.state_dict()}, path), then build the model from config before loading. Better still, keep the model-building code in a module (as lesson 7.9's nets.py) and don't change it under a saved file; make a new function for a new architecture. Avoid load_state_dict(..., strict=False) as a fix: it skips the missing and unexpected names and leaves those layers with random weights, silently.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- PyTorch: Reproducibility: seeding, and why results can still differ across devices and versions
- PyTorch: Saving and loading models: state_dict, and checkpoints with the optimiser's state for resuming
- PyTorch: torch.load: weights_only=True, the default: loads tensors and simple types, not arbitrary objects
- Python: csv: csv.DictWriter, writing a list of dictionaries as rows