Sub topic 18
Versioning data and models next to the environment
This chapter assumes you have read the earlier chapters on lock files, hash pinning, and container images. You should be comfortable with Git and with running a training script. The environment is now pinned, so the last step is to pin the data and the model that go in and out of it.
Why the environment is not enough
A lock file and a base image digest fix the code's runtime. A training run also depends on two other inputs:
- The training data, which often lives outside Git because it is large or private.
- The model artifacts, such as weights, tokenizers, and preprocessing objects, which the run produces and later runs consume.
If the data changes silently, you get a different model from an identical container. The run looks reproducible because the environment is the same, but the result is not. Data is also harder to pin than packages, because there is no registry that gives each version of your dataset an identifier.
What to record for a run
A run is reproducible when you can name every input and check each name against the real thing. For one training run, record these items:
| Input | How to identify it | Where it is stored |
|---|---|---|
| Code | Git commit hash | Git |
| Python packages | Lock file, committed with the code | Git |
| OS, system libraries, CUDA userland | Base image digest | Dockerfile in Git |
| Training data | Content hash or data version ID | Object storage, referenced from Git |
| Random seed and settings | Config file | Git |
| Output model | Content hash plus the run that made it | Object storage or a model registry |
The first three rows are already solved by earlier chapters. The new work is rows four and six.
Identify data by content, not by name
A file name such as train.csv says nothing about what is inside. A path such as s3://bucket/data/latest/ is worse, because "latest" moves. Use the content itself as the identifier. A SHA-256 hash of the bytes changes if any byte changes, so it works for data the same way hashes work for packages in a lock file.
The script below writes a manifest of file hashes and later checks the files against it. You commit the small manifest to Git, and the large files stay elsewhere.
import hashlib
import json
import sys
from pathlib import Path
def sha256_of(path: Path, chunk_size: int = 1 << 20) -> str:
digest = hashlib.sha256()
with path.open("rb") as f:
while chunk := f.read(chunk_size):
digest.update(chunk)
return digest.hexdigest()
def write_manifest(files: list[str], manifest_path: str = "artifacts.json") -> None:
manifest = {name: sha256_of(Path(name)) for name in files}
text = json.dumps(manifest, indent=2, sort_keys=True) + "\n"
Path(manifest_path).write_text(text)
def verify_manifest(manifest_path: str = "artifacts.json") -> bool:
manifest = json.loads(Path(manifest_path).read_text())
ok = True
for name, expected in manifest.items():
path = Path(name)
if not path.exists():
print(f"MISSING {name}")
ok = False
elif sha256_of(path) != expected:
print(f"MISMATCH {name}")
ok = False
return ok
if __name__ == "__main__":
if len(sys.argv) >= 3 and sys.argv[1] == "write":
write_manifest(sys.argv[2:])
elif len(sys.argv) == 2 and sys.argv[1] == "verify":
sys.exit(0 if verify_manifest() else 1)
else:
sys.exit("usage: artifacts.py write FILE... | artifacts.py verify")Use it like this:
python artifacts.py write data/train.csv data/val.csv
git add artifacts.json
git commit -m "Record dataset hashes"
# Later, before training:
python artifacts.py verifyThe script reads the file in 1 MiB chunks, so it works on files larger than memory. It exits with status 1 on any mismatch, which lets a shell script or CI job stop before training starts.
Use a tool when the data gets large
A hand-written manifest is enough for a few files. It does not move the data, deduplicate it, or handle directories with thousands of files. Tools such as DVC solve this. DVC stores a small pointer file in Git and keeps the data in a remote store, such as S3.
dvc init
dvc add data/train.csv
git add data/train.csv.dvc data/.gitignore
git commit -m "Track training data with DVC"
dvc push
# On another machine, after git checkout of the same commit:
dvc pullThe .dvc file contains the content hash. Checking out an old Git commit and running dvc pull gives you the data as it was at that commit. Other options, such as lakeFS, Delta Lake time travel, or object-store versioning, follow the same idea: an immutable version identifier that you commit next to the code.
Version the model that comes out
A trained model is an output, but it becomes an input to evaluation and serving. Treat it the same way:
- Store the weights in object storage or a model registry, not in Git history.
- Record the content hash of the file.
- Record the Git commit, the image digest, the data hashes, and the seed that produced it, in one run record.
- Reference the model by hash or registry version in downstream jobs, never by
model_latest.pt.
Keep preprocessing objects with the model. A tokenizer, a fitted scaler, or a label encoding is part of the model. If you retrain the scaler on new data and keep the old weights, predictions change with no error.
Edge cases and common errors
- Same weights, different file hash. Serialization can embed metadata, such as pickle details or timestamps. Two runs with identical weights may produce different bytes. A file hash tells you which file you have. It does not prove that two runs were equal. To compare runs, load the weights and compare tensors.
- Data changes before it reaches you. A query against a live database or an API returns different rows tomorrow. Snapshot the result to a file, then hash the file.
- Row order and sampling. Shuffling or splitting without a recorded seed gives different train and validation sets from identical files. Record the split seed, or save the split indices as an artifact.
- Unpinned downloads. Code that calls a pretrained-model download by name, such as a hub model without a revision, pulls whatever is current. Pin a specific revision or commit hash, and store a copy of the weights you used.
- Secrets and licenses. Hashes are safe to commit. The data is not always safe to copy. Keep access control on the remote store, and keep the manifest public to the team.
- Verification cost. Hashing a multi-gigabyte dataset takes time. Verify at the start of a run and in CI on a small fixture, and rely on the tool's cached hashes for the full set.
Putting it together
Before training, the job checks the data against the manifest. After training, it writes a run record with the model hash. A minimal record can be a JSON file stored with the model:
import json
import subprocess
from pathlib import Path
commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip()
record = {
"git_commit": commit,
"image_digest": "sha256:<digest of the image you ran>",
"data_manifest": json.loads(Path("artifacts.json").read_text()),
"seed": 42,
}
Path("run_record.json").write_text(json.dumps(record, indent=2) + "\n")Fill in the image digest from your build or registry. If the record cannot be produced automatically, it will be skipped under deadline pressure, so have the training job write it.
Exercise
A teammate reruns your training job from the same Git commit and the same container image digest, and gets a different model. The lock file is unchanged. Name two data-related causes you would check first, and one check for each.
Show answer
First, the training data may have changed. Run the manifest verification (or dvc status) and compare the file hashes with the ones committed at that commit. Second, the train and validation split may differ because the split seed is not recorded or the shuffle is unseeded. Check that the config stores the split seed, or compare the saved split indices between the two runs. Another valid cause is an unpinned pretrained-model download, which you would check by looking for a specified revision.
Exercise
Why is it a mistake to reference a model as models/latest.pt in an evaluation job?
Show answer
The name does not identify content. Retraining overwrites the file, so the same job configuration evaluates different models at different times, and you cannot tell which model a past result belongs to. Reference the model by content hash or registry version instead.