Sub topic 3
Pipelines: tying code, parameters, and data together
This chapter assumes you know Python modules, can commit and ignore files in Git, and have the TrainConfig loader and src/my_project package from earlier chapters. It shows how a pipeline links code, parameters, and data to each output, then covers the habits that make each run repeatable and checkable.
Defining the pipeline
A pipeline is a list of stages. Each stage names a command, its input files, its parameters, and its outputs. A tool such as DVC reruns only the stages whose inputs changed.
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.pklPinning the environment
Record the exact version of every installed library, including indirect dependencies. After you confirm the code works, run pip freeze > requirements.lock. On another machine, run pip install -r requirements.lock. Without this step, a plain pip install numpy next month can install a version that changes your results.
Controlling randomness
Set seeds from the config so that random splits and weight initialization repeat. Seed every library that generates random numbers. Deep learning frameworks need their own seeding calls, and some GPU operations stay nondeterministic even when seeded.
import random
import numpy as np
def set_seed(seed):
random.seed(seed)
np.random.seed(seed)Tracking experiments
Save each run's parameters, metrics, and Git commit so you can compare runs and rebuild the code later.
import json
import subprocess
from datetime import datetime
from pathlib import Path
def log_run(params, metrics, out_dir="runs"):
commit = subprocess.run(
["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True
).stdout.strip()
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
record = {"commit": commit, "params": params, "metrics": metrics}
Path(out_dir).mkdir(exist_ok=True)
path = Path(out_dir) / f"{stamp}-{commit[:8]}.json"
path.write_text(json.dumps(record, indent=2))Testing the parts that can break quietly
Test the code that changes results without raising an error, such as the override parser. A type bug there turns 0.01 into a string and produces no crash.
from my_project.config import apply_overrides
def test_apply_overrides_parses_types():
raw = {"learning_rate": 0.1}
out = apply_overrides(raw, ["learning_rate=0.01", "batch_size=32"])
assert out == {"learning_rate": 0.01, "batch_size": 32}Storing and naming models and outputs
Keep model files in models/ and out of Git. Put the date, commit prefix, and key parameters in the file name, for example model_20261130_a1b2c3d4_lr0.01.pkl. Store large files in a DVC remote or object storage.
Running checks automatically
Configure a CI service to run pytest and dvc repro on every commit. A broken stage or failing test then blocks the merge.
Exercise
Changing only learning_rate in the config reruns the train stage but not the prepare stage. Why?
Show answer
The train stage lists learning_rate under params, so a changed value marks that stage as out of date. The prepare stage does not list it as a dependency, so DVC skips it.