Guided lab · Build the four-stage pipeline¶
Time: 5 hours. Tools: Python 3.11/3.12, DVC 3.x, Git. Local disk only.
Scenario and business problem¶
The ETA model now trains reproducibly by hand, one command per stage. That is still a person remembering an order. The team wants a single command that runs whatever is stale, and no work when nothing changed: the data team retrains often, and a 15-minute experiment that reruns a 10-minute preparation step is a 15-minute experiment nobody repeats.
You will also be asked a question that sounds trivial and is not: if I change one hyperparameter, what reruns? Your answer has to be right before you run, not after.
Skills practised¶
- Declaring stages, dependencies, parameters, and outputs.
- Reading and predicting cache invalidation.
- Making a training entry point deterministic and idempotent.
- Separating a stateful model from a stateless feature function.
- Measuring stage cost.
Prerequisites¶
Modules 02–04, including the DVC remote and a dataset tracked with dvc add.
Input data¶
data/raw/trips.csv (1,200 rows), tracked by DVC from Module 04. If you are starting fresh, regenerate it with the course generator; the checksum in data/raw/trips.csv.dvc must match.
Directory layout¶
raviride-eta/
├── dvc.yaml
├── dvc.lock
├── params.yaml
├── data/processed/{train,test}.csv
├── data/features/{train,test}.csv
├── models/{model.joblib,run_meta.json}
├── metrics.json
└── src/raviride_eta/{prepare,featurise,train,evaluate}.py
Part 1: make the stages deterministic (60 minutes)¶
- Ensure every stage is runnable with
python -m raviride_eta.<stage>and does its work insidemain(). - Set
random_statefromparams.yamland pass it toRandomForestRegressor. Setn_jobs=1so timings and floating-point reduction are comparable between runs. - Sort the frame by
requested_atafter loading and before splitting, then reset the index. - Run the sequence twice and compare:
Checkpoint 1: run the block again; the hash and the MAE are unchanged. If they differ, find the source before adding DVC - a pipeline caches nondeterminism just as faithfully.
python -m raviride_eta.prepare; python -m raviride_eta.featurise python -m raviride_eta.train; python -m raviride_eta.evaluate (Get-FileHash models/model.joblib -Algorithm SHA256).Hash
Part 2: declare the pipeline (90 minutes)¶
- Write
dvc.yamlwith the four stages from the worked example. Include every source file the stage imports indeps; a missing import is a hidden input. - Add
features.settoparams.yamland to thetrainandevaluateparams lists. - Run:
Checkpoint 2: all four stages run, in order, and
dvc reprodvc.lockis created. Commitdvc.yamlanddvc.locktogether.
Recovery: if a stage fails with ModuleNotFoundError, DVC used a different interpreter - activate the environment in the same shell. If it fails with a path error, your stage used the current working directory instead of config.PROJECT_ROOT.
Part 3: predict, then confirm, the cache (45 minutes)¶
- Write your prediction in
docs/pipeline-evidence.mdas a table: change → stages you expect to rerun. - Run
dvc reprowith no changes. Checkpoint 3:Data and pipelines are up to date. - Change
model.n_estimatorsfrom 200 to 120 and rundvc repro. Checkpoint 4: exactlytrainandevaluaterun; the metrics change slightly (reference: MAE 2.777 → 2.787). - Restore 200, rerun, and confirm the original metrics return. This also proves the cache is content-based, not "last result wins".
- Delete
data/processed/and rundvc repro. Checkpoint 5:prepareandfeaturiseare cached and their outputs are checked out, rather than recomputed. Explain in your evidence file why this is possible and why it is not the same as "the stage ran".
Part 4: add a feature and watch the graph (45 minutes)¶
- Add one derived feature to
features.py(for exampleis_weekend_nightordistance_per_passenger). Add it to thefullfeature set. - Predict which stages will rerun before running.
Checkpoint 6:
featurise,train, andevaluatererun;preparedoes not. Ifpreparereran, you listedfeatures.pyas one of its dependencies by mistake - a good illustration of how a wrongdepsentry over-invalidates. - Record the metric change. If the feature does not help, say so and remove it; a pipeline that makes experiments cheap should also make it easy to discard them.
Part 5: measure and document (30 minutes)¶
- Time a fresh run (
Remove-Item -Recurse -Force .dvc\cachefirst) and a cached run:Measure-Command { dvc repro } - Record per-stage durations from the fresh run (the stage output prints are enough;
dvc.lockrecords timings). - Export the DAG with
dvc dag --mermaidand paste it into the evidence file. - Commit. The evidence file should contain: the prediction table, the three run outputs, timings, the DAG, and one paragraph on what remains non-deterministic.
Expected outputs¶
| Output | Reference value |
|---|---|
| Fresh run | four stages, MAE 2.777, RMSE 5.259, R² 0.8298 |
| Cached run | Data and pipelines are up to date. |
| Parameter change | train + evaluate only; MAE 2.787 at 120 trees |
| Model hash, two runs | identical SHA-256 |
| DAG | raw → prepare → featurise → {train} → evaluate |
Acceptance criteria¶
| Criterion | Passes when |
|---|---|
| Determinism | Two runs give identical metrics; artefact hash identical or the difference explained |
| Declaration | Every file a stage reads is in deps; every value it reads is in params |
| Prediction | Your expected-rerun table matches the observed runs |
| Reuse | The feature function is callable on a single row with the same result as on the batch |
| Evidence | The evidence file contains real outputs, timings, and the DAG |
| Hygiene | dvc.lock is committed; generated data is not in Git |
Troubleshooting¶
| Symptom | Cause | Fix |
|---|---|---|
Stage 'x' didn't change but you changed a file |
File not listed in deps |
Add it, then dvc repro |
| Everything reruns every time | A dependency changes on each run (timestamp, log file) | Remove the volatile file from deps; write it outside the project |
dvc repro says outputs are missing, then skips |
Outputs deleted but cache intact | Expected: DVC checks out from cache. Use --force to truly rerun |
PermissionError on models/ |
Stage run from the wrong directory | Anchor paths to PROJECT_ROOT |
| Metrics identical after a parameter change | Parameter not listed in params, or hard-coded |
Add to dvc.yaml and read it from load_params() |
dvc.lock merge conflict |
Two people repro'd different versions | Resolve by rerunning dvc repro on the merged dvc.yaml; never hand-merge hashes |
Cleanup¶
dvc pushafter the final run so the cache is recoverable.- Remove scratch timing files.
- No services were started.
Optional extensions¶
- Skip a stage deliberately. Use
dvc repro --single-item trainto rerun one stage. Readdvc repro --helpand explain in one sentence when this is safe and when it desynchronises the pipeline. - Second dataset version. Change
data.test_daysto 10, rerun, and record which stages rerun. Then explain why the metric is not comparable to the previous one (different question, not worse model). - Stage signature. Add a
--predict-fileoption totrainthat writes one prediction for a fixed input row. Run it before and after a retrain and compare. This is the beginning of the serving contract in Module 10.