Versioning Data and Models with DVC
Git is excellent at versioning code and poor at versioning data. A training set of 20 GB in a Git repository makes every clone download every version ever committed, and GitHub refuses files over 100 MB. So teams keep data elsewhere: a bucket, a shared drive, a folder called data_final_v3_fixed. Then the experiment tracker records "trained on s3://bucket/train.csv", someone overwrites that file next month, and the run can no longer be reproduced.
DVC (Data Version Control) solves this with one idea: keep the data out of Git, but keep a small pointer file in Git that names the exact content by its hash. Checking out an old commit gives you the old pointer, and DVC fetches the matching bytes. Data versions then move together with code versions, through the same commits, branches and pull requests.
The idea: content-addressed storage
The store that makes this work is content-addressed: a file is saved under the hash of its bytes, not under its name. Three properties follow. Identical content is stored once, so a new version of a data set only costs the files that changed. A hash names one exact content forever, so a pointer can never silently start meaning something else. And the hash doubles as an integrity check: reading a file back and hashing it again detects corruption. Git itself stores objects this way, as do Docker image layers and ML artifact stores.
From scratch: a tiny DVC
The example stores a data set of three files, then a second version in which only train.csv gained two rows. Files go into cache/<first two hex digits>/<rest of the hash>, DVC's layout; the "pointer" for a whole directory is the hash of its sorted manifest (DVC also writes such a manifest, as a .dir entry in its cache).
import hashlib, json, os, shutil, tempfile
root = tempfile.mkdtemp()
cache = os.path.join(root, "cache")
def md5(data: bytes) -> str:
return hashlib.md5(data).hexdigest()
def add(files: dict) -> dict:
"""Store every file in the cache under its hash; return a small pointer that names the version."""
entries = []
for name, data in sorted(files.items()):
h = md5(data)
path = os.path.join(cache, h[:2], h[2:]) # cache/ab/cdef...: the same layout DVC uses
if not os.path.exists(path): # identical content is stored once
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "wb") as f:
f.write(data)
entries.append({"relpath": name, "md5": h, "size": len(data)})
manifest = json.dumps(entries, sort_keys=True).encode()
return {"md5": md5(manifest) + ".dir", "nfiles": len(entries), "entries": entries}
def checkout(pointer: dict) -> dict:
out = {}
for e in pointer["entries"]:
with open(os.path.join(cache, e["md5"][:2], e["md5"][2:]), "rb") as f:
data = f.read()
assert md5(data) == e["md5"], "corrupted cache" # the hash also verifies the content
out[e["relpath"]] = data
return out
def cache_files():
return sum(len(fs) for _, _, fs in os.walk(cache))
v1 = {"train.csv": b"income,debt,default\n52,0.31,0\n38,0.62,1\n71,0.12,0\n",
"test.csv": b"income,debt,default\n45,0.40,0\n29,0.75,1\n",
"labels.txt": b"0=repaid\n1=default\n"}
p1 = add(v1)
print("v1 pointer:", p1["md5"], f"({p1['nfiles']} files) | cache files: {cache_files()}")
v2 = dict(v1, **{"train.csv": v1["train.csv"] + b"64,0.20,0\n33,0.81,1\n"}) # two new training rows
p2 = add(v2)
print("v2 pointer:", p2["md5"], f"({p2['nfiles']} files) | cache files: {cache_files()}")
for e1, e2 in zip(p1["entries"], p2["entries"]):
print(f" {e1['relpath']:10} {'changed' if e1['md5'] != e2['md5'] else 'same '} {e2['md5'][:8]} {e2['size']} bytes")
old = checkout(p1) # any version is a pointer away
print("checkout v1: train.csv has", old["train.csv"].count(b"\n") - 1, "rows; v2 has",
v2["train.csv"].count(b"\n") - 1)
shutil.rmtree(root)v1 pointer: da06842bc793e59c9095ac0cfdf83720.dir (3 files) | cache files: 3
v2 pointer: edfe7b60ae3ca1a75acd137eaad0a517.dir (3 files) | cache files: 4
labels.txt same ec761960 19 bytes
test.csv same 16deaab1 40 bytes
train.csv changed 5cbd68d7 70 bytes
checkout v1: train.csv has 3 rows; v2 has 5
Version 2 has a new directory hash, but the cache grew by one file, not three: labels.txt and test.csv have the same hashes as before and are reused. That is why keeping every version of a large data set is affordable when versions differ in a few files (it is not when every file changes, for instance a full re-export with new timestamps in every row). Checking out v1 needs only its pointer: the three hashes find the bytes, and the hash check guards against a corrupted cache.
DVC in practice
The same workflow with DVC 3.67, recorded in the course's Docker image (DVC is a command-line tool; the example calls it through python -m dvc from Python so that it can print each step). Steps:
git initanddvc init(creates.dvc/with its config; both are committed to Git).dvc add data/train.csv: hashes the file, moves it into the cache, links it back into the workspace, writes the pointerdata/train.csv.dvc, and adds/train.csvtodata/.gitignoreso Git ignores the data itself.- Commit the pointer and the
.gitignorewith Git. - Change the data,
dvc statusshows it,dvc addagain, commit again. - Configure a remote and
dvc pushthe cache to it. Here the remote is a local folder/tmp/store; in a team it is an S3, GCS or Azure bucket, an SSH server or a shared drive. - Go back in time: check out an old pointer with Git, then
dvc checkoutto make the workspace match it.
import os, subprocess, sys
import dvc # the import marks the example as recorded
os.makedirs("proj"); os.chdir("proj")
def sh(*args):
r = subprocess.run(list(args), capture_output=True, text=True)
print(r.stdout + r.stderr, end="")
def dvc_(*args):
sh(sys.executable, "-m", "dvc", *args)
def commit(msg):
sh("git", "add", "-A")
sh("git", "-c", "user.name=ana", "-c", "user.email=ana@example.com", "commit", "-q", "-m", msg)
sh("git", "init", "-q")
dvc_("init", "-q")
commit("init dvc")
os.makedirs("data")
with open("data/train.csv", "w") as f:
f.write("income,debt,default\n52,0.31,0\n38,0.62,1\n71,0.12,0\n")
print("$ dvc add data/train.csv")
dvc_("add", "-q", "data/train.csv")
print("$ cat data/train.csv.dvc"); print(open("data/train.csv.dvc").read(), end="")
print("$ cat data/.gitignore"); print(open("data/.gitignore").read(), end="")
commit("data v1")
with open("data/train.csv", "a") as f:
f.write("64,0.20,0\n33,0.81,1\n")
print("$ dvc status"); dvc_("status")
dvc_("add", "-q", "data/train.csv")
commit("data v2: two new rows")
print("$ git log --format=%s"); sh("git", "log", "--format=%s")
print("$ dvc remote add -d store /tmp/store && dvc push")
dvc_("remote", "add", "-d", "store", "/tmp/store")
dvc_("push")
commit("configure remote")
def files(top):
return sorted(os.path.relpath(os.path.join(d, f), top) for d, _, fs in os.walk(top) for f in fs)
print("local cache:", files(".dvc/cache"))
print("remote :", files("/tmp/store"))
print("$ git checkout HEAD~2 -- data/train.csv.dvc && dvc checkout")
sh("git", "checkout", "HEAD~2", "--", "data/train.csv.dvc")
dvc_("checkout")
print("rows now:", sum(1 for _ in open("data/train.csv")) - 1)
print("$ git checkout HEAD -- data/train.csv.dvc && dvc checkout")
sh("git", "checkout", "HEAD", "--", "data/train.csv.dvc")
dvc_("checkout")
print("rows now:", sum(1 for _ in open("data/train.csv")) - 1)$ dvc add data/train.csv
$ cat data/train.csv.dvc
outs:
- md5: 584c2aafe2c2c34562718b338f61bc4b
size: 50
hash: md5
path: train.csv
$ cat data/.gitignore
/train.csv
$ dvc status
data/train.csv.dvc:
changed outs:
modified: data/train.csv
$ git log --format=%s
data v2: two new rows
data v1
init dvc
$ dvc remote add -d store /tmp/store && dvc push
Setting 'store' as a default remote.
1 file pushed
local cache: ['files/md5/58/4c2aafe2c2c34562718b338f61bc4b', 'files/md5/5c/bd68d7b046da377b5e95141ea94860']
remote : ['files/md5/5c/bd68d7b046da377b5e95141ea94860']
$ git checkout HEAD~2 -- data/train.csv.dvc && dvc checkout
M data/train.csv
rows now: 3
$ git checkout HEAD -- data/train.csv.dvc && dvc checkout
M data/train.csv
rows now: 5
Read it from the top:
- The pointer file
train.csv.dvcis five lines of YAML: themd5of the content, itssizein bytes (50), the hash algorithm and the path. This is what Git versions. It is tiny whatever the size of the data. dvc statusnotices that the workspace file no longer matches the pointer (modified: data/train.csv), the data analogue ofgit status.- Git's history is the history of data versions:
data v1,data v2: two new rows. - The cache holds both versions, under
files/md5/58/4c2aaf...(v1) andfiles/md5/5c/bd68d7...(v2). The v2 hash starts5cbd68d7, exactly the hash the from-scratch store computed for the same bytes: DVC's address is the plain MD5 of the file. dvc pushuploaded 1 file: by default it pushes what the current workspace's pointers reference, so the v1 file stayed only in the local cache. To back up every version referenced anywhere in history, usedvc push --all-commits(or--all-branches,--all-tags).- Checking out the pointer from two commits back and running
dvc checkoutbrings back the 3-row file; checking out the current pointer restores 5 rows. In normal use you wouldgit checkout <commit>(or a branch, or a tag such asdata-2026-11) and thendvc checkout; a colleague without the cache runsdvc pullinstead, which fetches from the remote and checks out.
A trained model is versioned exactly the same way: dvc add models/model.joblib (or, better, let a pipeline stage produce it as an output), and the pointer in Git ties the model's bytes to the commit that made it.
What else DVC does
From the DVC documentation, as remembered; not run here:
- Pipelines (
dvc.yaml,dvc repro) that rerun only the stages whose inputs changed, with parameters (params.yaml) and metrics files: the subject of the next lesson. - Directories are tracked as one unit (
dvc add data/images/), with a.dirmanifest in the cache, like the from-scratch version. - Sharing:
dvc pull(fetch + checkout),dvc fetch(download only),dvc get <repo-url> <path>(download a file from another DVC repository without cloning it) anddvc import, which also records where the data came from sodvc updatecan follow it. - Link types: to avoid two copies of a large file (cache and workspace), DVC can use reflinks, hardlinks or symlinks instead of copies (
dvc config cache.type), with copy as the safe default where the file system supports nothing better. - Garbage collection:
dvc gcremoves cache entries no longer referenced by the chosen commits, branches or tags; run it carefully, the history you do not list is deleted from the cache. - Alternatives with the same goal: Git LFS (large files stored by pointer, without pipelines), lakeFS (Git-like branches over a data lake), Delta Lake and Apache Iceberg (table formats with snapshots and time travel), and the dataset versioning built into ML platforms. Dataset versioning compares these from the data side.
Pitfalls
- Committing the data to Git by accident.
dvc addwrites the.gitignoreentry; commit it. Agit add -Abeforedvc addputs the file in Git history for good. - Forgetting
dvc push. The commit with the new pointer is pushed to GitHub, the data is only on your laptop, and nobody else can check out that version. Push both (a Git pre-push hook can rundvc push;dvc installsets such hooks up). - Assuming the remote holds all history. As the example shows, a plain
dvc pushuploads the current version. Use--all-commitsfor backups. - Hashing is not anonymising. A data version in a public repository reveals nothing, but the remote holds the real data: its access rules and retention limits (deletion requests!) still apply, and deleting a row from a version means rewriting that version.
- Huge numbers of tiny files. Millions of small files make hashing and transfer slow; pack them (archives, Parquet, WebDataset shards) before versioning.
Practice
- A data set has 1,000 image files of 2 MB each. Version 2 changes 10 of them. How much does the DVC cache grow?
- Why does
train.csv.dvcchange when a single character intrain.csvchanges, and why is that what you want? - A colleague clones the repository and gets
train.csv.dvcbut notrain.csv. What do they run, and what must you have done first?
Answers
- About 20 MB (the 10 changed files) plus a new small
.dirmanifest. The other 990 files have the same hashes and are reused. - The pointer contains the MD5 of the content; any change of the bytes changes the hash (and usually the size). A pointer that did not change would let two different data sets claim the same version.
dvc pull(fetch the files named by the pointers from the remote and check them out). It only works if you randvc pushfor that version afterdvc add, and they need read access to the remote.
Test yourself
What does Git store for a file tracked with DVC?
- The file itself
- A small
.dvcpointer file with the content's md5 hash, size and path - A compressed copy of the file
- Nothing
In the from-scratch store, version 2 changed one of three files. How many new files did the cache get?
- 0
- 1
- 3
- 6
After dvc push in the example, the remote held only the newest version of train.csv. Why?
- The remote was full
- By default
dvc pushuploads what the current workspace's pointers reference;--all-commitspushes history - v1 was deleted by
dvc add - Remotes keep one version
How do you restore the data as it was at an older commit?
dvc addthe old file- Check out the commit (or its
.dvcfile) with Git, then rundvc checkout(ordvc pullwithout a local cache) git revertthe data- Download it from the tracker