Sub topic 9
Running and comparing experiments
This chapter covers how to try several parameter values against one pipeline, compare the results, and keep only the runs worth keeping. It assumes you have read the earlier chapters on dvc.yaml, params.yaml, and metrics. It also assumes you can commit, branch, and read a Git log. Your train stage should declare train.n_estimators and train.max_depth under params, and write metrics.json as a metrics file.
Why experiments need their own mechanism
Without tooling, trying ten hyperparameter values means editing params.yaml, running dvc repro, and committing each time. You get ten commits on your branch, most of them failures. Or you use ten branches and lose track of which was which.
DVC experiments solve this. An experiment is a run of your pipeline with changed inputs. DVC records it as a hidden Git commit, so your branch history stays clean. You decide afterwards which runs deserve a real commit.
The working model
Four ideas explain how experiments behave.
- Baseline. Every experiment is attached to the Git commit that was
HEADwhen it ran. This commit is the baseline. - Hidden commits. Each experiment is stored as a Git commit under
refs/exps/. You will not see these ingit logorgit branch. They hold thedvc.lock, parameters, and metrics for that run. - Workspace. After
dvc exp runfinishes, the workspace contains that run's files. Your tracked files such asparams.yamlandmetrics.jsonshow as modified ingit status. - Cache. Outputs such as
models/model.pklgo into the DVC cache, as withdvc repro. Two experiments that produce identical outputs share one cached copy.
Running an experiment
Start from a clean, committed baseline. The commands below assume the baseline from the previous chapters is tagged v1.0.
dvc exp run -n n200 -S train.n_estimators=200-S (long form --set-param) overrides a parameter for this run only. The syntax is file:key=value. Without a file name, DVC uses params.yaml. Use several -S flags to change several values.
dvc exp run -n deep -S train.n_estimators=200 -S train.max_depth=12-n gives the experiment a readable name. If you omit it, DVC generates one like exp-a1b2c.
Under the hood, dvc exp run is a dvc repro with temporary parameter changes. The usual change detection applies. If only train.max_depth changed, the prepare stage is skipped and only train reruns. Experiments are cheap when early stages are expensive and stable.
Comparing results
The experiments table
dvc exp showThe table lists the workspace and baseline rows first. Each experiment appears as a row nested under its baseline. Columns include metrics from metrics.json and parameters from params.yaml. The table can be wide. These options help:
dvc exp show --only-changed
dvc exp show --sort-by accuracy --sort-order desc--only-changed hides parameter columns whose values are the same in every row. This leaves the parameters you varied. --sort-by takes a metric or parameter name.
Diffs
For exact differences between two states, use diff commands:
dvc exp diff
dvc exp diff n200 deep
dvc metrics diff HEAD n200With no arguments, dvc exp diff compares the workspace with HEAD, showing both metric and parameter changes. With two names, it compares those experiments. dvc metrics diff and dvc params diff show only one kind of change. They accept any Git revision, so they also work for committed history, for example dvc metrics diff v1.0 HEAD.
Running many experiments
For a sweep, queue the runs first and execute them afterwards:
dvc exp run --queue -n n100 -S train.n_estimators=100
dvc exp run --queue -n n200 -S train.n_estimators=200
dvc exp run --queue -n n400 -S train.n_estimators=400
dvc queue status
dvc queue start --jobs 2Queued experiments are not run immediately. dvc queue start runs them, and --jobs 2 runs two at a time. Each queued run executes in its own temporary copy of the project, so parallel runs do not overwrite each other's metrics.json or model file. Keep the job count within your CPU, memory, and GPU limits.
A shell loop also works for a sweep:
for depth in 3 5 8 12; do
dvc exp run --queue -n "depth-$depth" -S train.max_depth="$depth"
done
dvc queue start --jobs 2Quote the variable so odd values do not split into extra arguments. After the queue finishes, dvc exp show lists every run.
Keeping a result
Experiments live outside your branch history, so keeping one is a deliberate step. There are two ways to do it.
Apply it to the workspace and commit:
dvc exp apply deep
git add dvc.lock params.yaml metrics.json
git commit -m "Train deeper forest, 200 trees, depth 12"dvc exp apply restores the experiment's parameters, metrics, and outputs into your workspace. It also checks out the cached outputs. After it runs, the workspace looks as if you had run dvc repro with those parameters yourself.
Promote it to a branch:
dvc exp branch deep try-deeper-forestThis creates a Git branch containing the experiment's commit. Use it when the experiment needs its own review or further work.
If you saved a run you want to keep but did not start it with dvc exp run, dvc exp save records the current workspace as an experiment.
Sharing and cleaning up experiments
Experiments are local by default. To share one through your Git remote:
dvc exp push origin deep
dvc exp pull origin deepdvc exp push sends the hidden experiment commit to the Git remote. It also uploads the experiment's data to the DVC remote. A teammate then runs dvc exp pull to fetch it.
To discard experiments:
dvc exp remove n100
dvc exp remove --queueThe first removes a named experiment. The second clears queued runs that have not run yet. Removing an experiment deletes only its Git reference. The cached data remains until you run dvc gc, which a later chapter covers.
Common errors and gotchas
- Dirty workspace surprises.
dvc exp runstarts from your current workspace, not only fromHEAD. If you have uncommitted edits totrain.py, the experiment includes them. Commit or stash first when you want a clean baseline. - Parameter not declared.
-S train.dropout=0.3only affects the pipeline if a stage liststrain.dropoutunderparams. If the key is missing fromparams.yaml, the run fails with an error. If the key is not listed underparamsindvc.yaml, the stage does not rerun. Check thatdvc.yamlandparams.yamlagree. - Nothing reran. If you rerun an experiment with identical inputs, DVC finds the same state in
dvc.lockand skips the stages. Usedvc exp run --forcewhen you need to rerun stages with unchanged inputs, for example for a randomized training script. - Missing seed. Two experiments that differ in accuracy by 0.2 points may differ only by randomness. Put the random seed in
params.yamlso it is tracked and repeatable. For close results, repeat runs with several seeds before concluding. - Experiments disappear from view. They stay attached to their baseline commit. After you commit new work,
dvc exp showshows only experiments for the currentHEADby default. Usedvc exp show -Ato list experiments from all commits. - Metrics file not cached. In the earlier
dvc.yaml,metrics.jsonusescache: false, so Git tracks it directly. This lets experiments store metrics in their commit. If you made the metrics file a cached output, the table still works, but the values live in the DVC cache and not in Git.
Choosing between experiments, commits, and branches
| Situation | Use |
|---|---|
| Trying a handful of parameter values quickly | `dvc exp run -S` |
| Running a sweep over many values | `dvc exp run --queue` then `dvc queue start` |
| A result you want in project history | `dvc exp apply`, then `git commit` |
| A change that needs code edits, review, or several commits | `dvc exp branch`, or a normal Git branch |
| Comparing released versions of the model | `dvc metrics diff v1.0 v2.0` |
Experiments suit parameter changes and small code changes you may discard. For larger changes, such as a new feature pipeline, a regular branch gives you review and merge tools.
Putting it together
A typical session looks like this:
git status # confirm a clean baseline
dvc exp run --queue -n n200 -S train.n_estimators=200
dvc exp run --queue -n n400 -S train.n_estimators=400
dvc queue start --jobs 2
dvc exp show --only-changed --sort-by accuracy --sort-order desc
dvc exp diff n200 n400
dvc exp apply n400
git add dvc.lock params.yaml metrics.json
git commit -m "Use 400 trees"The commit now records the winning parameters, the matching dvc.lock, and the metrics. Anyone who checks out this commit and runs dvc pull gets the model that produced those numbers.
Exercise
You queued three experiments with dvc exp run --queue, then ran dvc queue start --jobs 3. dvc exp show lists all three. The best one is named depth-8. Which commands put its parameters, metrics, and model into your project history on the current branch?
Show answer
Run dvc exp apply depth-8 to restore its parameters, metrics, and outputs into the workspace. Then run git add dvc.lock params.yaml metrics.json and git commit. The model file itself is tracked through dvc.lock, and its data goes to the remote with dvc push.
Exercise
A teammate says that after committing new work, dvc exp show no longer lists last week's experiments. Are they lost? How do you see them?
Show answer
No. Experiments stay attached to the baseline commit they were run from, and dvc exp show lists only experiments for the current HEAD by default. Run dvc exp show -A to list experiments from all commits.