TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Reproducible Training Runs

Reproducible Training Runs

A regulator asks how the credit model that rejected an applicant in March was built. A colleague cannot reproduce your 0.93 and wonders whether the improvement is real. A model in production misbehaves and you want to retrain last month's version with one bug fixed and nothing else changed. All three need the same capability: run the training again and get the same model, or know precisely why not. This lesson collects the sources of nondeterminism in training and the controls for each, and separates two goals that are often confused: getting the same bits and getting the same conclusion.

Two kinds of reproducibility

  • Bitwise reproducibility: same code, data, environment and seeds give byte-identical weights and predictions. Useful for debugging, audits and caching (pipelines skip stages whose inputs did not change, which only makes sense if the stage is deterministic). Achievable on one machine type with care; across different hardware, library builds or GPU models it is often impossible or too slow.
  • Statistical reproducibility: a rerun, even with other seeds or hardware, gives results from the same distribution, so the conclusion ("model B beats model A by about 2 points") holds. This is what science and model selection need, and it is measured by repeating runs with several seeds and reporting the spread.

The first is a property of a pipeline; the second is a property of a claim. A result that only appears with seed 0 is bitwise reproducible and statistically meaningless.

Sources of nondeterminism

Source Example Control
Random seeds initialisation, dropout, bootstrap samples in a forest, data shuffling, the train/test split set every seed, pass generators explicitly, log them
Data the file was refreshed, rows come back from a database in another order, a sample was redrawn versioned snapshots (DVC), a content hash, sort before use
Order of operations floating-point addition is not associative; parallel reductions add in varying order deterministic algorithms, fixed thread counts, stable sorts
Threads and hardware multi-threaded BLAS, GPU atomics, different CPU instruction sets (AVX2 vs AVX-512) pin thread counts, deterministic modes, same instance type
Library versions a changed default (solver, tolerance), a bug fix, a different BLAS build lockfiles, container images pinned by digest
Hidden state notebook cells run out of order, a global RNG consumed by an earlier call, Python's string hash seed changing set iteration order scripts run from scratch, explicit generators, PYTHONHASHSEED fixed
The outside world the current date in a feature, an API call during training, a download of "latest" weights pass dates as parameters, snapshot external data, pin model revisions

Seeds: same seed, same bits

The running example (2,000 synthetic rows, 8 features, a 75/25 split, 500 test rows) with a random forest, whose bootstrap samples and feature choices are random. The fingerprint is the SHA-256 of the test-set probabilities, so "identical" means bitwise identical outputs.

python · try it yourself
import hashlib
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier

X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)

def train(split_seed, model_seed):
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, stratify=y, random_state=split_seed)
    model = RandomForestClassifier(n_estimators=50, max_features="sqrt", random_state=model_seed).fit(X_tr, y_tr)
    proba = model.predict_proba(X_te)[:, 1]
    fingerprint = hashlib.sha256(proba.tobytes()).hexdigest()[:12]   # bitwise identity of the outputs
    return fingerprint, (proba.round() == y_te).mean()

a, b = train(0, 0), train(0, 0)
print(f"seeds fixed, run twice:    {a[0]} {b[0]}  identical: {a[0] == b[0]}")
c, d = train(0, None), train(0, None)
print(f"model seed None, twice:    identical: {c[0] == d[0]}")
e, f = train(None, 0), train(None, 0)
print(f"split seed None, twice:    identical: {e[0] == f[0]}")

accs = np.array([train(0, s)[1] for s in range(10)])
print(f"10 model seeds, same split: accuracy mean {accs.mean():.4f}, sd {accs.std(ddof=1):.4f}, "
      f"range {accs.min():.3f}..{accs.max():.3f}")
accs = np.array([train(s, s)[1] for s in range(10)])
print(f"10 split+model seeds:       accuracy mean {accs.mean():.4f}, sd {accs.std(ddof=1):.4f}, "
      f"range {accs.min():.3f}..{accs.max():.3f}")
seeds fixed, run twice:    02bf7f9f98f7 02bf7f9f98f7  identical: True
model seed None, twice:    identical: False
split seed None, twice:    identical: False
10 model seeds, same split: accuracy mean 0.9340, sd 0.0039, range 0.928..0.938
10 split+model seeds:       accuracy mean 0.9272, sd 0.0092, range 0.912..0.940

With both seeds fixed, two runs give the same fingerprint 02bf7f9f98f7: bitwise reproducible. Leave either seed as None (scikit-learn then draws fresh randomness) and the outputs differ. The split seed matters as much as the model seed: it decides which 500 rows are the test set.

The last two lines are the statistical view. Over 10 model seeds on one split, test accuracy ranges from 0.928 to 0.938 (sd 0.0039); when the split changes too, the range widens to 0.912..0.940 (sd 0.0092). So a claim that a change improved accuracy by 0.005, measured with one seed and one split, is within the noise of this setup. Report the mean and spread over several seeds and splits (cross-validation is the systematic version), and keep the seeds in the run record.

