Versioning Data and Models Next to Code
See why a file path is not a data version, identify files by content hash, version a dataset and a model with DVC pointer files, a content-addressed cache and a remote, switch between two versions of the data, and write a lineage record that ties a model to exact data, code and configuration.
Contentsand lesson path
On this page
- Why it matters
- Content hashes name the data
- DVC: a pointer in Git, the bytes in a cache
- A corrected dataset is a new version
- Check your understanding
- Apply it
- Review prompt
Lessons of Experiment Tracking & Reproducibility
- Why Results Become Unrepeatable Concept · 15 min
- Lab: Track and Compare Runs Lab · 25 min
- Versioning Data and Models Next to Code Concept · 20 min
- Worked Example: Rebuild Last Month's Model from Scratch Worked example · 25 min
- Model Registry: Versions, Aliases and Promotion Rules Concept · 15 min
- Check: Can You Reproduce It? Knowledge check · 8 questions
What you will learn
- Version datasets and models alongside code (for example with DVC or content hashes) so that every reported result traces back to exact data, code and configuration.
01. Why it matters
A run record that says "trained on data/train.csv" names a location, not content. If someone corrects a few rows and saves the file under the same name, the record still points at the path, but the bytes behind it are new, and last month's result can no longer be traced or rebuilt. To trace a result to its data, you need to record which exact content was used and keep that content available.
Git does this for code, but it is a poor fit for datasets and model files. Every version of a large file stays in the history, so every clone downloads all of them. Data versioning tools such as DVC (Data Version Control) split the job: Git keeps a small text file per dataset that holds a hash of its content, and the bytes themselves live in a cache and in separate storage. This lesson walks through that mechanism and then writes a lineage record: the link from a model back to the data, code and configuration that produced it.
mkdir data-versioning && cd data-versioning
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "dvc==3.67.1" "scikit-learn==1.9.1"02. Content hashes name the data
A cryptographic hash such as SHA-256 or MD5 turns any sequence of bytes into a short, fixed-length string. The same bytes always give the same hash, and changing even one byte gives a completely different one. That makes a hash a name for content: two files with the same hash hold the same bytes, whatever they are called. The script below writes a small customer dataset with a fixed seed, then hashes it, a copy under another name, and a version with one value changed.
"""Write data/train.csv: 200 customers. With --fix, negative spend is corrected to 0."""
import csv
import sys
from pathlib import Path
import numpy as np
rng = np.random.default_rng(7)
tenure = rng.integers(1, 72, size=200) # months as a customer
spend = rng.normal(60, 25, size=200).round(2) # monthly spend
calls = rng.poisson(1.5, size=200) # support calls
churn = (rng.random(200) < 1 / (1 + np.exp(0.05 * tenure - 0.6 * calls))).astype(int)
if "--fix" in sys.argv:
spend = np.clip(spend, 0, None) # data correction
Path("data").mkdir(exist_ok=True)
with open("data/train.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["tenure", "monthly_spend", "support_calls", "churned"])
w.writerows(zip(tenure, spend, calls, churn))
print(f"wrote data/train.csv: 200 rows, {int((spend < 0).sum())} with negative spend")import hashlib
import shutil
from pathlib import Path
def sha256(path, chunk=1 << 20):
"""Hash a file's bytes in 1 MiB chunks, so large files fit in memory."""
h = hashlib.sha256()
with open(path, "rb") as f:
while block := f.read(chunk):
h.update(block)
return h.hexdigest()
shutil.copy("data/train.csv", "copy-with-another-name.csv")
edited = Path("data/train.csv").read_text().replace("9.12", "9.13", 1)
Path("one-value-changed.csv").write_text(edited)
for name in ["data/train.csv", "copy-with-another-name.csv", "one-value-changed.csv"]:
print(f"{name:28} {sha256(name)[:16]}")python make_data.py
python hashing.pywrote data/train.csv: 200 rows, 2 with negative spend
data/train.csv 44e1e1637701c427
copy-with-another-name.csv 44e1e1637701c427
one-value-changed.csv c9f3316abab4d081The renamed copy has the same hash as the original; changing 9.12 to 9.13 in one row changes the hash completely. So if a run records 44e1e163…, anyone can check later whether the file they hold is the one that was used, whatever it is called now. Note that the dataset has 2 rows with negative monthly spend, a data error you will correct below.
03. DVC: a pointer in Git, the bytes in a cache
dvc add hashes a file with MD5, stores its bytes in the cache (.dvc/cache), and writes a small pointer file, data/train.csv.dvc, that records the hash, the size and the path. The cache is content-addressed: each file is stored under a path made from its own hash (the first two characters become a folder name). Identical content is stored once, however many times you add it. MD5 is used here to detect changes, not as a defence against someone forging a file on purpose.
In a real project you run dvc init inside a Git repository. This lesson uses dvc init --no-scm (no source-control manager) so that everything runs without Git; the DVC commands are the same, and the Git steps are shown afterwards.
dvc init --no-scm -q
dvc add data/train.csv
grep -E "md5|size|path" data/train.csv.dvc
md5sum data/train.csv
find .dvc/cache -type f- md5: 67a36d352240cc2460329c6c6c3e0f4e
size: 2802
hash: md5
path: train.csv
67a36d352240cc2460329c6c6c3e0f4e data/train.csv
.dvc/cache/files/md5/67/a36d352240cc2460329c6c6c3e0f4eThe md5 in the pointer equals the MD5 of the file (md5sum is md5 on macOS), and the cache file sits at 67/a36d35…, its own hash. The pointer is about 100 bytes whether the dataset is 2.8 KB, as here, or 20 GB. On some file systems the pointer also contains isexec: true, which records that the file had its executable bit set.
The cache is local. To share data and survive a lost laptop, DVC copies cached files to a remote: a folder, an S3 or Google Cloud bucket, an SSH server and others. Here the remote is a folder next to the project. After dvc push, you can delete both the data and the cache and get the file back from its hash with dvc pull.
dvc remote add -d storage ../dvc-storage
dvc push
rm -r .dvc/cache data/train.csv
dvc pull
md5sum data/train.csvSetting 'storage' as a default remote.
1 file pushed
A data/train.csv
1 file fetched and 1 file added
67a36d352240cc2460329c6c6c3e0f4e data/train.csv04. A corrected dataset is a new version
Now fix the two negative values. The rule that keeps results traceable is to treat a published data version as immutable: a correction does not edit version 1, it creates version 2, and version 1 stays available under its hash. The commands keep a copy of the version 1 pointer (in Git, the commit history would do this), regenerate the file with --fix, and ask dvc status what changed.
Then they run lineage.py, a training script that checks the data before using it: it compares the MD5 of data/train.csv with the hash in the pointer, and refuses to train if they differ. Without that check, a record could carry the pointer's hash while the model was trained on other bytes.
"""Train from the versioned data and write a lineage record next to the model."""
import hashlib
import json
import pickle
from pathlib import Path
import numpy as np
import yaml # PyYAML, installed with DVC
from sklearn.linear_model import LogisticRegression
CONFIG = {"C": 1.0, "max_iter": 1000,
"features": ["tenure", "monthly_spend", "support_calls"]}
def digest(path, algo):
return hashlib.new(algo, Path(path).read_bytes()).hexdigest()
pointer = yaml.safe_load(Path("data/train.csv.dvc").read_text())["outs"][0]
actual = digest("data/train.csv", "md5")
if actual != pointer["md5"]: # the file is not the version on record
raise SystemExit(f"data/train.csv is {actual[:8]} but its .dvc file says "
f"{pointer['md5'][:8]}: run dvc add or dvc checkout")
data = np.genfromtxt("data/train.csv", delimiter=",", names=True)
X = np.column_stack([data[c] for c in CONFIG["features"]])
y = data["churned"]
model = LogisticRegression(C=CONFIG["C"], max_iter=CONFIG["max_iter"]).fit(X, y)
Path("models").mkdir(exist_ok=True)
Path("models/churn.pkl").write_bytes(pickle.dumps(model))
record = {"data": {"path": "data/train.csv", "md5": actual},
"code_sha256": digest(__file__, "sha256")[:12],
"config": CONFIG,
"model": {"path": "models/churn.pkl",
"sha256": digest("models/churn.pkl", "sha256")},
"train_accuracy": round(model.score(X, y), 3)}
Path("models/lineage.json").write_text(json.dumps(record, indent=2))
print("data md5: ", record["data"]["md5"])
print("code sha256:", record["code_sha256"])
print("config: ", json.dumps({k: CONFIG[k] for k in ("C", "max_iter")}),
"+", len(CONFIG["features"]), "features")
print("train accuracy:", record["train_accuracy"], "-> models/lineage.json")cp data/train.csv.dvc pointer-v1.txt
python make_data.py --fix
dvc status
python lineage.pywrote data/train.csv: 200 rows, 0 with negative spend
data/train.csv.dvc:
changed outs:
modified: data/train.csv
data/train.csv is fcbf06e5 but its .dvc file says 67a36d35: run dvc add or dvc checkoutdvc status notices that the file no longer matches its pointer, and lineage.py stops with both hashes. Record the new version with dvc add and dvc push, then train. The model file is versioned the same way, with its own pointer.
dvc add data/train.csv
dvc push
find .dvc/cache -type f | sort
python lineage.py
dvc add models/churn.pkl
ls models1 file pushed
.dvc/cache/files/md5/67/a36d352240cc2460329c6c6c3e0f4e
.dvc/cache/files/md5/fc/bf06e553dc52d6436d159fd6c80c96
data md5: fcbf06e553dc52d6436d159fd6c80c96
code sha256: 0d2cb1294a93
config: {"C": 1.0, "max_iter": 1000} + 3 features
train accuracy: 0.805 -> models/lineage.json
churn.pkl
churn.pkl.dvc
lineage.jsonThe cache now holds both versions, each under its own hash, and the remote has both too. models/lineage.json records the data hash (fcbf06e5…), the hash of the training code, the full configuration and the hash of the saved model. That is the minimum a reported number needs to be traceable: which data, which code, which configuration. In a Git repository you would record the commit as well, and in a tracker you would log the same fields with the run, as tags or parameters. The model hash is not printed because the bytes of a saved model can differ slightly between machines and library versions.
Going back to version 1 needs only its pointer. dvc checkout makes the working file match whatever pointer is present, taking the bytes from the cache, or from the remote after a dvc pull.
cp pointer-v1.txt data/train.csv.dvc
dvc checkout data/train.csv.dvc
md5sum data/train.csvM data/train.csv
67a36d352240cc2460329c6c6c3e0f4e data/train.csvThe M means DVC modified the working file to match the pointer, and the MD5 is back to 67a36d35…. With Git, the pointer copies are commits. You commit each .dvc file next to the code that uses it, so checking out an old commit and running dvc checkout gives you the code and the data of that moment together. DVC also writes a .gitignore entry so that Git never stores the data itself.
git init && dvc init # dvc init without --no-scm
dvc add data/train.csv # writes data/train.csv.dvc and data/.gitignore
git add data/train.csv.dvc data/.gitignore .dvc/config
git commit -m "Data v1: 200 customers"
dvc push # bytes to the remote, by hash
# later: go back to the data (and code) of an older commit
git checkout <commit> -- data/train.csv.dvc
dvc checkout data/train.csv.dvc # or dvc pull on a fresh clone05. Check your understanding
06. Apply it
In the practice project, put the training data under version control.
- Run
dvc initin the project's Git repository,dvc addthe dataset, commit the pointer and push the data to a remote (a folder outside the repository is enough to start). - Make the training script hash the data it actually reads and refuse to run if the hash does not match the pointer, as
lineage.pydoes. - Log the data hash, the commit and the resolved configuration with every tracked run, so that each row of your results table names its data version.
- Make a corrected version of the data, train on it, then go back to the first version with
git checkoutanddvc checkout, and check that you get the first result again.
07. Review prompt
Without looking back, explain why a file path is not a data version and what a content hash gives you instead; describe what dvc add writes, where the bytes go, and why identical content is stored once; say what dvc push, dvc pull and dvc checkout each do; explain why a corrected dataset should become a new version instead of replacing the old one; and list the fields a lineage record needs so that a reported metric can be traced back.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.