Sub topic 3
Making tests reproducible: seeds, pinned dependencies, tolerances
A test that passes on Monday and fails on Tuesday with no code change teaches the team to ignore red builds. ML projects are especially prone to this because training uses randomness and numerical libraries. This chapter shows how to remove avoidable nondeterminism and how to tolerate the rest.
This chapter assumes you can write pytest tests, train a scikit-learn model, and read a pull-request CI run. Later chapters on model behavior tests and quality gates depend on the techniques here.
Where nondeterminism comes from
Before fixing flaky results, name the source. Each source has a different fix.
| Source | Example symptom | Fix |
|---|---|---|
| Random number generators | Accuracy changes by 1 to 2 points between runs | Seed every generator you use |
| Library versions | Same code, different results after a dependency upgrade | Pin versions |
| Floating-point arithmetic | Two runs differ in the 10th decimal place | Compare with tolerances |
| Threads and hardware | Results differ between a laptop and a CI runner | Limit parallelism, loosen tolerances |
| Data ordering | A test passes only when files load in a certain order | Sort inputs, use a fixed sample |
| Environment | Locale, time zone, or hash seed changes behavior | Set these explicitly in CI |
Seeding randomness
A seed is a starting value for a pseudo-random number generator. The same seed produces the same sequence of numbers, so a seeded run can be repeated exactly.
Python programs often use several independent generators, and seeding one does not affect the others:
- The standard library
randommodule. - NumPy, either the legacy global state (
np.random.seed) or aGeneratorobject (np.random.default_rng). - Library-specific generators, such as the
random_stateargument on scikit-learn estimators and splitters. - Deep learning frameworks, which have their own seeds (for example
torch.manual_seed).
The most reliable approach is to pass the seed explicitly to each component instead of relying on global state. Global seeding is a safety net, not a design.
import random
import numpy as np
import pytest
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
SEED = 42
@pytest.fixture(autouse=True)
def fixed_global_seeds():
# Safety net for code that uses global generators.
random.seed(SEED)
np.random.seed(SEED)
def fit_forest(seed):
X, y = make_classification(n_samples=300, n_features=8, random_state=0)
model = RandomForestClassifier(n_estimators=20, random_state=seed)
model.fit(X, y)
return model, X
def test_same_seed_gives_same_probabilities():
m1, X = fit_forest(seed=1)
m2, _ = fit_forest(seed=1)
np.testing.assert_allclose(
m1.predict_proba(X), m2.predict_proba(X), rtol=1e-7, atol=1e-9
)
def test_seed_is_actually_used():
m1, X = fit_forest(seed=1)
m2, _ = fit_forest(seed=2)
assert not np.allclose(m1.predict_proba(X), m2.predict_proba(X))The second test looks odd but has a purpose. If someone removes random_state from the estimator, the first test could still pass by accident on some runs. The second test confirms that the seed controls the outcome.
Details that trip people up
- Seed the data split too.
train_test_split(X, y, random_state=SEED)is needed even when the model is seeded. An unseeded split changes both the training set and the test set between runs. - Seed per test, not once per session. If one global seed is set at session start, a test's result depends on which tests ran before it. The autouse fixture above resets the seeds before every test. The
pytest-randomlyplugin does the same and also shuffles test order, which helps expose hidden dependencies between tests. - Prefer local generators. A function that takes a
rng: np.random.Generatorargument is easy to test. A function that callsnp.random.rand()depends on global state that any other code can change. - Set
PYTHONHASHSEED. Python randomizes string hashing per process. Code that iterates over asetof strings can produce a different order on each run. SettingPYTHONHASHSEED=0in the CI environment removes that source. - Parallel workers. With
n_jobsgreater than 1, or withpytest-xdist, each worker has its own generator state. Pass explicit seeds instead of relying on a global one.
Pinning dependencies
Seeds produce the same numbers only if the code that consumes them is unchanged. A new scikit-learn release can change a default solver, a tie-breaking rule, or the order in which random numbers are drawn. Your tests then fail with no change in your repository.
Pin exact versions so that the CI environment is the same on every run:
numpy==1.26.4
pandas==2.2.2
scikit-learn==1.4.2
pytest==8.2.0A few practices make pinning workable:
- Pin transitive dependencies too. A tool such as
pip-compile(from pip-tools),uv pip compile, or Poetry generates a full lock file from a short list of direct dependencies. - Pin the Python version in the workflow (
python-version: "3.11"), not only the packages. - Upgrade on purpose. Update the lock file in its own pull request so that a failing test points to the upgrade and not to your change.
- Consider a scheduled job that tests against the newest versions. It tells you early when an upgrade will break something, without blocking everyday pull requests.
Pinning has a cost. Pinned environments age, and security fixes do not arrive by themselves. Pin for reproducibility and set up a regular upgrade routine to balance that.
Tolerances for floating-point results
Seeds and pins make runs repeatable on one machine. They do not guarantee bit-for-bit equality across machines. Floating-point addition is not associative, so adding the same numbers in a different order can change the last digits. Different CPUs, BLAS libraries, and thread counts all change the order.
The classic example is that 0.1 + 0.2 == 0.3 is false in Python. Use a tolerance-based comparison instead of == for any float that comes from computation:
import numpy as np
import pytest
def test_float_equality_needs_tolerance():
assert 0.1 + 0.2 != 0.3
assert 0.1 + 0.2 == pytest.approx(0.3)
def test_sum_does_not_depend_on_order():
x = np.random.default_rng(0).normal(size=100_000)
assert np.sum(x) == pytest.approx(np.sum(x[::-1]), rel=1e-9)Two tolerance parameters appear in most tools:
- Relative tolerance (
rtolorrel) scales with the size of the value. Use it when values can be large. - Absolute tolerance (
atolorabs) is a fixed amount. Use it when the expected value is near zero, because a relative tolerance on zero is zero.
pytest.approx defaults to a relative tolerance of 1e-6 and an absolute tolerance of 1e-12. np.testing.assert_allclose defaults to rtol=1e-7 and atol=0. The atol=0 default surprises many people. Comparing an array that contains values near zero then fails on tiny differences, so set atol explicitly.
Choosing a tolerance
Match the tolerance to the kind of check:
- Deterministic arithmetic, such as a scaling function: use tight tolerances, around 1e-9 relative.
- Model outputs on the same machine and library versions:
rtol=1e-7with a smallatolis typical. - Model outputs across different hardware or thread counts: expect differences around 1e-5, and loosen the tolerance to match what you observe.
- Metrics such as accuracy: do not compare to many decimals. Check that the value lies within a band, for example within 0.02 of a recorded reference. The next chapters on quality gates build on this.
Choose the tolerance from evidence. Run the test several times on the CI runner, look at the spread, and set the tolerance a bit wider than that spread. A tolerance picked to make one failure disappear tends to hide real regressions.
Things that remain nondeterministic
Some sources cannot be fully removed. Know them so that you do not chase them endlessly.
- GPU training. Some GPU operations, such as atomic additions in certain convolution and scatter kernels, give different results from run to run. Frameworks provide flags that force deterministic algorithms at a speed cost. In CI, avoid GPUs for correctness tests and use small CPU models.
- Multithreaded math. Thread scheduling changes summation order. Setting
OMP_NUM_THREADS=1in CI makes results more stable. Use it for tests that compare outputs closely. - Ties in predictions. When two classes have nearly equal probability, a tiny numeric difference flips the predicted label. Tests on labels for a handful of borderline rows are fragile. Test probabilities with tolerances, or choose test inputs far from the decision boundary.
- Small test sets. With 50 test rows, one flipped prediction moves accuracy by 2 points. Either use more rows or set thresholds that allow for that granularity.
A practical checklist
Apply these in order when a test is unstable:
- Run the test ten times locally. If it fails sometimes, the cause is randomness or ordering.
- Check that every random component, including the data split, has a seed.
- Check that the lock file is used in CI, with the same Python version.
- Replace
==on floats withapproxorassert_allclose, and setatolwhere values can be near zero. - Set
PYTHONHASHSEEDandOMP_NUM_THREADSin the CI job if results still differ between machines. - If a result is still unstable, ask whether the test checks something too precise. Often a range or a property is the right assertion.
Exercises
Exercise
A test asserts np.testing.assert_allclose(actual, expected) where expected contains the value 0.0. It fails with actual equal to 3e-12. Why does it fail, and what is the fix?
Show answer
assert_allclose defaults to rtol=1e-7 and atol=0. The allowed error is atol + rtol * abs(expected), which is 0 when expected is 0, so any nonzero difference fails. Set an explicit absolute tolerance, for example atol=1e-9, so that tiny differences near zero are accepted.
Exercise
A team seeds RandomForestClassifier(random_state=0) and pins scikit-learn, but their accuracy test still fails about one run in five. Name two causes you would check first, and the fix for each.
Show answer
First, the data split may be unseeded: add random_state to train_test_split so the train and test sets are the same each run. Second, the test may compare accuracy to a threshold that is too tight for a small test set, or depend on global generators used elsewhere: use a larger test set or a tolerance band, and reset global seeds in an autouse fixture. Setting OMP_NUM_THREADS=1 and PYTHONHASHSEED is a further check if the failure only happens on the CI runner.