AI from scratch · Toolkit 6 · Stage 4: the engineer's toolkit
Experiments you can trust
"Last week it got 93%. Today, same code, 91%." "My change gave +0.8%!" "Which run was that model from?" Every team hears these, and they all have the same cause: experiments that weren't set up to be repeated or compared. Machine learning is unusually prone to it, because training is random on purpose and has dozens of settings. This lesson is the habits that make a result mean something: fix the randomness, write settings down, record every run, pin the data and the model to the run that made them, and compare with enough seeds to see past luck.
1. The seed lottery
Two small networks on a set of handwritten digits (the kind chapter 6 later teaches a network to read): model A has 16 hidden neurons, model B has 20. Each was trained 10 times, identical in every way except the random seed, which sets the starting weights and the order of the examples. Every dot is one real run (scikit-learn, 60 epochs, 540 test digits).
model A (16 neurons) model B (20 neurons)
B is better on average (92.4% against 91.3%). But A's runs spread from 89.3% to 93.1%, wider than the gap between the models. Compare one run of each and A wins about a quarter of the time. A team that tries an idea once, sees +0.8%, and ships it, is often shipping a lucky seed.
Your change raises accuracy from 91.2% to 91.9% in one run each. The seed-to-seed spread of this model is about ±1.5%. What can you say?
- The change helps
- The change does nothing
- Nothing yet: run several seeds of each and compare the averages
Training is random on purpose, so one run is one draw from a spread; compare averages over several seeds, never single runs.
Why a single run can't tell close models apart
- Model A's accuracy over seeds has a spread \(s_A \approx 1.5\%\); B's \(s_B \approx 0.7\%\).
- One run of each: the difference \(B - A\) has spread \(\sqrt{s_A^2 + s_B^2} \approx 1.7\%\) (variances of independent draws add, P4).
- The true gap is 1.1%, less than one spread of the difference. So a single comparison lands on the wrong side a good fraction of the time: here 26%, plus 5% exact ties.
- Average \(k\) seeds of each and the spread of the difference falls to \(1.7\% / \sqrt k\): with \(k = 10\), 0.5%, and the 1.1% gap is two spreads away from zero.
- The rule of thumb: to see a gap \(\delta\) reliably you need \(k\) with \(1.7\%/\sqrt k\) well under \(\delta/2\). Small gaps need many seeds, and many seeds cost compute: that trade is why big labs report results on few seeds and why their small gains are often noise.
2. Fix the randomness
To repeat a run exactly, every random choice must start from a known seed: Python's, NumPy's, PyTorch's, and the data loader's shuffling.
import random, numpy as np, torch
def set_seed(seed):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed) # torch.manual_seed also seeds the GPU
g = torch.Generator().manual_seed(0)
loader = DataLoader(train_ds, batch_size=64, shuffle=True, generator=g) # the shuffle order, pinned
torch.use_deterministic_algorithms(True) # optional: refuse GPU kernels that aren't repeatable (slower)
Seeding is for repeating a run (debugging, checking that a change really did nothing), not for judging one. A result that only holds for seed 42 isn't a result.
Seed every source of randomness to repeat a run exactly, and vary the seed on purpose to measure how much results wobble.
3. Configs: every setting in one place
A run is defined by its settings: data version, model size, learning rate, schedule, epochs, seed. Put them in one dictionary (or a YAML file), pass it to the training code, and save it next to the results. Then "what did run 17 use?" has an answer, and a new run is a changed config rather than an edited script.
config = {"data": "digits-v1", "hidden": 16, "lr": 1e-3, "epochs": 60, "seed": 0}
model = train(**config) # the code reads its settings from the config, never from constants inside it
A config holds every setting of a run in one place, so a run can be described, repeated and changed without touching the code.
4. Track every run
Record each run as one row: its config, its metrics, when it ran, the code version (git rev-parse HEAD) and the data version. A JSON-lines file (one JSON object per line) is enough to start; MLflow, Weights & Biases and TensorBoard do the same with charts and a web page. The point is the habit: every run gets logged, including the failures, so you can see what you tried.
Why log the failed and the boring runs too?
- To fill the dashboard
- So you can see how many things you tried: the best of 40 tries is optimistic (chapter 11), and you won't repeat dead ends
- Because the model trains on them
Log every run, with its config, code version, data version and metrics, so results can be traced and searches judged honestly.
5. Pin the data and the model
Code is versioned with git; data and models need the same. Two cheap habits cover most of it:
- Hash the data. A hash (like SHA-256) turns a file into a short fingerprint that changes if a single byte changes. Store it in the config. If someone quietly re-exports the CSV, the hash tells you.
- Save the model with its story. Next to the weights (
torch.save(model.state_dict(), ...)), save the config, the data hash, the git commit and the metrics. Tools like DVC and model registries do this at scale.
A hash fingerprints the exact data, and a model saved with its config, data hash and commit can always be traced back to how it was made.
Where it breaks: when "same seed" isn't the same run
- GPUs add in a different order. Many GPU kernels sum with many threads at once, and floating-point addition isn't exactly associative: \((a + b) + c\) can differ from \(a + (b + c)\) in the last digit. Over thousands of steps those differences grow, so two "identical" GPU runs can end a few tenths of a percent apart.
torch.use_deterministic_algorithms(True)forbids such kernels, at some cost in speed. - A new library version. The same seed with a newer PyTorch, NumPy or CUDA can draw different random numbers or use different kernels. Record versions (
pip freeze, a lock file, a Docker image) with each run. - The test set wears out. A tracker makes it easy to compare hundreds of runs on the same test set, and picking the best of hundreds overfits it (chapter 11, P4). Tune on validation; touch the test set rarely, and refresh it when you can.
6. What to carry forward
- One run is a draw from a spread: compare averages over several seeds, with the spread shown.
- Seed everything to repeat a run; record library versions too.
- All settings in a config, saved with the run.
- Log every run (config, commit, data hash, metrics), including failures.
- Save models with their config, data hash and metrics.
All lessons: AI from scratch. Made With ML's lessons on experiment tracking and versioning go further into the tools.
Last updated