Sub topic 7
Reproducible pipelines with dvc.yaml
Earlier chapters covered tracking single files with dvc add. This chapter chains those files into a pipeline. A pipeline is a set of commands whose inputs and outputs DVC knows about, so it can rerun only what changed.
Prerequisites
This chapter assumes you can:
- Run
dvc init,dvc add, andgit commiton a project. - Read YAML.
- Run a short Python script that reads and writes files.
- Understand that
data/raw.csvis tracked by a.dvcpointer file, as in the earlier chapters.
The example needs pip install dvc pandas scikit-learn pyyaml. It also assumes data/raw.csv has numeric feature columns and a label column.
Why `dvc add` is not enough
dvc add versions a file, but it does not record how the file was made. If a teammate asks how models/model.pkl was produced, a .dvc file cannot answer. A shell history or a README can, but both go stale.
A pipeline records the answer in dvc.yaml, which Git versions. Each stage declares the command to run, what the command reads, and what it writes. From those declarations DVC does three things:
- It builds a dependency graph of your stages.
- It detects which stages are out of date.
- It reruns only those stages, in the correct order.
The example project
Two scripts form the pipeline. The first removes rows with empty fields.
# src/prepare.py
import csv
import sys
from pathlib import Path
src, dst = sys.argv[1], Path(sys.argv[2])
dst.mkdir(parents=True, exist_ok=True)
with open(src, newline="") as f_in, open(dst / "clean.csv", "w", newline="") as f_out:
reader = csv.DictReader(f_in)
writer = csv.DictWriter(f_out, fieldnames=reader.fieldnames)
writer.writeheader()
for row in reader:
if all((v or "").strip() != "" for v in row.values()):
writer.writerow(row)The second trains a model and writes a metrics file. It reads hyperparameters from params.yaml.
# src/train.py
import json
import pickle
import sys
from pathlib import Path
import pandas as pd
import yaml
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
prepared, model_path = Path(sys.argv[1]), Path(sys.argv[2])
params = yaml.safe_load(open("params.yaml"))["train"]
df = pd.read_csv(prepared / "clean.csv")
X, y = df.drop(columns="label"), df["label"]
X_tr, X_te, y_tr, y_te = 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,
).fit(X_tr, y_tr)
model_path.parent.mkdir(parents=True, exist_ok=True)
with open(model_path, "wb") as f:
pickle.dump(model, f)
with open("metrics.json", "w") as f:
json.dump({"accuracy": model.score(X_te, y_te)}, f)The params.yaml file sits at the project root.
train:
n_estimators: 100
max_depth: 5Anatomy of dvc.yaml
The dvc.yaml file lists stages under a top-level stages key.
stages:
prepare:
cmd: python src/prepare.py data/raw.csv data/prepared
deps:
- src/prepare.py
- data/raw.csv
outs:
- data/prepared
train:
cmd: python src/train.py data/prepared models/model.pkl
deps:
- src/train.py
- data/prepared
params:
- train.n_estimators
- train.max_depth
outs:
- models/model.pkl
metrics:
- metrics.json:
cache: false| Field | Meaning |
|---|---|
| `cmd` | The shell command DVC runs for this stage. |
| `deps` | Files or directories the command reads. A change to any of them makes the stage stale. |
| `params` | Keys read from `params.yaml`. Only these keys count, so editing an unrelated key does not invalidate the stage. |
| `outs` | Files or directories the command writes. DVC caches them, like `dvc add` does. |
| `metrics` | Output files that hold numbers. `cache: false` keeps the file in Git instead of the DVC cache. |
You can write this file by hand, or generate each stage with dvc stage add:
dvc stage add -n prepare \
-d src/prepare.py -d data/raw.csv \
-o data/prepared \
python src/prepare.py data/raw.csv data/preparedBoth ways produce the same dvc.yaml. Editing by hand is usually easier once you have more than a couple of stages.
How stages connect
You never declare an order. DVC matches one stage's outs to another stage's deps. Here data/prepared is an output of prepare and a dependency of train, so train runs after prepare.
Run dvc dag to print this graph in the terminal. It is a quick way to check that DVC sees the links you meant to create.
Running the pipeline with dvc repro
dvc repro reads dvc.yaml, finds stale stages, and runs them in order.
dvc repro
git add dvc.yaml dvc.lock params.yaml metrics.json data/.gitignore models/.gitignore
git commit -m "Train baseline model"
git tag v1.0Note that data/raw.csv is already tracked by dvc add. A pipeline may depend on a tracked file but must not also list it as an output.
On the first run, both stages execute. DVC then writes dvc.lock and adds the large outputs to .gitignore files, which is why those files appear in the git add line. Run dvc repro again with no changes and you will see messages like Stage 'prepare' didn't change, skipping.
What dvc.lock records
dvc.yaml says what the pipeline is. dvc.lock says what happened the last time it ran. For every stage it stores the command, the hash of each dependency, the value of each parameter, and the hash of each output.
An abbreviated entry looks like this:
schema: '2.0'
stages:
train:
cmd: python src/train.py data/prepared models/model.pkl
deps:
- path: data/prepared
hash: md5
md5: 3f1c0a9e2b7d4c5a8e6f1b2d9c0a7e41.dir
params:
params.yaml:
train.max_depth: 5
train.n_estimators: 100
outs:
- path: models/model.pkl
hash: md5
md5: 91b0c2f7a4e85d3c6b1f0e9d2a7c4b58Commit dvc.lock with your code. Together, a Git commit's dvc.yaml, dvc.lock, and params.yaml pin the exact inputs and outputs of the run. This is how git checkout plus dvc checkout can restore a model, as shown in the previous chapter.
How DVC decides a stage is stale
For each stage, DVC compares the current state with dvc.lock. A stage reruns if any of these is true:
- The
cmdstring changed. - A dependency's content hash changed.
- A listed parameter value changed.
- An output is missing or its hash no longer matches the lock.
- The stage has no entry in
dvc.lock.
The comparison uses content hashes, not timestamps. Touching a file without changing it does not trigger a rerun. A stale stage also makes every stage downstream of it stale, because their dependencies change.
Before a stage runs, DVC deletes its declared outputs. This guarantees the command regenerates them instead of silently reusing leftovers. If you need an output to survive between runs, such as a model checkpoint you resume from, add persist: true to that output.
Useful dvc repro options
| Command | Effect |
|---|---|
| `dvc repro --dry` | Show which stages would run, without running them. |
| `dvc repro train` | Run `train` and the upstream stages it needs. |
| `dvc repro -s train` | Run only `train`, ignoring upstream stages. |
| `dvc repro -f` | Force every stage to rerun, even when unchanged. |
| `dvc repro --downstream prepare` | Run `prepare` and everything after it. |
Use -s carefully. It can leave the pipeline in a state where upstream outputs no longer match what train used.
Common errors
An output is missing after the command succeeds. If train.py writes model.pkl somewhere other than the path in outs, DVC fails with an error saying it cannot find the output. The outs path must match what the script writes exactly.
An undeclared dependency. If train.py reads data/extra.csv but deps does not list it, changing that file will not trigger a rerun. The pipeline looks up to date but is wrong. List every file the command reads, including the script itself.
Overlapping outputs. Two stages cannot write the same output, and a stage output cannot already be tracked by dvc add. DVC reports an overlap error. Remove the old .dvc file with dvc remove data/prepared.dvc, or change the paths.
Committing outputs to Git. DVC writes .gitignore entries so large outputs stay out of Git. If you use git add . and a hand-edited ignore file hides that, you can end up committing a model by accident. Check git status before committing.
A metrics file is cached but Git cannot diff it. Without cache: false, metrics.json goes to the DVC cache and Git sees only an ignored path. Set cache: false for small text files you want to review in pull requests.
Several similar stages with foreach
When many stages share a shape, foreach generates them from a list, so you do not copy the block. This example runs the same prepare script for two datasets.
stages:
prepare:
foreach:
- train
- test
do:
cmd: python src/prepare.py data/${item}.csv data/prepared/${item}
deps:
- src/prepare.py
- data/${item}.csv
outs:
- data/prepared/${item}DVC expands this into stages named prepare@train and prepare@test. You can run one with dvc repro prepare@train.
Sharing the pipeline's outputs
Stage outputs go into the DVC cache like any dvc add file. After dvc repro, run dvc push to upload them to the remote. A teammate can then clone the repository and run dvc pull to get the model and prepared data, or dvc repro to rebuild them. If every cached output is available, dvc repro skips the stages and only restores the files.
Pipeline checklist
Before committing a pipeline change, check these points:
- Every file a command reads appears in
deps, including the script. - Every file a command writes appears in
outsormetrics. dvc dagshows the links you expect.- A second
dvc reproskips every stage. dvc.yaml,dvc.lock,params.yaml, and small metrics files are committed together.
Exercise
You change the line max_depth: 5 to max_depth: 8 in params.yaml, then run dvc repro. Which stages run and why? What happens if you instead change only an unrelated key, such as featurize.window: 3, that no stage lists under params?
Show answer
Only train runs. It lists train.max_depth under params, and the value now differs from the one recorded in dvc.lock. prepare does not read that parameter, so it is skipped. If you change an unrelated key that no stage lists, DVC compares only the listed keys. Nothing is stale, so dvc repro skips every stage.
Exercise
A teammate says dvc repro reports everything up to date, but you know train.py reads data/labels.csv, and you just edited that file. What is the most likely cause, and how do you fix it?
Show answer
data/labels.csv is not listed under deps for the train stage, so DVC does not hash it. Add it to deps in dvc.yaml, then run dvc repro. DVC will see the dependency as new, rerun train, and record the file's hash in dvc.lock. Commit both dvc.yaml and dvc.lock.