Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 15 min · revision 2

Why Results Become Unrepeatable

Run small scripts that show where repeatability is lost: unfixed seeds, the spread one seed change causes, floating-point addition order, Python hash randomisation and set order, and a dependency list that resolves to different versions on different days, then name what still varies on GPUs.

Contentsand lesson path

On this page

  1. Why it matters
  2. Randomness you did not fix
  3. Order changes the numbers
  4. The environment drifts
  5. Check your understanding
  6. Apply it
  7. Review prompt

Lessons of Experiment Tracking & Reproducibility

  1. Why Results Become Unrepeatable Concept · 15 min
  2. Lab: Track and Compare Runs Lab · 25 min
  3. Versioning Data and Models Next to Code Concept · 20 min
  4. Worked Example: Rebuild Last Month's Model from Scratch Worked example · 25 min
  5. Model Registry: Versions, Aliases and Promotion Rules Concept · 15 min
  6. Check: Can You Reproduce It? Knowledge check · 8 questions

What you will learn

  • Reproduce a past run in a clean environment from pinned dependencies, configuration files and fixed seeds, and name the remaining sources of nondeterminism.

01. Why it matters

Last week a model scored 0.951 accuracy. Today the same notebook gives 0.937, and nobody remembers changing anything. Is the new number a bug, a data problem, or noise? Until you can rerun last week's training and get last week's number, you cannot answer, and you cannot tell whether any later change made the model better or worse.

A run is reproducible when someone else, or you later, can repeat it from its recorded inputs and get the same result, or a result within a stated tolerance. A training result depends on more inputs than the script you can see. There are six groups to think about:

  • the code, at an exact version;
  • the data, as exact file contents, not just a file name;
  • the configuration: hyperparameters and options, including defaults and command-line overrides;
  • the environment: Python and every installed library version;
  • the randomness: seeds for splits, initial weights and shuffling;
  • the execution: hardware, thread counts and the order in which numbers are added.

This lesson shows four of these going wrong in scripts that run in seconds. The rest of the skill records all six for every run: with a tracker (the lab after this one), with data versioning (lesson 3) and by rebuilding a past model in a clean environment (lesson 4).

Terminal
mkdir repro-demo && cd repro-demo
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.1" "uv==0.13.8"

02. Randomness you did not fix

Many steps of a training run draw random numbers: the train/test split, the bootstrap samples of a random forest, the initial weights of a network, the order of mini-batches. Each of these uses a pseudo-random number generator, which produces a fixed sequence of numbers from a starting value called the seed. Same seed, same sequence. No seed, and the library picks a fresh one from the operating system, so every run is different.

In scikit-learn you fix the seed with random_state. The script below runs a complete experiment (split, train, score) on the breast cancer dataset that ships with scikit-learn. It runs seed 0 twice, then seeds 0 to 9.

Python · seeds.py
import sys

from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

X, y = load_breast_cancer(return_X_y=True)


def run(seed):
    """One complete run: split, train, score. `seed=None` means 'not fixed'."""
    X_tr, X_te, y_tr, y_te = train_test_split(
        X, y, test_size=0.25, stratify=y, random_state=seed)
    model = RandomForestClassifier(n_estimators=50, random_state=seed)
    return model.fit(X_tr, y_tr).score(X_te, y_te)


if sys.argv[1:] == ["unseeded"]:
    print("unseeded:", [round(run(None), 3) for _ in range(3)])
else:
    print("seed 0, twice:", round(run(0), 3), round(run(0), 3))
    scores = [run(s) for s in range(10)]
    print("seeds 0-9:", [round(s, 3) for s in scores])
    print(f"spread from the seed alone: {min(scores):.3f} to {max(scores):.3f}")
Terminal
python seeds.py
Expected output
seed 0, twice: 0.944 0.944
seeds 0-9: [0.944, 0.937, 0.958, 0.972, 0.972, 0.979, 0.972, 0.965, 0.972, 0.958]
spread from the seed alone: 0.937 to 0.979

