Sub topic 6
Recording What Each Run Did
Assume you know Python functions and dataclasses, the basic train–validate–test workflow, Git, and how to run a Python module from a command line. This chapter focuses on experiment tracking: recording the inputs, results, and files produced by each training run.
Why a run needs a record
A model metric without context is difficult to use. An accuracy of 0.91 does not tell you:
- Which data version was used.
- Which configuration produced the model.
- Which code revision ran.
- Whether the metric came from validation or test data.
- Where the trained model was stored.
An experiment-tracking record connects these facts. A run is one execution of the pipeline with a particular configuration and set of inputs.
A useful run record contains three kinds of information:
| Record type | Examples |
|---|---|
| Parameters | `seed=42`, `test_size=0.2`, `n_estimators=100` |
| Metrics | accuracy, loss, validation time |
| Artifacts | model file, confusion matrix, prediction file |
Parameters describe what you chose. Metrics describe what happened. Artifacts are files produced by the run.
Give every run an identity
The run identity should include enough information to distinguish one execution from another. A configuration fingerprint is useful because it gives the same configuration the same identifier.
Do not use only a timestamp as the identity. Two runs can have different configurations at the same time, and the same configuration may be run repeatedly. Store both a stable configuration fingerprint and a unique execution identifier.
Keep records append-only when possible. An append-only record is one that is added but not silently changed later. This makes the history easier to audit.
Record parameters, metrics, and artifacts
The following small tracker writes one JSON document per run to a local file. It also copies the artifact into a directory belonging to that run.
from __future__ import annotations
import hashlib
import json
import shutil
import uuid
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
@dataclass(frozen=True)
class TrainConfig:
seed: int = 42
test_size: float = 0.2
n_estimators: int = 100
def config_fingerprint(config: TrainConfig) -> str:
payload = json.dumps(asdict(config), sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()[:12]
class RunTracker:
def __init__(self, root: str = "runs") -> None:
self.root = Path(root)
self.root.mkdir(parents=True, exist_ok=True)
self.index_path = self.root / "runs.jsonl"
def start(self, config: TrainConfig, data_version: str, git_commit: str) -> dict:
run_id = uuid.uuid4().hex[:12]
record = {
"run_id": run_id,
"started_at": datetime.now(timezone.utc).isoformat(),
"config": asdict(config),
"config_fingerprint": config_fingerprint(config),
"data_version": data_version,
"git_commit": git_commit,
"metrics": {},
"artifacts": [],
}
(self.root / run_id).mkdir()
self._write(record)
return record
def finish(self, record: dict, metrics: dict, artifact: Path | None = None) -> None:
record["finished_at"] = datetime.now(timezone.utc).isoformat()
record["metrics"] = metrics
if artifact is not None:
destination = self.root / record["run_id"] / artifact.name
shutil.copy2(artifact, destination)
record["artifacts"].append({
"path": str(destination),
"bytes": destination.stat().st_size,
})
self._write(record)
def _write(self, record: dict) -> None:
with self.index_path.open("a", encoding="utf-8") as file:
file.write(json.dumps(record, sort_keys=True) + "\n")
if __name__ == "__main__":
config = TrainConfig()
tracker = RunTracker()
run = tracker.start(
config=config,
data_version="iris-2026-01",
git_commit="a1b2c3d",
)
model_file = Path("model.txt")
model_file.write_text("trained model placeholder\n", encoding="utf-8")
tracker.finish(
run,
metrics={"validation_accuracy": 0.93, "training_seconds": 1.8},
artifact=model_file,
)
print(f"recorded run {run['run_id']}")This example writes a starting record and then a completed record. A production tracker would usually update one database row or use a tracking service instead. The important boundary is the data being recorded, not the storage product.
Track inputs that affect results
Record every input that can change the output:
- Configuration values and their fingerprint.
- Data version, snapshot, or content hash.
- Source-code commit.
- Dependency or container version.
- Random seeds.
- Hardware details when they can affect numerical behavior.
Avoid recording secrets such as access tokens or database passwords. Record a safe reference to the secret's location or version instead.
Use stable metric names. For example, choose validation_accuracy rather than sometimes writing val_acc and sometimes writing accuracy. Consistent names make filtering and comparison reliable.
Keep artifacts discoverable
An artifact should have a path, a type, and ideally a checksum. A file named model.pkl is not enough if every run produces a file with that name. Store it under the run's directory or in object storage with the run identity in its key.
Log artifacts only after they are completely written. Otherwise, a failed upload or interrupted process may leave a record pointing to a partial file.
Compare runs without losing context
A tracking system helps answer questions such as:
- Which configuration gave the best validation score?
- Did the score improve because of a code change or a data change?
- Can the promoted model be reproduced?
- Which artifacts belong to the selected run?
Select models using the evaluation metric and policy defined by the pipeline. Do not choose a model merely because it is the newest run. The run record should provide the evidence needed by a later evaluation gate and promotion step.
Exercise
A run has an accuracy of 0.94, but its record contains only the metric and a timestamp. Name two pieces of information you would require before promoting its model.
Show answer
Require at least the data version and configuration. The code commit, environment version, and model artifact location are also important for reproduction.