跳到正文

第 11 课 · Pipelines

DVC Templating, foreach and matrix Stages

Avoid copy-paste in dvc.yaml using templating variables, vars, foreach loops and matrix stages, learn how generated stage names work and how to run them.

Real projects repeat themselves. You may train one model per region, or compare several model types on several feature sets. Writing six near-identical stages is tedious and error-prone. dvc.yaml has three tools for this: templating, foreach and matrix.

Templating with ${ }

Put values in a parameters file, then reference them in dvc.yaml.

YAML
# params.yaml
prepare:
  input: data/raw.csv
  output: data/clean.csv
  min_length: 5
YAML
# dvc.yaml
stages:
  prepare:
    cmd: python src/prepare.py --min-length ${prepare.min_length}
    deps:
      - ${prepare.input}
      - src/prepare.py
    outs:
      - ${prepare.output}

params.yaml is always loaded first. You can reach nested keys with dots and list items with [0]. To write a literal ${, escape it with a backslash.

Values can also come from a top-level vars section, which may list other files or inline values:

YAML
vars:
  - config/paths.json
  - threshold: 0.5

The documentation notes that simple values used through ${} are tracked as parameters, but values from vars are not. Do not hide important settings in vars if you want them in parameter comparisons.

Inside cmd only, referencing a whole dictionary such as ${train} expands into command-line options built from its keys. Check the resolved command with a dry run or verbose output (-vv) to be sure you got what you expected.

foreach: one stage per item

YAML
stages:
  train:
    foreach:
      - uk
      - fr
      - jp
    do:
      cmd: python src/train.py --region ${item}
      deps:
        - data/${item}.csv
      outs:
        - models/${item}.pkl

DVC expands this into stages named train@uk, train@fr and train@jp. For a list of dictionaries, you access fields with ${item.key}, and the suffix is the position (train@0). With a dictionary, ${key} is the name suffix and ${item} the value:

YAML
stages:
  build:
    foreach:
      uk: {epochs: 3}
      jp: {epochs: 5}
    do:
      cmd: python src/train.py --region ${key} --epochs ${item.epochs}

The list can also come from params.yaml, for example foreach: ${regions}.

matrix: every combination

A matrix creates one stage for each combination of the listed values.

YAML
stages:
  train:
    matrix:
      model: [cnn, xgb]
      feature: [basic, rich]
    cmd: python src/train.py --model ${item.model} --features ${item.feature}
    outs:
      - models/${item.model}-${item.feature}.pkl

This produces four stages, with names such as train@cnn-basic. ${key} gives the combined name. Note that matrix puts the fields directly under the stage, without a do: block.

Combinations multiply quickly. Three models, four feature sets and five seeds already give 60 stages. Ask whether you really need each one.

Run generated stages

Terminal
# Read-only: run one, a group, or a pattern
dvc stage list
dvc repro train@uk
dvc repro train                  # the whole group
dvc repro --glob "train@cnn-*"

Each generated stage gets its own entry in dvc.lock, so DVC reruns only the ones whose inputs changed.

Try the idea

This stand-in expands a template into concrete stages so you can preview names and commands. It supports only a small part of the real rules.

Python Stand-in: expand foreach and matrix

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Give every generated stage a unique output path, usually by putting ${item} or ${key} in it. Two stages writing the same file is not allowed.

When not to use them

  • If the variants need different logic, separate stages are clearer.
  • If you only want to try several parameter values and compare scores, use experiments (see Running Experiments) rather than permanent stages.
  • Heavy templating makes files hard to review. Keep names readable.

Common templating errors

Problem Likely cause
Key not found Typo, or the file is not listed in vars
Duplicate output Missing ${item} in an output path
Unexpected stage names A list of dictionaries gives numeric suffixes
Command not as expected Quoting; check the resolved command

Common mistake: relying on a vars value for a setting that should appear in experiment comparisons. Move such values to params.yaml and track them as parameters.

A small worked design

Imagine you train a model for three regions, and each needs its own raw file and minimum row count. A clean design keeps the differences in data, not in copy-pasted YAML:

YAML
# params.yaml
regions:
  uk: {min_rows: 500}
  fr: {min_rows: 300}
  jp: {min_rows: 800}
YAML
# dvc.yaml
stages:
  train:
    foreach: ${regions}
    do:
      cmd: python src/train.py --region ${key} --min-rows ${item.min_rows}
      deps:
        - src/train.py
        - data/${key}.csv
      outs:
        - models/${key}.pkl

Adding a fourth region now means adding one entry to the parameters file and one data file. A reviewer sees a two-line change instead of a new block of stage definitions.

Check the expansion

Run dvc stage list after editing and count the generated names. Then run dvc repro --dry to read the resolved commands. If a value is missing for one item, you want to discover it here, not after hours of training. Keep generated names short and meaningful, because they appear in logs, in dvc.lock and in code review. Prefer dictionaries over lists when order is not important, so each stage has a stable, readable suffix: inserting an item in the middle of a list of dictionaries shifts the numbers and makes DVC treat stages differently.

Keep templates readable

Templating saves typing, but each ${} adds a hop for the reader. A person who opens dvc.yaml must also open the parameters file to know which path or value is used. Use it where repetition would be a real risk, such as the same path in three places or the same stage for many regions. For a value that appears once and never changes, writing it directly is often clearer.

Add a short comment above a templated stage that says what it expands into, for example "one training stage per region listed in params.yaml". When you review a change to the list, remember that removing an item removes a stage. Check whether its old outputs, plots or metrics are still referenced elsewhere, and delete or update those references in the same pull request.

Finally, treat the expanded names as part of your interface. CI scripts or documentation may target train@uk. Renaming a key breaks those references, so search for the old name before you change it.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which names does a foreach over the list [uk, jp] in stage train create?

    Generated stages use the stage name, an @ sign and the item or index.
  2. 2. A matrix has 3 models, 4 feature sets and 5 seeds. How many stages are created?

    Matrix creates every combination: 3 x 4 x 5 = 60.
  3. 3. Which parameters file is loaded for templating by default?

    params.yaml is always loaded first.
  4. 4. Why include ${item} in an output path of a foreach stage?

    Two stages cannot share one output.

Summary

  • ${} inserts values from params.yaml or vars; vars values are not tracked.
  • foreach creates one stage per list or dictionary item, using a do: block.
  • matrix creates every combination of the listed values.
  • Generated stages are named with @ and can be run alone, as a group or by pattern.
  • Preview expansion and keep output paths unique.

Next: Advanced Stage Options

你的学习进度保存在此浏览器中,无需账号。