With the same seed, the result is identical: 0.944 twice. Across ten seeds, test accuracy moves between 0.937 and 0.979, although the data, code and model settings never changed. The test set has 143 rows, so each extra mistake costs 0.007, and the seed alone decides which rows land in the test set and which trees the forest grows.

That spread is the most useful number in this lesson. A change that moves accuracy by less than the seed-to-seed spread has not been shown to help or hurt; to compare two settings, run both with the same set of several seeds and compare the averages and the spread. Without seeds, you see a different number each time:

Terminal
python seeds.py unseeded
Illustrative output
unseeded: [0.979, 0.965, 0.965]

Your three numbers will differ from these, and from each other: that is the point. Pass the seed explicitly to every function that takes one, or create one generator with NumPy's default_rng(seed) and hand it around. Setting a global seed once at the top of a script is fragile, because any new call that draws from the global generator shifts the numbers for every call after it.

03. Order changes the numbers

Even with every seed fixed, the order of operations can change results. Computers store real numbers as floating-point values with a fixed number of digits, and every addition rounds to the nearest representable value. So floating-point addition is not associative: (a + b) + c can differ from a + (b + c). Training is mostly sums, such as a gradient added up over a batch, so this matters more than it looks.

The script adds one million float32 values (the 32-bit format most deep learning uses) as one worker would, and as 4 or 8 parallel workers would: each worker sums its own slice, then the partial sums are added together.

Python · floatorder.py
import math

import numpy as np

print("(0.1 + 0.2) + 0.3 =", (0.1 + 0.2) + 0.3)
print("0.1 + (0.2 + 0.3) =", 0.1 + (0.2 + 0.3))

rng = np.random.default_rng(0)
x = rng.normal(size=1_000_000).astype(np.float32)   # e.g. one gradient's terms


def parallel_sum(values, workers):
    """Each worker adds its own slice, then the partial sums are added."""
    partials = [np.cumsum(part, dtype=np.float32)[-1]
                for part in np.array_split(values, workers)]
    return float(np.cumsum(partials, dtype=np.float32)[-1])


print(f"exact sum (math.fsum):  {math.fsum(x.astype(np.float64)):.6f}")
for workers in (1, 4, 8):
    print(f"float32, {workers} worker(s): {parallel_sum(x, workers):.6f}")
Terminal
python floatorder.py
Expected output
(0.1 + 0.2) + 0.3 = 0.6000000000000001
0.1 + (0.2 + 0.3) = 0.6
exact sum (math.fsum):  998.570663
float32, 1 worker(s): 998.564270
float32, 4 worker(s): 998.565796
float32, 8 worker(s): 998.566956

The same values give three different totals, all slightly off the exact sum from math.fsum. Nothing is random here: the same worker count gives the same total every time. On a CPU this is why a different number of threads in the maths library (BLAS), or a different CPU, can shift the last digits of a result.

On a GPU the effect is harder to control. Thousands of threads add into shared results, and some fast kernels (the small programs that run on the GPU) let those additions happen in whatever order the threads finish, so two runs on the same machine can differ slightly even with every seed fixed. Libraries also pick among several algorithms for the same operation, by speed. PyTorch documents these limits: torch.use_deterministic_algorithms(True) makes it use deterministic versions of operations or raise an error where none exists, torch.backends.cudnn.benchmark = False stops cuDNN from picking algorithms by timing them, and both can cost speed. Its notes also say that completely reproducible results are not guaranteed across PyTorch releases or platforms. Data loading adds one more source: each data-loader worker process needs its own seed, or the random augmentations in different workers can repeat or change between runs. Across different GPU models or driver versions, bit-identical results are generally not available, so you agree on a tolerance instead.

Python adds its own order effect. String hashes are randomised per process, controlled by the PYTHONHASHSEED environment variable, and the iteration order of a set follows those hashes.

Python · setorder.py
features = {"age", "income", "tenure", "region", "plan"}
print("list(set):", list(features))
print("sorted:   ", sorted(features))
Terminal
PYTHONHASHSEED=1 python setorder.py
PYTHONHASHSEED=2 python setorder.py
Expected output
list(set): ['plan', 'tenure', 'age', 'income', 'region']
sorted:    ['age', 'income', 'plan', 'region', 'tenure']
list(set): ['plan', 'tenure', 'age', 'region', 'income']
sorted:    ['age', 'income', 'plan', 'region', 'tenure']

