Sub topic 4
Making runs reproducible
This chapter assumes you can write Python dataclasses and use scikit-learn. It also assumes you know the pipeline from earlier chapters: a frozen TrainConfig, stage functions, and a run_pipeline function with an evaluation gate. Here you will control the four things that decide a run's result: the code, the configuration, the data, and the environment.
What reproducible means
A run is reproducible when someone can repeat it later, from recorded information alone, and get the same result. There are two levels of "same":
- Bitwise reproducibility: The same inputs give identical predictions and metrics. This is realistic for scikit-learn on one machine and one library version.
- Statistical reproducibility: The metrics fall within normal noise, but the weights differ in the last digits. This is often the best you can get with GPU training, multithreaded reductions, or different hardware.
Decide which level you need before you start. Bitwise equality is what makes a regression test cheap. Statistical equality needs tolerances and repeated runs. Most pipelines should aim for bitwise on small, CPU-based stages and document where they accept less.
A run is a function of four inputs:
| Input | What changes it | Control |
|---|---|---|
| Code | Edits to stage functions | Git commit hash |
| Configuration | Hyperparameters, split size, seed | Frozen dataclass and fingerprint |
| Data | New rows, relabeling, schema changes | Data version or content hash |
| Environment | Library, Python, OS, hardware | Pinned dependencies and a recorded snapshot |
If you record all four, you can explain any result. If you lose one, you cannot tell why two runs differ.
Control randomness with one seed
Randomness enters a training pipeline in several places: the train/test split, model initialization, bootstrap sampling in ensembles, shuffling between epochs, and data augmentation. Each source needs a fixed seed, and the seed should come from the configuration, not from a literal buried in a stage.
The earlier pipeline already does this. split passes cfg.seed as random_state, and train passes it to RandomForestClassifier. Two habits keep that discipline as the pipeline grows.
Pass seeds explicitly
Prefer passing a seed or a generator into each component over relying on global state. Scikit-learn estimators take random_state, and NumPy provides default_rng. Global seeding with np.random.seed still matters for libraries that read the global generator, so a small helper that covers both is useful:
import os
import random
import numpy as np
def seed_everything(seed: int) -> np.random.Generator:
"""Seed the global generators and return a local generator."""
random.seed(seed)
np.random.seed(seed)
return np.random.default_rng(seed)Call it once at the start of run_pipeline. Treat the global seeding as a safety net and pass the returned generator or cfg.seed to the code that you own.
Derive child seeds, do not reuse one
If two components share the same seed, their random streams can be correlated. For example, a bootstrap sample and a feature subsample may repeat the same pattern. NumPy's SeedSequence derives independent child seeds from one root:
import numpy as np
root = np.random.SeedSequence(42)
split_seed, model_seed = [int(s.generate_state(1)[0]) for s in root.spawn(2)]
print(split_seed, model_seed)The children are the same on every run because the root is fixed. Changing the root changes both. This keeps the single seed field in TrainConfig while avoiding accidental coupling.
Know what a seed does not cover
PYTHONHASHSEED: This affects the iteration order of sets and the hashes of strings. It is read when the interpreter starts. Settingos.environ["PYTHONHASHSEED"]inside a running script has no effect on that process. Set it in the launch command or CI job instead.- Parallelism: Code that sums floating-point numbers in a different order gives slightly different results, because floating-point addition is not associative. Scikit-learn's random forest gives the same result for any
n_jobs, but many libraries do not. - GPUs: Some CUDA kernels are nondeterministic by default. In PyTorch you can call
torch.use_deterministic_algorithms(True)and setCUBLAS_WORKSPACE_CONFIG=:4096:8. This can slow training, and some operations then raise an error because they have no deterministic version. - Worker processes: Data loaders that use several worker processes need per-worker seeding, or each worker may augment data in a way you cannot replay.
Version the data
Seeds only help if the data is the same. Data drifts in quiet ways: a table gets new rows, a labeling pass fixes errors, a column changes type, or a file is overwritten in place. A configuration that says dataset: train.csv does not identify the data.
You have three practical options, from lightest to heaviest:
- Content hash: Compute a hash of the data and record it with every run. This detects change but does not let you recover the old version.
- Immutable snapshots: Write each data version to a new path, such as a dated folder or an object-store key that is never overwritten, and record the path.
- Data version control: Use a tool such as DVC or lakeFS, which track large files by hash alongside your Git history.
The content hash costs almost nothing and is worth doing even if you also use option 2 or 3. For files, hash in chunks so large files do not need to fit in memory. For arrays already in memory, include the dtype and shape, because the same bytes can mean different arrays:
import hashlib
from pathlib import Path
import numpy as np
def file_fingerprint(path: str) -> str:
h = hashlib.sha256()
with Path(path).open("rb") as f:
for chunk in iter(lambda: f.read(1 << 20), b""):
h.update(chunk)
return h.hexdigest()[:12]
def array_fingerprint(*arrays: np.ndarray) -> str:
h = hashlib.sha256()
for a in arrays:
a = np.ascontiguousarray(a)
h.update(str(a.dtype).encode())
h.update(str(a.shape).encode())
h.update(a.tobytes())
return h.hexdigest()[:12]In our example, load_iris ships inside scikit-learn, so the data version is tied to the library version. That is why the environment snapshot below matters even for a toy dataset. For a real project, fingerprint the data you load and also record where it came from, such as a table name and a snapshot date.
Also watch for data that changes inside the pipeline. A query like SELECT * FROM events WHERE ts > now() - interval '30 days' returns different rows tomorrow. Pass an explicit cutoff date through the configuration instead, so the same configuration selects the same rows.
Pin and record the environment
The same code and data can give different results under different library versions. Default hyperparameters change between releases, solvers are rewritten, and numerical libraries update their kernels. Two layers of control help:
- Pin dependencies. Put exact versions in a lock file, such as
requirements.txtgenerated withpip freeze, or the lock file fromuv, Poetry, or conda. A range likescikit-learn>=1.3is not a pin. Direct dependencies are not enough either, because transitive ones (such as the version ofnumpythatscikit-learnpulls in) also change results. - Record what actually ran. The lock file says what you intended. A snapshot taken at run time says what you got. Store the Python version, platform, and the versions of the packages that matter.
import importlib.metadata as md
import platform
def environment_snapshot(
packages: tuple[str, ...] = ("numpy", "scikit-learn"),
) -> dict:
return {
"python": platform.python_version(),
"platform": platform.platform(),
"packages": {name: md.version(name) for name in packages},
}For a stronger guarantee, build a container image from the lock file and run the pipeline in that image. The image tag or digest then identifies the whole environment, including system libraries that a Python lock file cannot see.
Write a run manifest
A manifest is a small JSON document that stores the four inputs and the outputs of a run. It is the minimum record that makes a run explainable. A later chapter covers dedicated tracking tools. The manifest here is tool-independent and is what you would send to one.
The next example assumes the code from earlier chapters is saved in a module named pipeline.py, with TrainConfig, config_fingerprint, load_data, split, train, evaluate, and run_pipeline defined there. Save the new helpers above as repro.py.
import dataclasses
import json
import subprocess
from pipeline import TrainConfig, config_fingerprint, load_data, run_pipeline
from repro import array_fingerprint, environment_snapshot
def git_commit() -> str:
try:
out = subprocess.run(
["git", "rev-parse", "HEAD"],
capture_output=True, text=True, check=True,
)
return out.stdout.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown"
def build_manifest(cfg: TrainConfig, metrics: dict) -> dict:
X, y = load_data()
return {
"code_commit": git_commit(),
"config": dataclasses.asdict(cfg),
"config_fingerprint": config_fingerprint(cfg),
"data_fingerprint": array_fingerprint(X, y),
"environment": environment_snapshot(),
"metrics": metrics,
}
if __name__ == "__main__":
cfg = TrainConfig()
_, metrics = run_pipeline(cfg)
print(json.dumps(build_manifest(cfg, metrics), indent=2))Two details deserve attention. First, the commit hash only describes the code if the working tree is clean. If you have uncommitted edits, the hash is misleading. Record a dirty flag from git status --porcelain, or refuse to run in CI when the tree is dirty. Second, the manifest stores the full configuration as well as its fingerprint. The fingerprint is for fast comparison and naming, and the full values are for reading.
Test reproducibility
Reproducibility that is not tested decays. The pipeline already has one test that runs twice and compares metrics. That test can pass even when two models differ, because accuracy on a small test set is coarse. A stronger check compares the model's predicted probabilities:
import numpy as np
from pipeline import TrainConfig, load_data, split, train
def test_same_seed_gives_identical_probabilities():
cfg = TrainConfig()
X, y = load_data()
X_train, X_test, y_train, _ = split(X, y, cfg)
p1 = train(X_train, y_train, cfg).predict_proba(X_test)
p2 = train(X_train, y_train, cfg).predict_proba(X_test)
np.testing.assert_array_equal(p1, p2)
def test_different_seed_changes_the_split():
X, y = load_data()
a = split(X, y, TrainConfig(seed=1))[1]
b = split(X, y, TrainConfig(seed=2))[1]
assert not np.array_equal(a, b)The second test guards against the opposite failure: a seed that is silently ignored. If the test fails, the seed is not reaching the splitter. Run these tests in a fresh process in CI, because a test run that shares a process with other tests may share global random state with them.
For bitwise-unreachable stages, replace assert_array_equal with np.testing.assert_allclose and a tolerance you can justify, for example rtol=1e-5.
Common errors
- Seeding only the model. The split also uses randomness, and a different split changes the metrics more than a different model seed does.
- Seeding after the random call. Seeding must happen before the first draw. A helper called in
maindoes nothing for a dataset shuffled at import time. - Unpinned transitive dependencies. Direct pins pass review, and a transitive upgrade changes the numbers anyway.
- Hashing the path instead of the content. The path stays the same when a file is overwritten.
- Treating "works on my machine" as reproducible. Run it once on a clean machine or in CI before you trust it.
- Recording the fingerprint but not the configuration. A hash cannot be reversed to tell you which value changed.
- Letting time leak in.
datetime.now(), unordered file listings, and unsorted dictionary or set iteration all change the run without any input changing. Sort what you list and pass dates in as configuration.
Exercise
Your teammate reruns last month's training with the same TrainConfig and the same code commit, and the accuracy is 0.93 instead of 0.96. Name three things in the run manifest you would compare first, and say what each would reveal.
Show answer
Compare the data fingerprint (it shows whether the training data changed, for example through new rows or overwritten files), the environment snapshot (it shows library or Python version changes, such as a new scikit-learn default or solver), and the code commit with its dirty flag (it shows whether uncommitted edits ran under the same hash). The configuration fingerprint is already known to match, so it is the least informative.
Exercise
A test runs run_pipeline twice with the same configuration and asserts that the accuracy is equal. It passes, but a reviewer says the test is weak. Give one way the test could pass while the two runs differ, and write the stronger assertion.
Show answer
Accuracy on a small test set takes few distinct values, so two models with different internals can still score the same. Compare predict_proba outputs on the same test split instead: np.testing.assert_array_equal(p1, p2). For stages that cannot be bitwise equal, use np.testing.assert_allclose with an explicit tolerance.