Seeds to set in a typical Python training script: random.seed, np.random.seed (for libraries that use NumPy's global generator), the generators you create (np.random.default_rng(seed), passed explicitly), every scikit-learn random_state, and in PyTorch torch.manual_seed plus the data loader's generator and worker seeds; Checkpoints and Reproducibility covers PyTorch's deterministic mode (torch.use_deterministic_algorithms(True)) and GPU-specific settings.

Order effects: same data, same seed, different result

Seeds are not enough when the order of computation changes. Floating-point addition rounds after every step, so the sum depends on the order of the terms. Parallel code (multi-threaded BLAS, GPU reductions) may add in a different order on every run, and a different row order changes every step of stochastic gradient descent.

python · try it yourself
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import SGDClassifier

x = np.random.default_rng(0).standard_normal(1_000_000).astype(np.float32)
print("float32 sum, original order:", repr(float(x.sum())))
print("float32 sum, reversed order:", repr(float(x[::-1].sum())))
print("float32 sum, sorted order:  ", repr(float(np.sort(x).sum())))
print("float64 sum:                ", repr(float(x.astype(np.float64).sum())))
print("(0.1 + 0.2) + 0.3 == 0.1 + (0.2 + 0.3):", (0.1 + 0.2) + 0.3 == 0.1 + (0.2 + 0.3))

X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, random_state=0)
X_tr, y_tr, X_te, y_te = X[:1500], y[:1500], X[1500:], y[1500:]
perm = np.random.default_rng(1).permutation(1500)          # the same rows, read in another order
m1 = SGDClassifier(loss="log_loss", shuffle=False, random_state=0).fit(X_tr, y_tr)
m2 = SGDClassifier(loss="log_loss", shuffle=False, random_state=0).fit(X_tr[perm], y_tr[perm])
print(f"SGD, same seed, rows in another order: max |coef difference| {np.abs(m1.coef_ - m2.coef_).max():.3f}")
print(f"  test accuracy {m1.score(X_te, y_te):.3f} vs {m2.score(X_te, y_te):.3f}, "
      f"predictions differ on {(m1.predict(X_te) != m2.predict(X_te)).sum()} of {len(y_te)} rows")
float32 sum, original order: 998.5707397460938
float32 sum, reversed order: 998.5708618164062
float32 sum, sorted order:   998.5911865234375
float64 sum:                 998.5706627697155
(0.1 + 0.2) + 0.3 == 0.1 + (0.2 + 0.3): False
SGD, same seed, rows in another order: max |coef difference| 0.279
  test accuracy 0.850 vs 0.838, predictions differ on 38 of 500 rows

The same million float32 numbers sum to 998.5707 in their original order, 998.5709 reversed and 998.5912 sorted; in float64 the sum is 998.57066. The differences are in the 4th to 5th significant digit, tiny for one sum but enough to flip a comparison, take a different branch in a tree split, and grow through thousands of training steps. That is why the same code on a different number of threads or a different GPU can give a slightly different model with every seed fixed.

The SGD example makes the effect visible: same rows, same seed, shuffle=False, only the row order differs, and the coefficients differ by up to 0.279; 38 of 500 test predictions change and accuracy moves from 0.850 to 0.838. Data order is an input. Rows read from a database without ORDER BY, files listed with os.listdir (arbitrary order), or a parallel data loader without a fixed generator all change it silently. Sort by a key before training, or shuffle with a recorded seed.

The browser runs these examples on one thread, so thread effects cannot be shown here. In production training, pin thread counts (OMP_NUM_THREADS, MKL_NUM_THREADS, or threadpoolctl), and for GPUs see the deep-learning lesson linked above.

Capturing the environment and the data

Two more inputs must be pinned: the environment (Python and every package, exactly) and the data (by content, not by file name).

  • Lockfiles list every package with an exact version and ideally a hash: requirements.txt produced by pip-compile --generate-hashes or uv pip compile, uv.lock, poetry.lock, conda-lock.yml. A file with scikit-learn>=1.3 is a wish, not a lock. (Hash pinning explains the hash part.)
  • Container images add the operating system and system libraries (BLAS, CUDA). Refer to them by digest (image@sha256:...), not by a tag like latest that moves (Docker Images for Model Services).
  • Data snapshots: a DVC version, a table snapshot id, or at least a content hash of what was read, recorded with the run.
  • Hardware: CPU model and GPU type in the run record, because they explain small numeric differences.

The last example records a manifest (seed, data hash, Python and package versions) and compares a later run against it, the way a training script can refuse to start, or warn, when it is not reproducing what it claims to reproduce.

python · try it yourself
import hashlib, json, platform, random
import numpy as np, pandas as pd, sklearn

def set_seeds(seed):
    random.seed(seed)
    np.random.seed(seed)                     # legacy global state, still used by some libraries
    return np.random.default_rng(seed)       # pass this generator explicitly where you can

def snapshot(seed, data: pd.DataFrame):
    return {"seed": seed,
            "data_sha256": hashlib.sha256(pd.util.hash_pandas_object(data, index=True).values.tobytes()).hexdigest()[:12],
            "python": platform.python_version(),
            "packages": {"numpy": np.__version__, "pandas": pd.__version__, "scikit-learn": sklearn.__version__}}

