Sub topic 12
Versioning data, code, and models for reproducibility
This chapter assumes you know the basic train, validate, test, deploy workflow, can read Python, and use Git and a CI/CD system. It covers what a retraining pipeline must record so that any deployed model can be explained and rebuilt.
Why retraining makes versioning urgent
A manually trained model is usually a one-off. An automated pipeline produces a new model every time a trigger fires, often with nobody watching. Within a few months you may have dozens of candidate models, and some will have been promoted and rolled back.
When production quality drops, you need to answer these questions:
- Which model is serving traffic right now?
- Which data, code, and configuration produced it?
- Can we rebuild it and get the same result?
- Which earlier model can we safely roll back to?
If the pipeline does not record the answers when it runs, you cannot reconstruct them later. Reproducibility is the ability to rerun a training job from recorded inputs and get an equivalent model. Lineage is the recorded chain linking a model to the inputs that produced it.
What to version
A trained model is a function of four things. Version all of them.
| Ingredient | What to record | Common tool or method |
|---|---|---|
| Code | Git commit SHA of the training and feature code | Git |
| Data | Immutable snapshot or content hash of the training and evaluation sets | Snapshot tables, DVC, lakehouse table versions |
| Configuration | Hyperparameters, feature list, trigger reason, random seeds | Config files committed to Git, logged parameters |
| Environment | Library versions, container image digest, hardware type | Lock files, image digests |
The output, the model artifact, gets its own version in the model registry (covered in a later chapter). The registry entry should point back to all four ingredients.
Versioning data
Code versioning is solved. Data versioning is where pipelines usually break, because production data keeps changing underneath you.
Three failure patterns are common:
- Query by date range on a mutable table. Late-arriving rows and corrections change the result of the same query run next week.
- Overwritten files. A job rewrites
train.parquetin place and the earlier version is gone. - Changed label definitions. Upstream teams redefine a column, and old and new rows silently mix.
There are three practical strategies:
- Immutable snapshots. Write each training set to a new path, such as one that includes a snapshot ID, and never modify it.
- Table versioning. Use a storage format that supports time travel (for example, Delta Lake, Apache Iceberg, or Hudi), and record the table version used.
- Content hashing. Compute a hash of the dataset and store it with the model. This detects changes even when you cannot keep every copy.
A content hash is cheap to compute and works with any storage. The helper below hashes a file in chunks so that large files do not need to fit in memory.
import hashlib
from pathlib import Path
def file_sha256(path, chunk_size=1024 * 1024):
"""Return the SHA-256 hex digest of a file, read in chunks."""
digest = hashlib.sha256()
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(chunk_size), b""):
digest.update(chunk)
return digest.hexdigest()
sample = Path("sample_train.csv")
sample.write_text("age,income,label\n34,52000,0\n41,61000,1\n")
print(file_sha256(sample))The same input always gives the same digest, and any change to the file gives a different one. For datasets split across many files, hash each file and then hash the sorted list of digests.
Remember the evaluation data too. If the champion and the challenger are compared on different test sets, the comparison in the evaluation gate means nothing. Version the evaluation set separately and record which one each comparison used.
Versioning code and configuration
Record the Git commit SHA at the start of each run, and refuse to train from a dirty working tree in production. Keep hyperparameters and feature lists in committed config files rather than in command-line arguments typed by hand. When a trigger starts the run, also record the trigger type and reason, such as drift_with_enough_data. That tells you later why this model exists.
Pin the environment as well. Use a lock file for Python dependencies and a container image referenced by digest, not by a mutable tag like latest. A tag can be repointed to a different image; a digest cannot.
Capturing lineage in a run manifest
Lineage works best when the pipeline writes one structured record per run. The example below builds a manifest, writes it as JSON, and can be extended with whatever your tooling needs.
import json
import subprocess
import sys
from datetime import datetime, timezone
def git_sha():
"""Return the current Git commit SHA, or 'unknown' outside a repository."""
try:
out = subprocess.run(
["git", "rev-parse", "HEAD"],
capture_output=True, text=True, check=True,
)
return out.stdout.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return "unknown"
def build_manifest(train_hash, eval_hash, params, trigger_reason, seed):
return {
"created_at": datetime.now(timezone.utc).isoformat(),
"code_commit": git_sha(),
"python": sys.version.split()[0],
"train_data_sha256": train_hash,
"eval_data_sha256": eval_hash,
"params": params,
"seed": seed,
"trigger_reason": trigger_reason,
}
manifest = build_manifest(
train_hash="a1b2c3",
eval_hash="d4e5f6",
params={"max_depth": 6, "learning_rate": 0.1},
trigger_reason="drift_with_enough_data",
seed=42,
)
print(json.dumps(manifest, indent=2))Store the manifest next to the model artifact and attach it to the registry entry. In a real pipeline, replace the placeholder hashes with the output of file_sha256 or a table version.
Reproducibility has limits
Recording inputs makes a rerun possible. It does not guarantee a bit-identical model. Know the usual sources of difference:
- Random seeds. Set seeds for every library involved (NumPy, the ML framework, data shuffling).
- Non-deterministic hardware operations. Some GPU kernels and parallel reductions give slightly different floating-point results between runs.
- Thread and worker ordering. Distributed training and multi-threaded data loading can change the order of operations.
- Time-dependent features. A feature computed as "days since signup" changes if you recompute it on a different day.
The realistic goal is usually statistical reproducibility: a rerun gives metrics within a small tolerance. Test this. Rerun an old manifest occasionally and check that the evaluation metric lands within an agreed margin.
Versioning features and the training-serving gap
A model is only reproducible if its features are. If training computes features with one code path and serving uses another, the two can disagree even when both are versioned. Version the feature definitions, ideally in a shared library or a feature store, and record the feature set version in the manifest. This also makes data validation easier, because the schema for each version is explicit.
Retention and cost
Keeping every snapshot forever is expensive, and some data has legal retention limits. Decide a policy up front:
- Keep full lineage records (manifests) indefinitely. They are small.
- Keep data snapshots for models that were ever promoted, for as long as they could be rollback targets.
- Delete or archive snapshots for challengers that failed the gate, after a short window.
- If privacy rules require deleting personal data, keep hashes and aggregate statistics, and note in the manifest that the raw snapshot is no longer available.
Common errors
- Logging the code commit but not the data version, so the model cannot be rebuilt.
- Comparing champion and challenger on different evaluation sets.
- Recording a mutable tag instead of an immutable digest.
- Storing the manifest somewhere separate from the model, where the two drift apart.
- Assuming a seed makes GPU training exactly repeatable.
Exercise
A retraining run finished three weeks ago and its model is now serving traffic. Its manifest records the Git commit, the hyperparameters, and the query "all rows from the events table where event_date is in the last 90 days". Name two reasons you might not be able to reproduce this model, and say what you would record instead.
Show answer
First, "the last 90 days" is relative to the run date, so rerunning today selects a different window. Second, the events table is mutable, so late-arriving rows and corrections change the result even for the same dates. Record the resolved date range, and a snapshot ID, table version, or content hash of the exact rows used. Also record the environment (image digest or lock file) and the seed, since those are missing too.
Exercise
Why should the manifest record the evaluation data hash separately from the training data hash?
Show answer
The evaluation gate compares the challenger with the champion, and that comparison is only valid if both were scored on the same evaluation set. The separate hash lets you verify that, and lets you reproduce the comparison later.