Without PYTHONHASHSEED, every new process picks its own order. If feature columns are built from a set, two processes can put them in different orders, and a model that receives columns in the wrong order still returns numbers, just wrong ones. Sort anything whose order matters, as sorted does here.

04. The environment drifts

A requirements.txt that says scikit-learn>=1.8 describes a range, not an environment. Which versions you get depends on the day you install, and scikit-learn itself pulls in other packages, its transitive dependencies, such as NumPy and SciPy, whose versions are not written anywhere. A new release can change a default, a solver or a rounding detail, and the metrics move.

A lock file records the exact version of every package, direct and transitive, that one resolution chose. uv pip compile writes one. Its --exclude-newer option ignores releases uploaded after a timestamp, which lets us replay the same resolution as it would have run on two different days.

Text · requirements.in
scikit-learn>=1.8
Terminal
uv pip compile -q requirements.in --exclude-newer 2026-11-01T00:00:00Z -o lock-nov01.txt
uv pip compile -q requirements.in --exclude-newer 2026-11-16T00:00:00Z -o lock-nov16.txt
grep '==' lock-nov01.txt
echo "--- what changed by 16 November:"
diff <(grep '==' lock-nov01.txt) <(grep '==' lock-nov16.txt)
Expected output
cloudpickle==3.1.2
joblib==1.6.0
narwhals==2.28.0
numpy==2.5.4
scikit-learn==1.9.1
scipy==1.18.1
threadpoolctl==3.7.0
--- what changed by 16 November:
4c4
< numpy==2.5.4
---
> numpy==2.5.5
7c7
< threadpoolctl==3.7.0
---
> threadpoolctl==3.8.0

One line of requirements became seven pinned packages. Between 1 and 16 November, two of them moved: a person who installed on the 16th got a different NumPy and a different threadpoolctl (the package that controls how many threads the maths libraries use) from a person who installed on the 1st, with the same requirements.in. Commit the lock file next to the code and install from it, for example with uv pip sync lock-nov01.txt, and both people get the same seven versions. The lock pins Python packages only; also record the Python version, and the operating system, CUDA and driver versions if you use a GPU.

05. Check your understanding

Practice check · 3 questions

Where the numbers moved

Use the scripts and outputs of this lesson.

Q1. In `seeds.py`, ten seeds give test accuracies from 0.937 to 0.979. A colleague adds a feature, runs the script once without fixing the seed, and gets 0.965 against 0.951 for the old code. What does that comparison show?
Q2. A training job builds its feature matrix from `list(set(columns))` and saves the model. The scoring service, a separate process, builds its input the same way. Based on `setorder.py`, what can go wrong?
Q3. Every cell of a notebook sets its own seeds and the data file has not changed. It showed a validation AUC of 0.91 yesterday; after "Restart kernel and run all" it shows 0.89. Which explanation fits best?
Practice only: not graded, not saved, not evidence.

06. Apply it

The practice project starts from an existing training script. Before adding any tool, find out how unrepeatable it is today.

  1. Run the script three times without changes and write down the main metric each time. If the numbers differ, find every function that takes a seed or random state and fix it from one configuration value.
  2. Run it with five seeds and record the spread. Use that spread as the smallest difference you will believe in later comparisons.
  3. Write a requirements.in with your direct dependencies, compile a lock file with uv pip compile, and install from it in a fresh environment. Check that the metric for seed 0 matches the one from your old environment, and write down any difference.
  4. Search the code for sets or dict keys used to order columns, and sort them.

07. Review prompt

Without looking back, list the six groups of inputs a training result depends on; explain why a single run per setting cannot show that a small change helps; explain why adding the same numbers in a different grouping can change the total, and name two places where that happens in training; say what PYTHONHASHSEED controls and why it can reorder columns; and describe what a lock file records that a list of package names does not.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check