Sub topic 10
Versioning trained models
This chapter assumes you have read the earlier chapters. You should know dvc add, the cache, remotes with dvc push and dvc pull, dvc checkout, and the dvc.yaml and params.yaml basics. You should also be comfortable with Git tags and branches.
A model is a pipeline output
A trained model is a large binary file produced by code, data, and parameters. Git cannot store it well, and a bare file name like model.pkl says nothing about how it was made. DVC handles this in two ways:
- The model is declared as an
outsentry of thetrainstage. DVC then hashes it, caches it, and keeps it out of Git. dvc.lockrecords the hash of every dependency, parameter value, and output for that run.
So a model version is a Git commit that contains dvc.yaml, dvc.lock, params.yaml, and your code. The model file itself lives in the cache and the remote, found by hash.
A training stage that produces a model
This script reads parameters from params.yaml, trains a classifier, and writes the model and a metrics file. It expects data/prepared/data.csv with a label column.
import json
import pickle
import sys
from pathlib import Path
import pandas as pd
import yaml
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
prepared_dir, model_path = sys.argv[1], sys.argv[2]
with open("params.yaml") as f:
params = yaml.safe_load(f)["train"]
df = pd.read_csv(Path(prepared_dir) / "data.csv")
X, y = df.drop(columns=["label"]), df["label"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42
)
model = RandomForestClassifier(
n_estimators=params["n_estimators"],
max_depth=params["max_depth"],
random_state=42,
)
model.fit(X_train, y_train)
Path(model_path).parent.mkdir(parents=True, exist_ok=True)
with open(model_path, "wb") as f:
pickle.dump(model, f)
accuracy = accuracy_score(y_test, model.predict(X_test))
with open("metrics.json", "w") as f:
json.dump({"accuracy": accuracy}, f)The train stage in dvc.yaml is the one from the pipelines chapter. Its outs entry, models/model.pkl, is the model. The metrics entry marks metrics.json with cache: false, so Git stores that small file directly and git diff can show it.
What dvc.lock records
After dvc repro, the lock file contains one entry per stage. Here is the train entry, with hashes shortened for display:
schema: '2.0'
stages:
train:
cmd: python src/train.py data/prepared models/model.pkl
deps:
- path: data/prepared
hash: md5
md5: 3f1c9a7e2b4d4c0f8a61d5e7b9c20a14.dir
size: 48213
nfiles: 1
- path: src/train.py
hash: md5
md5: 7be0d3a15c8f42e9a0d6b1c3f5e78d92
size: 1186
params:
params.yaml:
train.max_depth: 5
train.n_estimators: 100
outs:
- path: models/model.pkl
hash: md5
md5: c41a8f0e6d2b57a93e0f1b8d4c6a7e35
size: 2914507Read it as a receipt. It says that this exact code, data, and parameter set produced a model whose content hash is c41a.... The .dir suffix marks a directory hash. Commit dvc.lock together with the code. If you leave it uncommitted, the Git history has no link to a specific model file.
Creating a model version
A version is a commit plus a tag. Run the pipeline, commit the small files, tag the commit, and upload the model.
dvc repro
git add dvc.yaml dvc.lock params.yaml metrics.json
git commit -m "Train baseline model"
git tag -a model-v1.0 -m "Baseline random forest, 100 trees"
dvc push
git push origin main --tagsRun dvc push before you share the Git commit. If a teammate pulls your commit and the model is not on the remote yet, dvc pull fails because nothing exists to download.
DVC does not add a .dvc file for models/model.pkl. Stage outputs are tracked through dvc.lock. DVC also adds the output path to .gitignore for you. Check that models/model.pkl appears in models/.gitignore before you commit.
Tag naming
Tags are the only version labels DVC relies on, so choose a convention and keep it. A common one is <artifact>-v<major>.<minor>, such as model-v1.0. A repository that holds several models may add the model name, such as fraud-model-v1.2. Annotated tags (git tag -a) carry an author and message, which helps when you need to know why a version was cut.
Restoring an older model
To get an older model, switch Git to the tagged commit and then let DVC sync the workspace.
git checkout model-v1.0
dvc pull models/model.pkldvc pull downloads the file if it is missing from the local cache and then places it in the workspace. When the cache already holds the file, dvc checkout alone is enough. Use dvc pull when you are unsure. Naming the target restricts the download to the model, so you do not fetch every dataset.
You can also check the state without changing anything:
dvc statusIf the output reports models/model.pkl as deleted or modified, the workspace does not match dvc.lock. If it reports that the stage is up to date, you hold exactly the model from that commit.
Comparing model versions
Because metrics.json is in Git, you can compare metrics between any two tags without retraining:
dvc metrics diff model-v1.0 model-v1.1
dvc params diff model-v1.0 model-v1.1The first command shows the change in each metric. The second shows which parameter values changed. Together they answer the usual question, "what did we change to get this accuracy?". The comparison reads files from Git, so neither model needs to be downloaded.
Promoting an experiment to a version
Experiments from dvc exp run are not Git commits on your branch. When one is worth keeping, promote it explicitly. First list the results:
dvc exp showThen choose one of two routes. dvc exp apply <exp-name> puts that experiment's files and parameters into your workspace, so you can review and commit them yourself. dvc exp branch <exp-name> better-model creates a Git branch holding the experiment. After you commit and tag it, dvc push uploads the new model.
Experiment models that you never promote can still occupy the cache. Chapter 13 covers cleaning them up.
Using a model from another place
A serving job or another team often needs one model version without cloning your whole workflow. dvc get downloads a tracked file from a Git repository and a revision, with no DVC project needed on the consumer side:
dvc get https://github.com/example-org/churn-model models/model.pkl --rev model-v1.0 -o deploy/model.pklThis command downloads a plain copy. It leaves no link to the source repository. If the consumer should be notified when the model changes, use dvc import with the same arguments. It records the source repository and revision in a .dvc file, and dvc update later pulls a newer version. Pin --rev to a tag, not to a branch name, so a deployment cannot change silently.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `dvc add models/model.pkl` fails with an error that the output is already specified in a stage | The file is already an output of `train`. Stage outputs are tracked through `dvc.yaml` and `dvc.lock`. | Do not run `dvc add` on stage outputs. Use `dvc repro`. |
| `dvc pull` reports missing cache files | The model was never pushed, or the remote in `.dvc/config` is wrong | Ask the author to run `dvc push` from the commit's machine. Check `dvc remote list`. |
| `dvc checkout` reports the file is missing from the cache | You switched commits without downloading | Run `dvc pull`, then `dvc checkout` if needed. |
| Same inputs, different model hash | Training is not deterministic (no random seed, parallel nondeterminism) | Set seeds, as `random_state=42` does above. Accept that some GPU training will still vary. |
| `dvc repro` reruns nothing after you edit the model file by hand | The file is an output, and `dvc status` shows it as modified. Edits to outputs do not trigger a rerun. | Run `dvc repro --force train`. Better, never edit outputs. |
| Model file appears in `git status` | The output path is missing from `.gitignore` | Run `dvc add` or `dvc repro` again so DVC rewrites the ignore entry. Never `git add` the model. |
When tags are not enough
Git tags and dvc.lock give you a reproducible, auditable history. They do not provide stage labels such as "staging" or "production", approval workflows, or a catalog that non-developers can browse. If you need those, you can add a model registry on top. The DVC data remains the storage layer, and the registry points at your Git tags. For many teams, a tag convention plus a protected branch is enough and has fewer moving parts.
Exercise
A teammate clones your repository at tag model-v1.0 and runs dvc pull, but it fails with missing cache files for models/model.pkl. Training ran fine on your machine and dvc.lock is committed. What most likely went wrong, and what do you run?
Show answer
You committed and tagged the model version without running dvc push, so the model exists only in your local cache and not on the remote. From the repository at that tag, run dvc push (check dvc remote list first if you are unsure which remote is the default). Your teammate then runs dvc pull again.
Exercise
You want to compare the accuracy of model-v1.0 and model-v1.1, and see which parameters changed, without downloading either model file. Which two commands do you use, and why can they work without the model files?
Show answer
Run dvc metrics diff model-v1.0 model-v1.1 and dvc params diff model-v1.0 model-v1.1. Both read metrics.json and params.yaml from the two Git revisions. Those files are stored in Git (cache: false for the metrics file), so the large model files are not needed.
Exercise
Your inference service should always use exactly the model released as model-v1.0 and be updatable later through a deliberate action. Should you use dvc get or dvc import, and what do you pass as --rev?
Show answer
Use dvc import, because it records the source repository and revision in a .dvc file and lets you move to a newer version later with dvc update. Pass the tag model-v1.0 as --rev, not a branch name, so the version cannot change without an explicit update.