Sub topic 1
Why structure matters: reproducible results
A model that scored well last month and cannot be rebuilt today is a liability. This chapter explains what makes a result reproducible and which parts of a project have to be controlled to get there. The rest of the tutorial builds those controls one at a time.
Prerequisites
This chapter assumes you have:
- Basic Python, including modules and functions.
- Comfort with the command line.
- Basic Git usage: commit, branch, and ignore files.
- Trained at least one model with a library such as scikit-learn or PyTorch.
What reproducible means
A result is reproducible when someone else, or you in six months, can run the same project and get the same numbers, or numbers close enough that the difference is explained. Two related terms are often confused:
- Reproducibility means the same code, data, and settings give the same result.
- Replicability means an independent attempt with new data or new code reaches the same conclusion.
This tutorial is about the first. It is the precondition for the second, because you cannot tell whether a new result agrees with an old one if the old one cannot be rebuilt.
"Same numbers" needs a tolerance. On a CPU with seeded random generators you can often get bit-for-bit identical output. On a GPU, some operations are nondeterministic, so you may only get metrics that agree to a few decimal places. Decide up front which standard you are aiming for and write it down.
The four inputs to a run
Every training run is a function of four things:
- Code: the training logic and the helper functions it calls.
- Configuration: hyperparameters, file paths, and other values that change between runs.
- Data: the exact files the code reads.
- Environment: the Python version, library versions, and hardware.
Randomness is a fifth input that is easy to forget. It enters through the seed, which is the starting value of a random number generator.
If any of these changes and you did not record it, you cannot explain why a result changed. If you can record all of them, you can rerun the experiment.
How projects lose reproducibility
Most failures come from a small set of habits. They are common because each one is convenient in the moment.
- Hyperparameters edited in place. You change
learning_rate = 0.001to0.01in the training script, run it, and change it back. Nothing records what produced the number you saw. - Notebook state. A notebook cell can depend on a variable defined in a cell you later deleted, or on cells run out of order. The notebook on disk may not reproduce the output it displays.
- Mutable data. Someone overwrites
train.csvwith a cleaned version. Old results now refer to a file that no longer exists. - Unpinned libraries.
pip install scikit-learntoday installs a different version than it did a year ago. Defaults inside libraries change between versions. - Hard-coded paths. A path such as
/home/ana/data/train.csvworks on one machine only. - Uncontrolled randomness. Train/test splits and weight initialization differ on every run, so a difference of 0.5 points in accuracy might be noise.
- Unrecorded code version. The model file exists, but no one knows which commit produced it, or whether the working tree had uncommitted changes.
Notice that these are structural problems, not modeling problems. Better algorithms do not fix them. Where files live and how values are passed around do.
Separate what changes at different speeds
The central idea of this tutorial is that code, configuration, and data change at different rates and for different reasons, so they should live in different places.
| Part | Changes when | Where it lives | How it is versioned |
|---|---|---|---|
| Code | You fix a bug or add a feature | A source package in Git | Git commits |
| Configuration | You try a new experiment | Config files and command-line overrides | Git, plus a copy saved with each run |
| Data | New data arrives or cleaning rules change | Data folders outside Git history | A data versioning tool or content hashes |
| Environment | You upgrade a dependency | A lock file or container image | Git, for the lock file |
When these are mixed together, a small change forces you to touch everything. Changing a learning rate should not mean editing a function. Replacing a dataset should not mean editing a path in five files. And when they are separated, you can state exactly what differs between two runs: "same code, same data, learning rate 0.001 versus 0.01."
A run fingerprint
You do not need a full framework to start recording the inputs. The script below builds a small manifest for a run: the Git commit, a hash of the data file, the parameters, and the Python version. A hash is a short fixed-length value computed from a file's bytes. If the file changes by even one byte, the hash changes.
import hashlib
import json
import platform
import subprocess
import tempfile
from pathlib import Path
def file_sha256(path):
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def git_commit():
try:
result = subprocess.run(
["git", "rev-parse", "HEAD"],
capture_output=True,
text=True,
check=True,
)
return result.stdout.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown"
def run_manifest(data_path, params):
return {
"git_commit": git_commit(),
"data_sha256": file_sha256(data_path),
"params": params,
"python": platform.python_version(),
}
if __name__ == "__main__":
with tempfile.TemporaryDirectory() as tmp:
data_file = Path(tmp) / "train.csv"
data_file.write_text("x,y\n1,2\n3,4\n")
manifest = run_manifest(data_file, {"seed": 42, "learning_rate": 0.001})
print(json.dumps(manifest, indent=2))Run it twice and the output is identical. Change one character in the CSV and data_sha256 changes. Saving a manifest like this next to every model answers the question "what produced this?" without relying on anyone's memory.
What a structured project gives you
The remaining chapters each add one control. Here is how they map to the five inputs.
- Repository layout and a source package keep code in one importable place, so notebooks and scripts call the same functions.
- Config files, typed loading, and overrides move hyperparameters and paths out of code and make every value explicit.
- Data folders and data versioning separate raw files from derived ones and tie each result to a data version without committing large files to Git.
- Pipelines declare which code, parameters, and data produce each output, so only stale steps are rerun.
- Environments and seeds pin library versions and fix random choices.
- Experiment tracking records parameters, metrics, and code version for every run so you can compare them.
- Tests and automated checks catch the failures that do not raise errors, such as a config value silently parsed as a string.
Treat reproducibility as a property you build in from the first day, not a cleanup task at the end. Retrofitting is possible but costs more. The original data may have been overwritten and the exact library versions forgotten by then.
Limits and trade-offs
Perfect reproducibility is not free, and it is not always the right target.
- Hardware nondeterminism. Some GPU kernels give slightly different results across runs or across GPU models. Forcing deterministic mode can slow training. Often the practical answer is to run several seeds and report the spread.
- Cost of storing data versions. Keeping every dataset version takes space. Decide how long old versions must remain available.
- Overhead on small projects. A one-day exploration does not need a pipeline tool. It does need a seed, a recorded data file name, and a saved set of parameters. Add structure as the project lives longer or has more collaborators.
- External sources. If your data comes from a live API or database, you must snapshot it. Otherwise the project depends on something you do not control.
A useful test for any project is this: could a teammate clone the repository on a fresh machine, fetch the data, run one command, and get your reported metrics? Each later chapter removes one reason the answer might be no.
Exercise
A teammate reports that a model you trained last quarter reached 0.91 accuracy, and they cannot reproduce it. They have the code at the commit you gave them. List three other things that could differ and name the input category (code, configuration, data, environment, or seed) for each.
Show answer
Examples: the dataset file was overwritten or cleaned since then (data); a different scikit-learn or PyTorch version with changed defaults is installed (environment); the learning rate or batch size was changed in a local edit that was never committed (configuration); the train/test split or weight initialization used a different random seed (seed). Any three of these, each with its category, are correct. The commit identifies the code only if the working tree was clean when the model was trained.
Exercise
In the run fingerprint script, you change a single value in the CSV file and run the script again. Which field in the output changes, and why does that help with reproducibility?
Show answer
The data_sha256 field changes, because the hash is computed from the file's bytes and any change produces a different hash. This lets you detect that two runs used different data even if the file name stayed the same, which is how you find out that a file was overwritten.