Sub topic 6
Making training runs reproducible
This chapter assumes you can train and evaluate a supervised model in Python and use basic Git. You should also know the experiment-tracking idea from the previous chapters: a run is one recorded training execution. Here you will learn what must be pinned so that a run can be repeated, and how to check that it was.
What reproducible means
A training run is reproducible when someone else, or you in six months, can rerun it from its record and get the same model, or a model within a stated tolerance. The record needs to name four inputs:
- Code: the exact commit, including any uncommitted changes.
- Data: the exact rows and labels used, not "the latest table".
- Environment: Python version, library versions, and hardware or system libraries where they matter.
- Randomness: every seed that influences splitting, initialization, shuffling and sampling.
If any one of these is missing, a changed result has no explanation. You cannot tell whether the model got better or the data moved underneath you.
Pinning code
Record the commit hash with every run. A hash alone is misleading when the working tree has uncommitted edits, so also record whether the tree was dirty. Many teams make the training job refuse to run, or tag the run, when the tree is dirty.
Notebooks are a common source of hidden state. Cells run out of order, or run only once, produce results that no file reproduces. Move training logic into modules that a script or pipeline calls, and use the notebook only to explore.
Pinning data
Data is usually the hardest input to pin, because it changes in place. There are three common approaches:
| Approach | How it works | Trade-off |
|---|---|---|
| Content hash | Compute a hash of the training file or table and log it | Detects change but does not restore the old data |
| Immutable snapshots | Write each training set to a new, never-overwritten path or version | Uses more storage, but restoring is trivial |
| Data version control | Tools such as DVC or lakeFS track data versions next to Git commits | Adds tooling, but links code and data versions directly |
A hash is the minimum. A snapshot or versioning tool is what lets you rebuild the run. For tables queried from a warehouse, record the query text and the snapshot or timestamp it ran against, since the same query can return different rows tomorrow.
Also pin the split. If you split with a fixed seed, the split still changes whenever the input rows change or are reordered. For long-lived projects, store the train and test row identifiers, or split by a stable hash of an ID column.
Pinning the environment
"Works on my machine" is an environment problem. Pin versions with a lock file: pip freeze, pip-tools, poetry.lock or conda-lock. A requirements.txt that says scikit-learn>=1.0 is not a pin. Library upgrades change defaults, solvers and numerical results.
For stronger guarantees, build a container image from the lock file and record the image digest, not the mutable tag latest. A digest names exactly one image. For GPU training, the CUDA and driver versions belong in the record too.
Controlling randomness
Seed every random number generator the pipeline uses. This usually means Python's random, NumPy, and the framework (torch.manual_seed or tf.random.set_seed). Pass random_state to scikit-learn estimators and splitters.
A seed does not guarantee identical results everywhere. Known sources of residual variation:
- GPU kernels that use non-deterministic algorithms, such as some atomic-add reductions. PyTorch offers
torch.use_deterministic_algorithms(True), which can slow training or raise errors for unsupported operations. - Multi-threaded or distributed training, where the order of floating-point summation varies between runs.
- Data loaders with several worker processes, each needing its own seed.
- Different CPU architectures or library builds, which change floating-point rounding.
Because exact equality is not always possible, decide what "the same" means. For a deterministic CPU pipeline you can require identical outputs. For GPU deep learning, a common rule is to run the job several times and require the metric to stay within a tolerance, such as the observed spread across seeds. This spread is also useful evidence when you compare two models: a 0.2-point gain is meaningless if reruns vary by 0.5.
Recording everything in one run
The example below combines the four inputs. It hashes the training data, reads the Git commit and dirty flag, logs library versions, seeds the generators, then trains and logs the result. It then trains a second model with the same inputs and checks that the two are identical.
import hashlib
import random
import subprocess
from importlib.metadata import version
import mlflow
import numpy as np
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
SEED = 42
def data_fingerprint(X, y):
digest = hashlib.sha256()
digest.update(np.ascontiguousarray(X).tobytes())
digest.update(np.ascontiguousarray(y).tobytes())
return digest.hexdigest()[:16]
def git_state():
try:
commit = subprocess.check_output(
["git", "rev-parse", "HEAD"], text=True, stderr=subprocess.DEVNULL
).strip()
dirty = bool(
subprocess.check_output(
["git", "status", "--porcelain"], text=True, stderr=subprocess.DEVNULL
).strip()
)
return commit, dirty
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown", True
def train(X, y):
random.seed(SEED)
np.random.seed(SEED)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=SEED
)
model = LogisticRegression(C=1.0, max_iter=200, random_state=SEED)
model.fit(X_train, y_train)
return model, model.score(X_test, y_test)
X, y = load_iris(return_X_y=True)
commit, dirty = git_state()
with mlflow.start_run():
model, accuracy = train(X, y)
mlflow.log_params(
{
"seed": SEED,
"git_commit": commit,
"git_dirty": dirty,
"data_hash": data_fingerprint(X, y),
"sklearn_version": version("scikit-learn"),
"numpy_version": version("numpy"),
}
)
mlflow.log_metric("accuracy", accuracy)
model_again, accuracy_again = train(X, y)
assert np.array_equal(model.coef_, model_again.coef_)
assert accuracy == accuracy_again
print("Reproduced:", accuracy)The final assertions are a cheap reproducibility test. Teams often run such a check in continuous integration on a small data sample, so a change that breaks determinism is caught early.
Common errors
- Seeding only the split. The model initialization, shuffling or sampling still varies between runs.
- Unpinned transitive dependencies. You pinned
scikit-learnbut notnumpyorscipy, which also affect results. - Mutable data paths. A job reads
data/train.csv, and someone overwrites that file. - Comparing runs across environments. A small metric difference may come from a library upgrade rather than your change.
- Treating one rerun as proof. Run several seeds to learn the normal spread before trusting a small difference.
Exercise
A teammate reports that rerunning last month's logged run, with the same seed and the same Git commit, gives accuracy 0.91 instead of the logged 0.94. Name three inputs you would check first and what to look for in each.
Show answer
Check the data first: compare the logged data hash with the hash of the data the rerun read, since an overwritten or reordered table changes both the training rows and the seeded split. Check the environment next: compare the logged library versions, or lock file, with the current ones, because an upgraded library can change defaults or solvers. Check the Git state last: the commit may match while the working tree was dirty at the original run, or at the rerun. Also check whether the pipeline has unseeded randomness, such as data loader workers or non-deterministic GPU operations. Compare against the metric's normal spread across seeds before concluding something broke.