Sub topic 4
Making Runs Reproducible
Prerequisites
This chapter assumes you understand Python functions, dataclasses, and modules. You should also know the basic machine learning workflow: split data, train a model, and evaluate it. The examples use scikit-learn and assume you can run a Python script from a command line.
A reproducible run produces the same result, or a result within a known tolerance, when you run the same pipeline again. Reproducibility matters because a model is difficult to trust if nobody can explain how its result was produced.
Reproducibility has several parts:
- The code version must be known.
- The input data version must be known.
- Random choices must be controlled.
- The software environment must be recorded.
- The configuration must be saved with the run.
A random seed alone is not enough. Changing the dataset, library version, or feature-processing code can change the result even when the seed stays the same.
Control Randomness
Many training steps use pseudorandom numbers. A pseudorandom number generator produces a repeatable sequence when it starts from the same seed.
Set seeds at the boundaries where randomness enters your pipeline. In this example, the data split and random forest both receive the same configured seed.
import dataclasses
import hashlib
import json
import random
from dataclasses import dataclass
import numpy as np
from sklearn.datasets import load_iris
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
@dataclass(frozen=True)
class TrainConfig:
seed: int = 42
test_size: float = 0.2
n_estimators: int = 100
data_version: str = "iris-v1"
def config_fingerprint(config: TrainConfig) -> str:
payload = json.dumps(dataclasses.asdict(config), sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()[:12]
def run(config: TrainConfig) -> float:
random.seed(config.seed)
np.random.seed(config.seed)
features, labels = load_iris(return_X_y=True)
split = train_test_split(
features,
labels,
test_size=config.test_size,
random_state=config.seed,
stratify=labels,
)
x_train, x_test, y_train, y_test = split
model = RandomForestClassifier(
n_estimators=config.n_estimators,
random_state=config.seed,
)
model.fit(x_train, y_train)
return accuracy_score(y_test, model.predict(x_test))
if __name__ == "__main__":
config = TrainConfig()
print("run_id:", config_fingerprint(config))
print("accuracy:", run(config))The seed controls choices made by Python, NumPy, and the estimator. Pass an explicit random_state where a library accepts one. Do not rely only on global seed settings.
Some operations remain nondeterministic. Parallel numerical operations can execute in a different order on different hardware. GPUs can use algorithms with nondeterministic behavior. Treat reproducibility as a target with a defined tolerance rather than a promise of identical bytes.
Version Data and Environments
Record a stable data identifier, not only a filename. A filename such as train.csv can point to different contents next week. Use a release name, database snapshot ID, object version, or content hash.
The environment also affects results. Record the Python version, operating system, accelerator details when relevant, and exact dependency versions. A common practice is to commit a lock file or a pinned requirements file.
| Item | Example record | Why it matters |
|---|---|---|
| Code | Git commit `a13f9c2` | Identifies pipeline logic |
| Data | `customer-events-2026-11-30` | Identifies inputs |
| Dependencies | `scikit-learn==1.5.2` | Identifies library behavior |
| Configuration | `run_id=8e4d1f2a91c0` | Identifies tunable values |
Store these records with the metrics and model artifact. A run should answer, “Which code, data, environment, and settings produced this file?”
Understand the Reproducibility Chain
Each item depends on the previous items. If the data changes, a matching seed cannot restore the old result.
Check Reproducibility
Test the pipeline twice with the same inputs. For deterministic CPU code, exact equality may be reasonable. For parallel or floating-point-heavy code, compare values with a tolerance.
Also test that changing an important input changes the run identity. A configuration fingerprint is useful for this purpose, but it should include every value that can affect the result.
Use smoke tests to run a small end-to-end dataset in continuous integration. This catches missing files, incompatible dependencies, and broken stage interfaces. Keep full training runs outside ordinary unit tests when they are slow or expensive.
Exercise
Your second run has the same seed but a different accuracy. Name two causes you would investigate before changing the seed.
Show answer
Check whether the data version or code commit changed, then compare dependency versions and hardware or parallel execution settings.