TExcelTAD
Home › Deployment & MLOps: Serving, Pipelines, Monitoring › Versioning Data and Models with DVC

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

Git repositorycode, params.yamltrain.csv.dvc (md5) workspacetrain.csv (git-ignored) local cache.dvc/cache/files/md5/ remoteS3, GCS, SSH, folder names add / checkout push pull

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).

python · try it yourself
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:

  1. git init and dvc init (creates .dvc/ with its config; both are committed to Git).
  2. dvc add data/train.csv: hashes the file, moves it into the cache, links it back into the workspace, writes the pointer data/train.csv.dvc, and adds /train.csv to data/.gitignore so Git ignores the data itself.
  3. Commit the pointer and the .gitignore with Git.
  4. Change the data, dvc status shows it, dvc add again, commit again.
  5. Configure a remote and dvc push the 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.
  6. Go back in time: check out an old pointer with Git, then dvc checkout to make the workspace match it.
python · try it yourself
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.dvc is five lines of YAML: the md5 of the content, its size in bytes (50), the hash algorithm and the path. This is what Git versions. It is tiny whatever the size of the data.
  • dvc status notices that the workspace file no longer matches the pointer (modified: data/train.csv), the data analogue of git 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) and files/md5/5c/bd68d7... (v2). The v2 hash starts 5cbd68d7, exactly the hash the from-scratch store computed for the same bytes: DVC's address is the plain MD5 of the file.
  • dvc push uploaded 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, use dvc push --all-commits (or --all-branches, --all-tags).
  • Checking out the pointer from two commits back and running dvc checkout brings back the 3-row file; checking out the current pointer restores 5 rows. In normal use you would git checkout <commit> (or a branch, or a tag such as data-2026-11) and then dvc checkout; a colleague without the cache runs dvc pull instead, 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 .dir manifest 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) and dvc import, which also records where the data came from so dvc update can 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 gc removes 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 add writes the .gitignore entry; commit it. A git add -A before dvc add puts 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 run dvc push; dvc install sets such hooks up).
  • Assuming the remote holds all history. As the example shows, a plain dvc push uploads the current version. Use --all-commits for 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

  1. 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?
  2. Why does train.csv.dvc change when a single character in train.csv changes, and why is that what you want?
  3. A colleague clones the repository and gets train.csv.dvc but no train.csv. What do they run, and what must you have done first?
Answers
  1. About 20 MB (the 10 changed files) plus a new small .dir manifest. The other 990 files have the same hashes and are reused.
  2. 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.
  3. dvc pull (fetch the files named by the pointers from the remote and check them out). It only works if you ran dvc push for that version after dvc add, and they need read access to the remote.

Test yourself

What does Git store for a file tracked with DVC?

  1. The file itself
  2. A small .dvc pointer file with the content's md5 hash, size and path
  3. A compressed copy of the file
  4. Nothing

In the from-scratch store, version 2 changed one of three files. How many new files did the cache get?

  1. 0
  2. 1
  3. 3
  4. 6

After dvc push in the example, the remote held only the newest version of train.csv. Why?

  1. The remote was full
  2. By default dvc push uploads what the current workspace's pointers reference; --all-commits pushes history
  3. v1 was deleted by dvc add
  4. Remotes keep one version

How do you restore the data as it was at an older commit?

  1. dvc add the old file
  2. Check out the commit (or its .dvc file) with Git, then run dvc checkout (or dvc pull without a local cache)
  3. git revert the data
  4. Download it from the tracker