Sub topic 10
Pipelines: Tying Code, Parameters, and Data Together
This chapter assumes you can read a YAML file, run Python modules from the command line, and use Git. It also assumes you have the layout, config loading, and data folders from the earlier chapters. Here we connect those pieces so one command rebuilds a result and every output can be traced to the inputs that produced it.
Why a pipeline
Without a pipeline, a project is a set of scripts you run by hand in an order you remember. Three problems follow:
- You rerun everything after a small change, or you rerun too little and use stale outputs.
- Nobody can tell which code, parameters, and data produced a given model file.
- A new teammate has to ask you for the order of commands.
A pipeline is a declared list of stages. A stage is one step with a command, the files it reads (dependencies), the parameters it uses, and the files it writes (outputs). Because these are declared, a tool can work out what is out of date and run only that part.
The stage model
Think of each stage as a function whose inputs are files and parameter values, and whose outputs are files. The tool records a fingerprint (a hash) of every input and output. On the next run, it compares the current fingerprints to the recorded ones. If nothing a stage depends on has changed, it skips the stage and reuses the stored outputs.
The arrow from data/processed to the train stage is what links the stages. You never state "run prepare before train". The tool infers the order because one stage's output is another stage's dependency.
Declaring stages in dvc.yaml
DVC (Data Version Control) is a common tool that implements this model. Its pipeline file, dvc.yaml, sits in the project root. The file below matches the layout from the earlier chapters.
stages:
prepare:
cmd: python -m my_project.data.prepare
deps:
- src/my_project/data/prepare.py
- data/raw
outs:
- data/processed
train:
cmd: python -m my_project.train --config configs/train.yaml
deps:
- src/my_project/train.py
- data/processed
params:
- configs/train.yaml:
- learning_rate
- batch_size
outs:
- models/model.pklEach key has a specific job:
| Key | Meaning | What happens when it changes |
|---|---|---|
| `cmd` | The shell command that runs the stage | The stage reruns |
| `deps` | Files or folders the stage reads | The stage reruns if their content hash changes |
| `params` | Named keys inside a parameter file | The stage reruns if those values change |
| `outs` | Files or folders the stage writes | Stored by the tool and restored on demand |
Run the whole pipeline with dvc repro. The first run executes both stages. A second run with no changes prints that the stages are unchanged and does nothing.
Parameters are tracked per key
The params entry lists learning_rate and batch_size, not the whole file. This matters. The config also holds data_path and seed. If you list only two keys, editing batch_size reruns the train stage, but a change to some unrelated key in the same file does not.
The consequence is that every value that affects the output must be listed somewhere. If seed changes results and you leave it out of params, the tool will not rerun training when you change it, and you will keep a model made with the old seed. Treat the params list as a statement of what the stage's output depends on.
Compare the effect of each kind of edit:
| Edit | Stages that rerun |
|---|---|
| Change `learning_rate` in `configs/train.yaml` | `train` only |
| Edit `src/my_project/train.py` | `train` only |
| Edit `src/my_project/data/prepare.py` | `prepare`, then `train` because its input changed |
| Replace the files in `data/raw` | `prepare`, then `train` |
| Edit a comment in `README.md` | None |
Keeping the stage and the config in sync
The pipeline passes --config configs/train.yaml to the training module. The training code should load that file with the typed loader from the config chapter, so the values the tool tracks are the same values the code reads.
import argparse
from my_project.config import load_config
from my_project.seed import set_seed
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--config", required=True)
parser.add_argument("overrides", nargs="*")
args = parser.parse_args()
cfg = load_config(args.config, args.overrides)
set_seed(cfg.seed)
print(f"training with lr={cfg.learning_rate}, batch_size={cfg.batch_size}")
if __name__ == "__main__":
main()This sketch assumes set_seed lives in src/my_project/seed.py, and it stops at the point where your real training loop would go.
There is one gotcha with overrides. If you run python -m my_project.train --config configs/train.yaml learning_rate=0.01 by hand, the code uses 0.01, but the file on disk still says 0.001. The pipeline tool reads the file, so it records the old value. The recorded run no longer matches the real one. To keep them aligned, change values in the YAML file (or use the tool's own experiment command, which applies the override and records it). Use ad hoc command-line overrides only for throwaway exploration.
Locking results with dvc.lock
After a run, DVC writes dvc.lock. It lists the hash of every dependency, parameter value, and output for each stage. You commit dvc.yaml and dvc.lock to Git. The large files themselves go into DVC's cache and, from there, to remote storage, as covered in the data versioning chapter.
This gives each Git commit a complete record:
dvc.yamlsays how the results are made.dvc.locksays exactly which inputs produced the current outputs.- The cache or remote holds the actual bytes.
To reproduce an old result, check out the old commit and run dvc checkout. The data and model files from that commit are restored. If you run dvc repro instead, the tool rebuilds only what does not match the lock file.
Common failure modes
- Undeclared dependency. The code reads a file that is not in
deps, such as a lookup table inconfigs/. Editing that file does not trigger a rerun. Fix it by listing every file the command reads. - Undeclared output. The stage writes a file that is not in
outs. It is not stored or restored, so a teammate who runsdvc checkoutdoes not get it. - Hidden inputs. The code reads the current date, an environment variable, or a database. None of these appear in the fingerprints, so results can change with no rerun. Move such values into the config, or snapshot the data into a tracked file.
- Overlapping outputs. Two stages write to the same path. The tool rejects this because it cannot say which stage owns the file.
- Tracking the same file in Git and DVC. If a path listed in
outsis also committed to Git, the tool reports a conflict. Add the path to.gitignore; DVC does this for you when you use its commands to add outputs. - Nondeterministic stages. A stage with an unseeded random choice gives different outputs for identical inputs. The pipeline will treat it as reproducible, but it is not. Seed the code, as in the earlier chapter, and expect some framework operations to still vary.
Alternatives and when to choose them
You do not need DVC to use the idea. A Makefile also declares targets, dependencies, and commands, and it reruns by file modification time. It is simple and widely available, but it compares timestamps, not content hashes, and it does not track parameter values or store outputs. Orchestrators such as Airflow or Prefect schedule and monitor jobs across machines, but they are aimed at running production workflows, not at versioning the link between data, parameters, and code.
| Need | Reasonable choice |
|---|---|
| A few scripts, a single machine, no data versioning | Makefile or a shell script |
| Reproducible experiments with large data and per-parameter tracking | DVC-style pipeline |
| Scheduled production jobs across machines with retries | An orchestrator, often combined with the above |
Pick the lightest tool that still answers the question "what produced this file?".
A practical checklist
- Give each stage one job: preparing data, training, or evaluating.
- List every file the command reads under
depsand every file it writes underouts. - List every parameter that affects the output under
params. - Run
dvc reproafter any change, anddvc statusbefore each commit. - Commit
dvc.yamlanddvc.locktogether with the code change that caused them.
Exercise
Your train stage lists only learning_rate and batch_size under params. You change seed from 42 to 7 in configs/train.yaml and run dvc repro. The tool reports nothing to do. Why, and how do you fix it?
Show answer
The tool tracks parameters by key, and seed is not listed under params for the train stage, so its change is invisible to the fingerprint. The existing model was trained with seed 42 and is now stale. Add seed to the params list for the train stage (and any other stage whose output depends on it), then run dvc repro so the stage reruns and dvc.lock records the new value.
Exercise
A teammate runs python -m my_project.train --config configs/train.yaml batch_size=64 and commits the resulting model with an unchanged dvc.lock. What is wrong with this record?
Show answer
The override changed the value used in training but not the value in configs/train.yaml, which is what the pipeline records. The lock file still says batch_size is 32, so the model appears to come from different settings than it did. Edit the value in the YAML file and run dvc repro, or use the tool's experiment command so the override is recorded.