def compare(recorded, now):
    problems = []
    for key in ("seed", "data_sha256", "python"):
        if recorded[key] != now[key]:
            problems.append(f"{key}: recorded {recorded[key]}, now {now[key]}")
    for pkg, ver in recorded["packages"].items():
        if now["packages"].get(pkg) != ver:
            problems.append(f"{pkg}: recorded {ver}, now {now['packages'].get(pkg)}")
    return problems or ["environment matches the recorded run"]

rng = set_seeds(42)
df = pd.DataFrame({"income": rng.normal(50, 15, 500).round(1), "debt_ratio": rng.uniform(0, 1, 500).round(3)})
manifest = snapshot(42, df)
print(json.dumps({k: manifest[k] for k in ("seed", "data_sha256")}), "| packages:", sorted(manifest["packages"]))

print("same data, same environment:", compare(manifest, snapshot(42, df)))
edited = df.copy(); edited.loc[17, "income"] += 0.1            # one value changed by 0.1
old_env = json.loads(json.dumps(manifest)); old_env["packages"]["scikit-learn"] = "1.5.2"
for line in compare(old_env, snapshot(42, edited)):
    print("  mismatch ->", line)
{"seed": 42, "data_sha256": "6618c7e9832d"} | packages: ['numpy', 'pandas', 'scikit-learn']
same data, same environment: ['environment matches the recorded run']
  mismatch -> data_sha256: recorded 6618c7e9832d, now aaf54aed7224
  mismatch -> scikit-learn: recorded 1.5.2, now 1.7.0

The manifest's data hash (6618c7e9832d) covers every value and the index, so changing a single income by 0.1 changes it (aaf54aed7224), and the check also reports that the recorded run used scikit-learn 1.5.2 while this environment has 1.7.0. Either mismatch means the rerun is not a reproduction, and the report says which input moved. pd.util.hash_pandas_object hashes values row by row; reordering rows changes the hash, which is what you want here, since row order affects training.

A reproducibility checklist

  1. Code: a commit, and no uncommitted changes (check git status in the script).
  2. Data: a versioned snapshot or content hash per input, and the split definition (seed or explicit ids).
  3. Environment: a lockfile and a container image by digest; record hardware.
  4. Seeds: all of them, passed explicitly, recorded.
  5. Order: sort inputs by a key; fix thread counts; use deterministic algorithms where they exist.
  6. Outside world: no "now", no network during training; dates and external data are parameters and snapshots.
  7. Verify: rerun a training occasionally (in CI on a small sample, see CI/CD) and compare fingerprints; for claims, run several seeds.

Pitfalls

  • One seed, one claim. A difference smaller than the seed-to-seed spread is not a result.
  • Seeding only NumPy. Python's random, scikit-learn's random_state=None, the framework's generator, and data-loader workers each have their own randomness.
  • Bitwise equality as a test across machines. A test that compares weights exactly will fail on another CPU or GPU; compare predictions with a tolerance or metrics within a band, and keep exact checks for same-machine pipelines.
  • Unpinned transitive dependencies. Pinning scikit-learn but not numpy or scipy still lets results drift.
  • Deterministic but wrong. Fixing a seed hides variance; it does not make the model better. Choose seeds before looking at results, never by trying seeds until the test score is good.

Practice

  1. In the first example, why does leaving only the split seed unset change the fingerprint, although the model seed is fixed?
  2. A teammate reports that the new feature improves accuracy from 0.931 to 0.936, from one run each. Using the spread from the example, what do you ask for?
  3. Two training runs on the same commit, data snapshot and seeds give slightly different weights on two machines. Name two likely causes.
Answers
  1. The split seed decides which rows go to training and to test. Different training rows give a different forest and different test rows give different probabilities, so the fingerprint of the outputs changes.
  2. The improvement (0.005) is about the size of the seed-to-seed spread (sd 0.0039 with one split, 0.0092 with varying splits). Ask for several seeds and splits (or cross-validation) for both versions and compare the distributions, ideally paired by seed.
  3. A different order of floating-point operations: different thread counts or CPU instruction sets in BLAS, or nondeterministic GPU kernels. Also possible: a different library build or version if the environment was not pinned by digest.

Test yourself

What is the difference between bitwise and statistical reproducibility?

  1. None
  2. Bitwise: identical bytes from a rerun; statistical: reruns (possibly with other seeds or hardware) support the same conclusion
  3. Bitwise is for deep learning only
  4. Statistical means rounding the output

The same million float32 values summed in a different order gave a different result. Why?

  1. A bug in NumPy
  2. Floating-point addition rounds at every step and is not associative, so the order changes the result
  3. The random seed changed
  4. float32 cannot represent sums

Which of these does NOT pin the training environment exactly?

  1. A lockfile with exact versions and hashes
  2. A container image referenced by its sha256 digest
  3. A requirements file with scikit-learn>=1.3
  4. A recorded list of exact package versions checked at start-up

SGD with the same seed and shuffle=False was trained on the same rows in two different orders. What happened?

  1. Identical models
  2. Different coefficients and 38 of 500 test predictions changed
  3. An error
  4. Only the intercept changed