Sub topic 3
Making Tests Reproducible: Seeds, Pinned Dependencies, and Tolerances
This chapter assumes that you know Python and pytest, use Git pull requests, and have trained a model with scikit-learn or a similar library. Reproducibility means that the same test inputs and configuration produce the same result, or a result within an explicitly allowed range.
Reproducibility matters because CI must distinguish a real regression from random variation. A test that passes locally and fails randomly in CI wastes time and reduces trust in the test suite.
Where variation comes from
ML tests can vary for several reasons:
- A random split, shuffle, or model initialization uses an uncontrolled random-number generator.
- A dependency changes its behavior after an upgrade.
- Floating-point operations produce tiny differences across hardware or library versions.
- Parallel computation changes the order of operations.
- A test depends on the current time, file order, or an external service.
A useful test records the choices that affect its result.
flowchart TD
A[Test inputs] --> B[Seed random generators]
B --> C[Run deterministic code]
C --> D[Compare with tolerance]
E[Pinned dependencies] --> C
D --> F[Pass or report regression]The seed controls pseudo-random choices. A pinned dependency set controls the software implementation. A tolerance defines how much numeric variation is acceptable.
Seed every source of randomness
Prefer passing a seed directly to the function or estimator under test. This makes the dependency visible and avoids hidden global state.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
def train_model(seed: int) -> tuple[LogisticRegression, np.ndarray, np.ndarray]:
X, y = make_classification(
n_samples=200,
n_features=5,
random_state=seed,
)
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=seed,
stratify=y,
)
model = LogisticRegression(max_iter=200, random_state=seed)
model.fit(X_train, y_train)
return model, X_test, y_test
def test_training_is_repeatable():
first, X_test, _ = train_model(seed=7)
second, _, _ = train_model(seed=7)
assert np.array_equal(first.predict(X_test), second.predict(X_test))Use separate seeds when testing different scenarios. Avoid relying on the process-wide NumPy seed unless the code under test cannot accept a generator or seed.
When parallel libraries are involved, configure their worker count for tests. A single worker is often slower but easier to reproduce. If exact repeatability is impossible, test an invariant such as valid output shape or a metric range instead of exact model coefficients.
Pin dependencies and record the environment
A seed cannot protect against changed library behavior. Pin direct dependencies to known versions and update them deliberately.
numpy==1.26.4
pandas==2.2.1
scikit-learn==1.4.1.post1
pytest==8.1.1Commit this file, install it in CI, and use the same Python version locally and in CI. For stronger control, generate a lock file that records transitive dependencies, which are packages installed by your direct dependencies.
Record relevant environment details with model or test artifacts:
- Python version
- operating system or container image
- dependency lock-file hash
- random seed
- CPU or accelerator type when numerical behavior depends on it
Pinning improves repeatability but creates maintenance work. Schedule dependency updates, run the full suite, and review changed metrics rather than upgrading packages during unrelated pull requests.
Compare floating-point results with tolerances
Floating-point values are approximations. Two correct runs may differ in the last few digits. Use pytest.approx or NumPy comparison helpers instead of exact equality.
import pytest
def scale_income(income: float, median: float) -> float:
if median <= 0:
raise ValueError("median must be positive")
return income / median
def test_scale_income():
assert scale_income(50_000.0, 25_000.0) == pytest.approx(2.0)
def test_scale_income_rejects_invalid_median():
with pytest.raises(ValueError):
scale_income(50_000.0, 0.0)Use a relative tolerance for values whose size varies and an absolute tolerance near zero. Do not choose a large tolerance merely to make a failing test pass. Estimate normal numerical variation, document the reason, and keep the tolerance narrower than the smallest meaningful regression.
| Result type | Suitable assertion |
|---|---|
| Exact labels or categories | Exact equality |
| Floating-point feature value | Relative and absolute tolerance |
| Model score | A documented threshold or allowed range |
| Probability vector | Shape, range, and sum within tolerance |
A reproducibility checklist
Before trusting an ML test, ask:
- Are all random operations seeded?
- Are seeds passed into libraries and estimators directly?
- Are Python, dependency, and container versions controlled?
- Are floating-point comparisons tolerant but meaningful?
- Does the test avoid time, network, and unordered external data?
- Does CI use the same installation procedure as local development?
Exercise
A model test passes locally but fails in CI because its accuracy changes by 0.001. What should you check before increasing the tolerance?
Show answer
Check that every random operation has a controlled seed, that local and CI use the same Python and dependency versions, and that parallel execution is configured consistently. Increase the tolerance only after measuring normal variation and confirming that the difference is numerical rather than a real regression.