Sub topic 12
Versioning Data, Models, and Metrics
This chapter assumes you can write pytest tests, use Git and pull requests, and train a scikit-learn model. It also assumes you have read the chapters on quality gates and CI workflows. Here you will learn how to record which data, code, and settings produced each model, so that a CI result can be traced and reproduced later.
Why Git alone is not enough
In conventional software, a commit identifies the code, and the code determines the build. In ML, a model depends on at least four inputs:
- The code that trains it.
- The training data.
- The configuration, such as hyperparameters and random seeds.
- The environment, meaning library versions.
Git tracks the first and part of the third well. It handles large binary files poorly, and it does not know that data/train.csv changed last Tuesday. A quality gate that compares a candidate with a baseline is only meaningful if you know exactly what the baseline was. If the baseline's data has been silently overwritten, a "regression" may only be a data change.
The goal of versioning is a simple statement you can verify: this model file was produced by this commit, from this data, with this configuration, and scored these metrics.
What to version, and where
Different artifacts suit different storage.
| Artifact | Typical size | Where it lives | How it is identified |
|---|---|---|---|
| Source code, tests, workflow files | Small | Git | Commit hash |
| Configuration (hyperparameters, seeds) | Small | Git | Commit hash |
| Dependency pins | Small | Git (`requirements.txt` or a lock file) | Commit hash |
| Small sample data used by tests | Small | Git (`tests/data/`) | Commit hash |
| Full training data | Large | Object storage or a data-versioning tool | Content hash |
| Trained model files | Medium to large | Object storage or a model registry | Content hash plus metadata |
| Metrics and run metadata | Tiny | Git, a JSON file in storage, or an experiment tracker | Run identifier |
The rule of thumb is to keep small, text-based, reviewable files in Git. Put large or binary files in a store addressed by content, and keep a small pointer file in Git that names the exact content.
Content hashes as identifiers
A content hash is a fixed-length fingerprint computed from a file's bytes. If one byte changes, the hash changes. Using the hash as the identifier means a name can never silently point to different data.
This is the core idea behind tools such as DVC, which stores a small .dvc pointer file in Git, and behind model registries. You can implement the principle yourself in a few lines:
import hashlib
from pathlib import Path
def file_sha256(path: str, chunk_size: int = 1 << 20) -> str:
digest = hashlib.sha256()
with open(path, "rb") as f:
while chunk := f.read(chunk_size):
digest.update(chunk)
return digest.hexdigest()
def test_file_hash_changes_with_content(tmp_path: Path):
a = tmp_path / "a.csv"
b = tmp_path / "b.csv"
a.write_text("age,income\n30,50000\n")
b.write_text("age,income\n31,50000\n")
assert file_sha256(str(a)) != file_sha256(str(b))
assert file_sha256(str(a)) == file_sha256(str(a))The function reads the file in chunks, so a multi-gigabyte dataset does not have to fit in memory.
A run manifest links everything together
A manifest is a small JSON file written at the end of each training run. It records the inputs and the outputs, and it is the artifact your CI quality gate and later deployment steps read.
import json
import subprocess
import sys
from pathlib import Path
def git_commit() -> str:
result = subprocess.run(
["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True
)
return result.stdout.strip()
def build_manifest(data_hash: str, model_hash: str, params: dict, metrics: dict) -> dict:
return {
"git_commit": git_commit(),
"python": sys.version.split()[0],
"data_sha256": data_hash,
"model_sha256": model_hash,
"params": params,
"metrics": metrics,
}
def write_manifest(manifest: dict, path: str) -> None:
Path(path).write_text(json.dumps(manifest, indent=2, sort_keys=True))
def test_manifest_round_trip(tmp_path: Path):
manifest = {
"git_commit": "abc123",
"data_sha256": "d" * 64,
"model_sha256": "m" * 64,
"params": {"seed": 0},
"metrics": {"accuracy": 0.9},
}
target = tmp_path / "manifest.json"
write_manifest(manifest, str(target))
assert json.loads(target.read_text()) == manifestWriting with sort_keys=True produces stable output, so two manifests from identical runs diff cleanly in a pull request.
A manifest turns a vague question ("which data trained the production model?") into a lookup. It also gives you an easy test: a CI step can fail if a model is published without a complete manifest.
REQUIRED_KEYS = {"git_commit", "data_sha256", "model_sha256", "params", "metrics"}
def check_manifest(manifest: dict) -> list[str]:
missing = sorted(REQUIRED_KEYS - manifest.keys())
return [f"manifest missing key: {key}" for key in missing]
def test_incomplete_manifest_is_reported():
assert check_manifest({"git_commit": "abc"}) == [
"manifest missing key: data_sha256",
"manifest missing key: metrics",
"manifest missing key: model_sha256",
"manifest missing key: params",
]Versioning metrics for baseline comparison
The quality gate from the previous chapters takes a baseline dictionary. Where does it come from? There are three common answers, each with trade-offs.
- A metrics file committed to Git. The baseline is updated by a reviewed pull request. This is simple and auditable, but the file can drift out of date, and it records the numbers without the model that produced them.
- The manifest of the currently deployed model, fetched from storage or a registry. This always compares against what users actually get. It needs network access and credentials in CI.
- Recomputing the baseline in CI by training the main-branch code on the same data. This is the fairest comparison, since both models see identical conditions, but it doubles the cost of the job.
For a first setup, option 1 is usually the right choice. Keep the file small and in a predictable location:
import json
from pathlib import Path
def load_baseline(path: str = "metrics/baseline.json") -> dict:
return json.loads(Path(path).read_text())
def test_baseline_file_has_accuracy(tmp_path: Path):
target = tmp_path / "baseline.json"
target.write_text(json.dumps({"accuracy": 0.91, "data_sha256": "d" * 64}))
baseline = load_baseline(str(target))
assert 0.0 <= baseline["accuracy"] <= 1.0Storing the data hash in the baseline file matters. A gate can then refuse to compare when the candidate was evaluated on different evaluation data, because the comparison would not be like for like.
def check_comparable(candidate_manifest: dict, baseline: dict) -> list[str]:
if candidate_manifest["data_sha256"] != baseline["data_sha256"]:
return ["baseline was computed on different data; update the baseline deliberately"]
return []
def test_different_data_is_flagged():
candidate = {"data_sha256": "a"}
baseline = {"data_sha256": "b"}
assert len(check_comparable(candidate, baseline)) == 1Whether a data change should fail the build or just warn is a team decision. Failing forces a deliberate baseline update in the same pull request, which makes the change visible to reviewers.
How the pieces connect in CI
The following diagram shows the flow from a pull request to stored artifacts.
Publishing from CI safely
Not every CI run should publish. A pull request from a branch should evaluate and report, but only a merge to main should write to the shared store. Gating on the event keeps experimental models out of the registry. The example below extends the earlier workflow with an artifact upload that runs only on pushes to main.
name: ml-ci-publish
on:
pull_request:
push:
branches: [main]
jobs:
test-and-publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: pip
- run: pip install -r requirements.txt
- name: Fast tests
run: pytest tests/unit tests/data tests/model -q
- name: Train and write manifest
run: python train.py --output artifacts/
- name: Upload model and manifest
if: github.event_name == 'push' && github.ref == 'refs/heads/main'
uses: actions/upload-artifact@v4
with:
name: model-${{ github.sha }}
path: artifacts/Naming the artifact with github.sha ties the stored files to the commit. GitHub's artifact storage is temporary by default, so for a long-lived model you would copy the files to object storage or a registry in a later delivery step. The next chapter covers that handoff.
Common errors
- Overwriting a file at a fixed path. Saving
model.pklto the same location each time erases history. Include the commit hash or content hash in the name, or use a registry that assigns versions. - Hashing the wrong thing. Hashing a pickle file can give different results for identical models, because serialization may embed incidental details. Treat the hash as an identity of that file, not a proof that two models behave identically. Use metrics and behavioral tests to compare behavior.
- Forgetting the environment. Two runs with the same commit and data can differ if a library was upgraded. Record versions in the manifest and keep dependencies pinned.
- Unversioned evaluation data. If the test set changes without a record, metric trends become meaningless. Version it as carefully as the training data.
- Committing large files to Git. Repository history grows permanently, and cloning in CI slows down. Move big files to a content-addressed store before they reach a commit.
- Updating the baseline casually. If anyone can overwrite
baseline.jsonin any pull request, the gate protects nothing. Require review of changes to that file, for example through a code owners rule.
Summary of decisions
- Keep code, configuration, and dependency pins in Git.
- Identify large artifacts by content hash, and keep a pointer to that hash in Git.
- Write a manifest for every training run, and test that it is complete.
- Store the baseline with the data hash it was computed on, and change it only through review.
- Publish only from
main, and name artifacts by commit.
Exercise
A teammate opens a pull request that changes the evaluation CSV and also lowers the stored baseline accuracy from 0.91 to 0.88 so the quality gate passes. What does your versioning setup let a reviewer check, and what should the reviewer ask for?
Show answer
The baseline file stores the data hash, and the candidate manifest stores the hash of the data it was evaluated on. The diff therefore shows that the evaluation data and the baseline changed together. The reviewer should ask why the evaluation data changed, and whether the model on the old commit scores 0.88 on the new data. If it does, the drop comes from the data, not the model, and the baseline update is justified. If it still scores about 0.91, the lowered baseline hides a real regression in the candidate. The reviewer should also confirm that changes to the baseline file require approval from the designated code owners.
Exercise
Write a function check_manifest_matches_model(manifest, model_path) that returns a list of error strings, and is empty only when manifest["model_sha256"] equals the SHA-256 of the file at model_path. Which function from this chapter would you reuse?
Show answer
Reuse file_sha256. For example: def check_manifest_matches_model(manifest, model_path): actual = file_sha256(model_path); return [] if manifest["model_sha256"] == actual else [f"model hash mismatch: manifest {manifest['model_sha256']}, file {actual}"]. Running this check before publishing or deploying catches a model file that was replaced or corrupted after training.