Sub topic 13
Tracking experiments
This chapter assumes you have a source package, a typed YAML config with command-line overrides, and a pipeline that produces a model from versioned data. You also need to be comfortable with Git commits and basic Python. Here you will add the last piece that makes runs comparable: a record of what each run did.
Why a run needs a record
A pipeline can reproduce a result. It does not tell you which of your last forty runs gave the best validation score, or which settings produced it. Without a record, people rely on memory, file names such as model_final_v2.pkl, and notebook cells that were overwritten.
Experiment tracking means saving one structured record per run. That record lets you answer three questions later:
- What settings did this run use?
- What did it score?
- Which code and data produced it?
The record is useful only if it is written automatically. A record that depends on someone remembering to copy numbers into a spreadsheet will have gaps.
What to record
Each run should store the following fields.
| Field | Example | Why it matters |
|---|---|---|
| Run ID | `20261130-094955-a3f9` | Gives each run a unique, sortable name |
| Parameters | `learning_rate=0.01`, `batch_size=32` | Lets you compare settings across runs |
| Metrics | `val_accuracy=0.912` | Lets you rank runs |
| Git commit | `7c1e9d2` | Identifies the exact code version |
| Dirty flag | `true` | Warns that uncommitted changes were present |
| Data version | hash from `dvc.lock` | Identifies the exact data used |
| Seed | `42` | Needed to repeat the random choices |
| Artifact paths | `models/model.pkl` | Links the record to its outputs |
The parameters come from the config object, after overrides are applied. Record the final resolved values, not the YAML file on disk. If you ran with learning_rate=0.01 on the command line, the file still says 0.001, and a record copied from the file would be wrong.
How a run is tracked
The training script creates a run, logs parameters first, logs metrics as they become available, and closes the run. Every run, including a failed one, should leave a record.
A minimal tracker with the standard library
You can start without any external tool. The following module writes one JSON file per run. It uses only the standard library, so it runs as shown. It reads the config object from the earlier chapter through dataclasses.asdict.
import json
import subprocess
import uuid
from dataclasses import asdict
from datetime import datetime, timezone
from pathlib import Path
def git_info():
try:
commit = subprocess.run(
["git", "rev-parse", "--short", "HEAD"],
capture_output=True, text=True, check=True,
).stdout.strip()
status = subprocess.run(
["git", "status", "--porcelain"],
capture_output=True, text=True, check=True,
).stdout.strip()
except (subprocess.CalledProcessError, FileNotFoundError):
return {"commit": None, "dirty": None}
return {"commit": commit, "dirty": bool(status)}
class Run:
def __init__(self, config, root="runs"):
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
self.run_id = f"{stamp}-{uuid.uuid4().hex[:4]}"
self.dir = Path(root) / self.run_id
self.dir.mkdir(parents=True)
self.record = {
"run_id": self.run_id,
"status": "running",
"params": asdict(config),
"git": git_info(),
"metrics": {},
"artifacts": [],
}
self.save()
def log_metric(self, name, value):
self.record["metrics"][name] = value
self.save()
def log_artifact(self, path):
self.record["artifacts"].append(str(path))
self.save()
def finish(self, status="finished"):
self.record["status"] = status
self.save()
def save(self):
with open(self.dir / "run.json", "w") as f:
json.dump(self.record, f, indent=2)Use it in train.py so that a crash still leaves a record:
run = Run(config)
try:
# ... train the model, compute val_accuracy ...
run.log_metric("val_accuracy", 0.912)
run.log_artifact("models/model.pkl")
run.finish()
except Exception:
run.finish("failed")
raiseThe save() call after every update means the file is current even if the process is killed. The cost is a small write per metric, which is fine for summary metrics and wasteful if you log every training step.
Comparing runs
Because each record is a JSON file, comparison is a short script. This one loads every record, drops runs that did not finish, and sorts by validation accuracy.
import json
from pathlib import Path
def load_runs(root="runs"):
for path in Path(root).glob("*/run.json"):
with open(path) as f:
yield json.load(f)
finished = [r for r in load_runs() if r["status"] == "finished"]
finished.sort(key=lambda r: r["metrics"].get("val_accuracy", 0), reverse=True)
for r in finished[:5]:
p = r["params"]
print(r["run_id"], r["metrics"]["val_accuracy"], p["learning_rate"], p["batch_size"])This works for tens of runs. Past that, you want filtering, plots, and a shared view, which is what dedicated tools provide.
Choosing a tool
Tools such as MLflow, Weights & Biases, and DVC's experiment commands implement the same idea with more features. They add a web interface, charts of metrics over time, run comparison tables, and artifact storage. The choice depends on constraints rather than quality.
| Concern | Local JSON files | Self-hosted server | Hosted service |
|---|---|---|---|
| Setup effort | None | Moderate | Low |
| Team sharing | Manual, through Git or a shared disk | Built in | Built in |
| Data leaves your network | No | No | Yes |
| Charts and filtering | Write your own | Included | Included |
| Ongoing cost | None | Hosting and upkeep | Subscription |
Keep your own code independent of the tool. If the training script calls run.log_metric(...) on a small wrapper, you can change the backend later by editing one module. If MLflow calls are scattered through the code, switching means touching every file.
Common errors
- Logging the file, not the resolved config. Overrides are lost. Log the dataclass instance after overrides.
- Ignoring uncommitted changes. A commit hash alone is misleading if the working tree was modified. Record the dirty flag, and consider refusing to start a run you intend to publish when the tree is dirty.
- Leaving out the data version. The same commit with different data gives different results. Copy the data hash from
dvc.lock, or record the file checksum, in the run record. - Overwriting metrics. Logging
val_accuracyonce per epoch into a single key keeps only the last value. Log a list or a series with a step number when the curve matters. - Losing failed runs. Failures are information. A run that diverged with a high learning rate tells you where the useful range ends.
- Comparing metrics from different splits. If the data version or split seed differs, a higher score may not mean a better model.
- Storing artifacts inside the run record. Keep large files in artifact storage and store only paths or hashes in the record.
Connecting tracking to the pipeline
The pipeline from the previous chapters says how to produce outputs. The tracker says what happened in a particular execution. They overlap on parameters, which is intentional: dvc.yaml declares the tracked parameters for deciding when to rerun, and the run record stores their values for comparison. Both read the same config, so they cannot disagree.
Exercise
A teammate reports that run 20261130-094955-a3f9 scored 0.912, and you cannot reproduce it. Its record shows commit 7c1e9d2, dirty: true, and learning_rate: 0.01. Name two pieces of information that are missing or uncertain, and say what you would add to the tracker.
Show answer
First, dirty: true means the code that ran differed from commit 7c1e9d2, so checking out that commit does not recover it. Add a saved diff (output of git diff) to the run directory, or block runs on a dirty tree. Second, the record has no data version, so the input data may have changed since the run. Add the data hash from dvc.lock. The seed is also absent from the listed fields; confirm it is in params and add it if not.
Exercise
Your script logs val_accuracy once per epoch with run.log_metric("val_accuracy", value), using the Run class above. After training, the record shows a single number. Why, and how would you change the class to keep the whole curve?
Show answer
log_metric assigns to self.record["metrics"][name], so each call replaces the previous value and only the last epoch remains. Change it to store a list of {"step": step, "value": value} entries, for example by taking a step argument and appending to self.record["metrics"].setdefault(name, []). The comparison script would then read the last entry, or the maximum, instead of a single number.