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?

With 10 seeds each, the averages' spreads shrink by \(\sqrt{10} \approx 3.2\) (C4's \(1/\sqrt N\)), to about ±0.5%: then a 0.7-point gap starts to be visible. Probability 4's tests make "visible" precise.

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
  1. Model A's accuracy over seeds has a spread \(s_A \approx 1.5\%\); B's \(s_B \approx 0.7\%\).
  2. 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).
  3. 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.
  4. 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.
  5. 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?

A results table that only shows winners hides how much searching produced them, which is exactly the information needed to judge how lucky the winner is.

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:

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

6. What to carry forward

All lessons: AI from scratch. Made With ML's lessons on experiment tracking and versioning go further into the tools.

Last updated