Level 3 In-Depth AI · ML Engineering and Production
Experiment Tracking and Reproducibility
Record every training run (code version, data version, configuration, random seed, environment and results) so you can compare runs honestly and rebuild any model months later. Seeds, configs, data hashes, MLflow and Weights & Biases.
- Level
- ●●●●● Easy
- Reading
- 10 min
- To learn it well
- 45 minutes to read, an afternoon to practise
- Builds on
- 5 concepts →
- Quiz
- 5 questions ↓
Read first
The ML Project LifecycleThis leads to
—The full path from zero — 5 concepts before this one
- What Is AI?
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Supervised Learning
- The ML Project Lifecycle
- Experiment Tracking and Reproducibility
Read them roughly in this order. See it on the concept map →
Why it matters
Three weeks into a project, your model scores 0.91. Last Tuesday something scored 0.93. Which code was that? Which version of the data? Was the learning rate 0.003 or 0.0003? Did you already have the bug fix? If you can't answer, the 0.93 is lost, and you can't even be sure it was real.
This happens to everyone who trains models without a system. Machine learning has more moving parts than ordinary software. The result depends on the code, the data, a dozen settings, the random seed, the library versions and sometimes the hardware. Change any one and the number moves.
Experiment tracking is the habit, and the tooling, of recording all of these for every training run, automatically. Reproducibility is the payoff: anyone on the team, including you in six months, can rerun a recorded experiment and get the same model. Tracking also makes comparisons honest. You can see whether an "improvement" is bigger than the noise you get from changing nothing but the seed.
It is the second stage of the The ML Project Lifecycle, and everything later relies on it: you can only deploy and monitor a model whose origin you know.
The intuition
A scientist in a laboratory keeps a lab notebook. Each page records the date, the materials and their batch numbers, the exact procedure, the instrument settings and the result. Without it, a surprising result is just an anecdote.
An experiment tracker is a lab notebook that fills itself in. Each training run — one execution of your training script — gets a page with everything that went in and everything that came out:
If you can recreate every input on the left, you can recreate every output on the right. Leave one out, and the model can't be rebuilt exactly. The usual culprits are the data version and the seed.
Key idea A result you cannot reproduce is a rumour. Log the code version, data version, config, seed and environment of every run, and judge improvements against the run-to-run noise.
How it works
Seeds: taming randomness
Training is full of deliberate randomness: initial weights (Weight Initialization), the order of shuffled mini-batches, Dropout and Regularizing Neural Networks masks, data augmentation, the train/test split. Computers produce this randomness with a pseudo-random number generator, which turns a starting number, the random seed, into a long sequence that looks random but is completely determined by the seed. Same seed, same sequence, same model.
In Python you usually need to seed three generators, because each library keeps its own:
import random, numpy as np, torch
random.seed(0); np.random.seed(0); torch.manual_seed(0)
On a CPU that is usually enough for bit-identical results. On a GPU, some fast operations (certain convolution and scatter-add kernels) add floating-point numbers in an order that varies from run to run. Because floating-point addition is not exactly associative ( can differ from in the last bits), the results drift slightly. PyTorch's torch.use_deterministic_algorithms(True) forces deterministic versions where they exist and raises an error where they don't, at some cost in speed. Even then, the PyTorch documentation warns that results are not guaranteed to match across PyTorch versions or different hardware.
Seed variance: how big is the noise?
Fixing the seed makes a run repeatable. It doesn't make the result representative. A different seed gives a slightly different model and a slightly different score. This spread, called seed variance, is the noise floor for every comparison you make.
Here is a small network trained on the same data with ten seeds, for two widths of hidden layer (the code is below):
If you had run each configuration once with seed 0, you would have seen 96.0% against 97.0% and concluded that the wider model is a full point better. With ten seeds the means are 95.9% and 96.3%, and the spreads overlap almost completely. The honest conclusion is "maybe slightly better, not clearly". A widely cited 2018 study of deep reinforcement learning (Henderson et al., Deep Reinforcement Learning that Matters) found that changing only the seed could produce differences as large as those reported between competing methods.
The practical rule: before you believe a gain, measure the spread across 3–10 seeds. If the gain is smaller than that spread, it is not yet a result.
What to record
Each run should record five inputs and its outputs.
- Code version. With git, this is the commit hash (
git rev-parse HEAD), plus a flag if there were uncommitted changes. A tracker can do this automatically. - Data version. Datasets change: rows are added, labels corrected, filters tweaked. Record a fingerprint of the exact data, such as a hash — a short string computed from the file's bytes that changes completely if even one byte changes. For large or changing datasets, use a data versioning tool such as DVC, which stores the data outside git and commits only small pointer files (Data Pipelines and Datasets).
- Configuration. Every setting: learning rate, batch size, model size, number of epochs, which features. Put them in a configuration file (YAML or a Python dataclass) rather than scattering constants through the code, and log the whole thing.
- Seed. Part of the config, but easy to forget.
- Environment. Python and library versions, ideally a lockfile (Setting Up Your Environment), and the hardware.
Outputs are metrics (loss curves, validation scores), and artifacts: files produced by the run, above all the trained model weights, but also plots, predictions and the config itself.
Tools
You can do all of this with a JSON file per run (the code below does). Dedicated tools add a database, a web dashboard with charts, and comparison tables.
- MLflow (open source, released by Databricks in 2018) logs parameters, metrics and artifacts to a local database or a shared server and shows them in a web UI. It also has a model registry: a catalogue of trained models with versions and stages such as "staging" and "production", so deployment can refer to "churn-model version 7" instead of a file path.
- Weights & Biases (a hosted service, with a free tier for individuals and a free academic licence, as of late 2026) does the same with richer live dashboards and team features. It is popular in deep learning research.
- DVC (Data Version Control) versions data and models alongside git and can define pipelines whose steps rerun only when their inputs change.
- Hydra (from Meta) manages hierarchical configs and lets you override any setting from the command line, for example
python train.py model.hidden=32 seed=1,2,3.
Most frameworks, including the Hugging Face Trainer and PyTorch Lightning, can report to MLflow or Weights & Biases with one setting.
In code
A complete, dependency-light version: one config dataclass, one seed function, one training function and a log line per run. The dataset is fixed with its own seed, so only the model's randomness varies.
import hashlib, json, random, time
from dataclasses import dataclass, asdict
from pathlib import Path
import numpy as np
import torch
@dataclass
class Config:
seed: int = 0
lr: float = 0.05
hidden: int = 16
epochs: int = 30
def set_seed(seed):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
def make_data(): # fixed dataset: always seed 123
g = np.random.default_rng(123)
X = g.normal(size=(600, 2)).astype("float32")
y = ((X[:, 0] ** 2 + X[:, 1] ** 2) < 1.2).astype("int64") # inside a circle?
return X, y
def train(cfg):
set_seed(cfg.seed)
X, y = map(torch.from_numpy, make_data())
model = torch.nn.Sequential(torch.nn.Linear(2, cfg.hidden), torch.nn.ReLU(),
torch.nn.Linear(cfg.hidden, 2))
opt = torch.optim.SGD(model.parameters(), lr=cfg.lr)
for _ in range(cfg.epochs):
for idx in torch.randperm(400).split(32): # shuffled mini-batches
loss = torch.nn.functional.cross_entropy(model(X[idx]), y[idx])
opt.zero_grad(); loss.backward(); opt.step()
return (model(X[400:]).argmax(1) == y[400:]).float().mean().item()
def log_run(cfg, acc, root="runs"):
X, y = make_data()
record = {"config": asdict(cfg), "val_acc": round(acc, 4),
"data_sha256": hashlib.sha256(X.tobytes() + y.tobytes()).hexdigest()[:12],
"torch": torch.__version__, "time": time.strftime("%Y-%m-%d %H:%M:%S")}
Path(root).mkdir(exist_ok=True)
with open(f"{root}/runs.jsonl", "a") as f:
f.write(json.dumps(record) + "\n")
return record
print(train(Config(seed=0)), train(Config(seed=0))) # same seed -> same number
accs = [train(Config(seed=s)) for s in range(10)]
print("seeds 0-9:", [round(a, 3) for a in accs])
print(f"mean {np.mean(accs):.3f} std {np.std(accs):.3f}")
print(log_run(Config(seed=0), accs[0]))
# 0.9599999785423279 0.9599999785423279
# seeds 0-9: [0.96, 0.955, 0.975, 0.965, 0.95, 0.96, 0.96, 0.965, 0.96, 0.94]
# mean 0.959 std 0.009
# {'config': {'seed': 0, 'lr': 0.05, 'hidden': 16, 'epochs': 30}, 'val_acc': 0.96,
# 'data_sha256': 'b12733508fe0', 'torch': '2.15.0', 'time': '2026-11-30 14:06:29'}
The same experiment with MLflow (pip install mlflow), reusing Config and train from above. Runs are stored in a local mlflow.db file, and mlflow ui opens the dashboard in a browser:
import mlflow
from dataclasses import asdict
mlflow.set_experiment("circle-classifier")
for hidden in (16, 32):
for seed in range(5):
cfg = Config(seed=seed, hidden=hidden)
with mlflow.start_run(run_name=f"h{hidden}-s{seed}"):
mlflow.log_params(asdict(cfg))
mlflow.log_metric("val_acc", train(cfg))
runs = mlflow.search_runs(experiment_names=["circle-classifier"])
print(runs.groupby("params.hidden")["metrics.val_acc"].agg(["mean", "std", "count"]))
# mean std count
# params.hidden
# 16 0.961 0.009618 5
# 32 0.964 0.008216 5
Weights & Biases looks almost the same: wandb.init(project=..., config=asdict(cfg)), then wandb.log({"val_acc": acc}).
Common pitfalls
- Seeding only one library. NumPy is seeded but PyTorch is not, or the data loader's worker processes get their own unseeded generators. Results then differ for no visible reason.
- Comparing single runs. A one-point gain from one seed each is often noise. Run several seeds before you trust a difference, and report the mean and spread.
- Untracked data changes. Someone fixes labels in the shared CSV, and every old result silently stops being reproducible. Hash or version the data, and log the version with the run.
- Settings hidden in code. A learning rate edited in place, a filter added in a notebook cell and never committed. If it isn't in the config or the commit, it didn't happen.
- Tuning on the test set. Fifty tracked runs, then picking the one with the best test score, is tuning on the test set. Choose with a validation set, and look at the test set once at the end (Training, Validation and Test Sets).
- Logging too little, or too much. Too little and you can't rebuild the run. Logging every tensor every step fills disks and buries the signal. Log configs, scalars per step or epoch, and final artifacts.
Watch out Bit-identical reproducibility on GPUs is not guaranteed by default, and never across different hardware or library versions. Aim for statistical reproducibility: the same config gives the same result within the known seed variance. Keep the exact environment of any model you ship.
Where it leads
- Hyperparameter Tuning runs dozens or hundreds of tracked experiments automatically. Without tracking it is unmanageable.
- Data Pipelines and Datasets goes deeper into versioning and validating the data side.
- Deploying Models takes a registered model version and serves it.
- For LLM applications, the same idea applies to prompts: version each prompt and log its evaluation scores (Evaluating LLM Applications).
A bit of history
Researchers have kept lab notebooks for centuries, and "reproducible research" became a slogan in computational science in the 1990s. Machine learning caught up later. Around 2017–2018 a series of papers showed how fragile reported results were. Henderson and colleagues' 2018 study showed that deep reinforcement learning results could swing with the random seed alone. At the same time, tools appeared to make tracking automatic. Weights & Biases was founded in 2017. Databricks released MLflow as open source in 2018. DVC grew out of the same period. Major ML conferences such as NeurIPS later introduced reproducibility checklists for submitted papers. Today a tracker is a standard part of any serious training setup.
Try it
- Run the first script, then delete
torch.manual_seedfromset_seed. Run it twice. Do the twotrain(Config(seed=0))calls still agree?- Extend the seed study to
hidden=4andhidden=64. Which differences are larger than the seed spread?- Change one label in
make_data(for exampley[0] = 1 - y[0]) and check thatdata_sha256changes completely.Hint for 2: a rough rule is that a difference in means smaller than the standard deviation of single runs needs many more seeds to confirm.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
MLflow documentation
The open-source tracker: log parameters, metrics and artifacts, compare runs in a web UI, and register model versions.
PyTorch: Reproducibility
The official note on seeding, deterministic algorithms and what PyTorch can and cannot guarantee.
Made With ML
How to design, develop, deploy and iterate on ML systems in production.
Weights & Biases
A hosted experiment tracker with live dashboards, sweeps and reports, widely used in deep learning research.
DVC (Data Version Control)
Version large data files and models next to git, and define pipelines that rerun only what changed.
Hydra
A framework for hierarchical configuration files with command-line overrides and multi-run sweeps.
Deep Reinforcement Learning that Matters
Shows how random seeds, code bases and reporting choices change deep RL results, and argues for careful, reproducible evaluation.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/mlops/experiment-tracking.md