Experiment tracking and configuration
A free local experiment system with declarative configuration and command-line overrides, run directories with full provenance, TensorBoard metrics and pandas analysis, including resumable local sweeps.
After this lesson you can
- Structure experiment configuration with dataclasses or Hydra and override it from the command line.
- Create a run directory with resolved configuration, provenance, environment, GPU, driver and logs.
- Log scalars, histograms, images and hyperparameters with SummaryWriter and compare TensorBoard runs.
- Launch sequential resumable local GPU sweeps and consolidate results in a DataFrame.
- Choose logging content and frequency without slowing training or filling disk.
Before you start
Motivation: the good run was Tuesday’s
On Thursday morning you must redo figure 3 of a report. On Tuesday afternoon a run reached validation loss 1.81; today, with “the same configuration”, it will not fall below 1.86. You start asking questions and none has an answer:
- What code? The commit you remember is
a3f9c21, but Tuesday you were changing the loss function and had not committed. - What learning rate? The legend says
3e-4, passed on the command line. Other values came from code, and Wednesday you changed the defaultweight_decay. - What seed? None fixed: the script called
torch.manual_seed(int(time.time())). - What data?
train.parquetwas regenerated yesterday with a different duplicate filter. - What environment? You updated PyTorch Monday, or was it Wednesday?
None of this is bad luck. It is what happens by default when an experiment’s result depends on a dozen inputs and only a curve is saved. Sculley and coauthors described it in Hidden Technical Debt in Machine Learning Systems (2015): in a mature machine-learning system, configuration lines can far exceed conventional code, each is an opportunity for error, and yet their verification is often secondary; hence they call for reviewing configuration changes as carefully as code. The NeurIPS 2019 reproducibility program (Pineau and coauthors, 2021) introduced a checklist requesting, among other things, hyperparameter ranges explored, number of runs, dispersion measure and compute infrastructure: data only someone who recorded it at execution can give.
This lesson builds a free local system to avoid losing results. It has four pieces, the four lesson concepts:
- Declarative, typed configuration, with one source of truth and command-line overrides validated before training.
- Provenance: each run has its own directory with resolved configuration, commit and git working-tree state, environment, GPU, seed and data fingerprint.
- Tracking: metrics, histograms, images and hyperparameters logged with TensorBoard (or custom JSONL files) at measured cost, without slowing training.
- Sequential, resumable sweeps on a single GPU, with results consolidated in a
DataFramefor comparison with between-seed bands.
It builds on prior lessons: dataclasses, dependency lockfile, training loop, seeding strategy and checkpoints. The next lesson, anatomy of a research project, puts it all in a repository with its git workflow.
The lineage of a result
Think of a report number as the value of a function:
Each argument you fail to record is a question about the result you can no longer answer. Worse than not recording is recording incorrectly. A commit saved when the working tree had uncommitted changes looks like an answer to “what code was it?”, but is false, and nothing reveals it.
Three lessons from the figure:
- Questions have dependencies. “With what hyperparameters?” can be answered with only the command line, but then depends on code: defaults live there. If code is unidentified, so is the answer.
- Rerunning needs more than understanding. To know what was done, code and configuration suffice; to repeat it, data and environment are also needed, and for identical bits, seed, same hardware and deterministic algorithms (lesson 20’s reproducibility levels).
- A dirty tree without diff poisons everything depending on code. It is the most frequent practical case and the only one where the record lies.
Configuration: one typed source of truth
Resolved configuration identifies a run, not the command line launching it: two runs with the same command line and different code defaults are different experiments.
Typed dataclasses
The simplest way to satisfy points 1 and 2 is a hierarchy of dataclasses: schema and defaults live in one place, understood by type checker and editor autocomplete.
from dataclasses import dataclass, field
@dataclass(frozen=True)
class ModelCfg:
name: str = "transformer"
d_model: int = 256
n_layers: int = 6
dropout: float = 0.1
@dataclass(frozen=True)
class OptimCfg:
lr: float = 1e-3
weight_decay: float = 0.1
betas: tuple[float, float] = (0.9, 0.95)
@dataclass(frozen=True)
class Config:
seed: int = 0
steps: int = 20_000
model: ModelCfg = field(default_factory=ModelCfg)
optim: OptimCfg = field(default_factory=OptimCfg)
frozen=True prevents training code changing configuration halfway: if the value saved at the start is not the one used, provenance lies. To “change” a frozen configuration, create another with dataclasses.replace. What a dataclass does not provide is command-line input. The usual shortcut, a dictionary updated with sys.argv strings, fails silently in two ways:
import json
from dataclasses import dataclass, field, asdict
@dataclass
class ModelCfg:
name: str = "mlp"
width: int = 512
depth: int = 4
dropout: float = 0.1
@dataclass
class OptimCfg:
name: str = "adamw"
lr: float = 1e-3
weight_decay: float = 0.1
@dataclass
class Config:
seed: int = 0
steps: int = 20_000
model: ModelCfg = field(default_factory=ModelCfg)
optim: OptimCfg = field(default_factory=OptimCfg)
# el atajo: un dict y asignaciones con las cadenas de la línea de comandos
cfg = asdict(Config())
for item in ["optim.lrr=3e-4", "model.depth=6"]:
key, value = item.split("=", 1)
*parents, leaf = key.split(".")
node = cfg
for p in parents:
node = node[p]
node[leaf] = value # nadie comprueba la clave ni el tipo
print(json.dumps(cfg["optim"]), json.dumps(cfg["model"]))
print("lr efectivo:", cfg["optim"]["lr"], " depth:", repr(cfg["model"]["depth"]))
try:
capas = [None] * cfg["model"]["depth"]
except TypeError as e:
print("al construir el modelo:", e)
# YAML 1.1 (PyYAML) tiene sus propias sorpresas
import yaml
print(yaml.safe_load("lr: 3e-4\nlr_con_punto: 3.0e-4\npais: NO\nversion: 1.10"))Typo lrr creates a new key nobody reads, and training silently uses the original lr. Depth remains string '6' and the error appears where used, perhaps halfway through hours of training, perhaps never (if only printed). You will write the correct version with type conversion and clear errors in the first code exercise.
YAML and its traps
Configurations often live in YAML because it is readable and supports comments. But the cell’s last line shows three real traps in YAML 1.1, the version PyYAML implements:
3e-4is a string, not a float: YAML 1.1 grammar requires a point in the mantissa and an exponent sign (3.0e-4is float;1e3and3.0e4remain strings). Passing that string totorch.optim.AdamW(params, lr=cfg["lr"])raisesTypeError: '<=' not supported between instances of 'float' and 'str', which is lucky: other code might accept it and fail later.NO,no,offandyesare booleans: Norway’s code becomesFalse.1.10is float 1.1: quote versions.
Typed configuration defuses all three: if schema says lr is float, string '3e-4' is converted or rejected on load, never reaching the optimizer.
OmegaConf and Hydra: composition and overrides
OmegaConf is the configuration library underlying Hydra, Meta Research’s configuration system. OmegaConf provides the typed tree (DictConfig), configuration merging, interpolations (${optim.lr}) and struct mode, where assigning a nonexistent key is an error. With a dataclass schema, each assignment is also validated against its declared type:
from omegaconf import OmegaConf
schema = OmegaConf.structured(Config) # el esquema: claves y tipos
cfg = OmegaConf.merge(schema, OmegaConf.load("exp.yaml"), # fichero del experimento
OmegaConf.from_dotlist(["optim.lr=3e-4", "model.n_layers=8"]))
OmegaConf.merge(schema, OmegaConf.from_dotlist(["optim.lrr=3e-4"])) # ConfigKeyError: la clave no existe
OmegaConf.merge(schema, OmegaConf.from_dotlist(["model.n_layers=seis"])) # ValidationError: no es un int
print(OmegaConf.to_yaml(cfg, resolve=True)) # la configuración resuelta, para guardarla
Hydra adds group composition and command line. A conf/ directory has a main file with a defaults list and a subdirectory per group, with one file per option:
# conf/config.yaml
defaults:
- model: mlp # conf/model/mlp.yaml
- data: cifar10 # conf/data/cifar10.yaml
- optim: adamw # conf/optim/adamw.yaml
- _self_ # los valores de este fichero se aplican después de los grupos
seed: 0
steps: 20000
sched:
warmup: 500
max_lr: ${optim.lr} # interpolación: sigue a optim.lr aunque se sobrescriba
import hydra
from omegaconf import DictConfig, OmegaConf
@hydra.main(version_base=None, config_path="conf", config_name="config")
def main(cfg: DictConfig) -> None:
print(OmegaConf.to_yaml(cfg))
train(cfg)
if __name__ == "__main__":
main()
Hydra’s override grammar has five forms, all shown in the next figure:
| Override | Effect |
|---|---|
model=transformer | choose another model group option (another file) |
optim.lr=3e-4 | change an existing value; error if absent |
+trainer.compile=true | add a nonexistent key; error if already present |
++trainer.compile=true | add or change without checking |
~data.augment | delete a key |
Precedence follows composition: first schema, then groups in list order, then the file itself (wherever _self_ appears), and finally command line. Interpolations resolve at the end, on the already composed tree.
The figure’s three validation levels correspond to real practices. Homemade dict.update detects nothing: everything is a string and any key works. OmegaConf struct mode detects key typos, but infers each command-line value’s type from its form (seis is a string, 8 an integer) and compares it with nothing. Typed configuration detects both and converts values to declared type: model.n_layers=8 arrives as int and optim.lr=1 as 1.0. The figure converts with strict rules, the ones you will program in the first exercise. OmegaConf’s schema is more permissive with booleans: it accepts yes, no, on, off and integers, so data.augment=no arrives as False (exactly what was intended, but by the same rule that converts Norway to False).
What early validation buys
The argument for validation before training is expected cost. A typo caught at launch costs one second. The same typo caught halfway through training costs hours lost until then, and a typo producing no error (a new key nobody reads) costs an entire experiment with a false conclusion: “raising lr changes nothing”. It is static typing’s logic applied to the object changing most in a research project.
The run directory
The second piece makes each run a self-describing object: a directory containing everything needed to know what was done and, as far as possible, repeat it.
A run directory looks like this:
runs/
20261021-140311-be2a95ec-7e2b/
config.yaml # configuración resuelta: todos los valores efectivos
meta.json # procedencia y estado
diff.patch # solo si el árbol estaba sucio
metrics.jsonl # una línea JSON por registro
tb/ # ficheros de eventos de TensorBoard
checkpoints/ # los de la lección 21
stdout.log
The identifier
The directory name is the run identifier, generated rather than written. A good recipe is fecha-hora, the first eight characters of the resolved configuration hash and a few random characters: date orders runs chronologically, hash groups those sharing configuration and random suffix prevents collisions between launches in the same second. Names like final_v2_bueno encode an opinion that expires, not information: metadata says what the run is, and labels and notes (editable in meta.json) say what you think of it.
How to obtain each piece
Almost everything comes from one command or attribute:
| Piece | How |
|---|---|
| commit | git rev-parse HEAD |
| dirty tree | git --no-optional-locks status --porcelain (empty output if clean) |
| diff | git diff HEAD > diff.patch (staged and unstaged changes) |
| untracked | git ls-files --others --exclude-standard |
| readable summary | git describe --always --dirty (for example, a3f9c21-dirty) |
| environment | sha256 of uv.lock; importlib.metadata.version("torch") |
| CUDA and cuDNN | torch.version.cuda, torch.backends.cudnn.version() |
| GPU and driver | torch.cuda.get_device_name(); nvidia-smi --query-gpu=name,driver_version --format=csv,noheader |
| data | file sha256 in blocks; for large datasets, a manifest with paths, sizes and hashes |
The procedure must be robust: if git is absent (a container, Pyodide) or there is no GPU, record None and continue. A provenance function that crashes training because nvidia-smi is not on PATH will not last a week in code. You will write it this way in the second code exercise.
The dirty tree
A dirty tree deserves explicit policy because it is the only case where the record can lie. Three reasonable choices:
- Refuse to launch with uncommitted changes unless explicitly opted in (
--allow-dirty). Safest for results going into a report. - Save the diff (
git diff HEAD) and untracked-file list. With commit and diff,git apply diff.patchreconstructs the exact code. Convenient for rapid iteration. - Automatically commit on an experiment branch before launching. Works but fills history with commits without useful messages.
Watch new files: git diff HEAD excludes files git does not track. If the important change is in nueva_perdida.py without git add, the diff misses it. Therefore also record the untracked-file list (and, if few and small, a copy).
A logger from scratch
The system core fits in a class. Each Run creates its directory, writes configuration and provenance atomically (lesson 21’s atomic write technique: temporary file and os.replace), opens a metrics JSONL and, on leaving the with block, marks the run done or failed with error. The provenance function here is minimal; the complete one is the second exercise.
import os, sys, time, uuid, hashlib, platform, subprocess, tempfile
from dataclasses import is_dataclass
from pathlib import Path
def config_hash(cfg) -> str:
"""sha256 de la configuración resuelta en forma canónica (claves ordenadas, sin espacios)."""
d = asdict(cfg) if is_dataclass(cfg) else cfg
blob = json.dumps(d, sort_keys=True, separators=(",", ":"))
return hashlib.sha256(blob.encode()).hexdigest()
def atomic_write_json(path: Path, obj) -> None:
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(obj, indent=1, sort_keys=True))
os.replace(tmp, path) # atómico: o el fichero viejo o el nuevo, nunca uno a medias
def git_state():
try:
sha = subprocess.run(["git", "rev-parse", "HEAD"], capture_output=True, text=True, check=True, timeout=5).stdout.strip()
st = subprocess.run(["git", "--no-optional-locks", "status", "--porcelain"], capture_output=True, text=True, check=True, timeout=5)
return {"commit": sha, "dirty": st.stdout.strip() != ""}
except Exception: # sin git, fuera de un repositorio o sin procesos (Pyodide)
return {"commit": None, "dirty": None}
class Run:
"""Una ejecución = un directorio con config.json, meta.json y metrics.jsonl."""
def __init__(self, root, cfg, seed):
self.cfg, h = cfg, config_hash(cfg)
self.id = f"{time.strftime('%Y%m%d-%H%M%S')}-{h[:8]}-{uuid.uuid4().hex[:4]}"
self.dir = Path(root) / self.id
self.dir.mkdir(parents=True)
atomic_write_json(self.dir / "config.json", asdict(cfg) if is_dataclass(cfg) else cfg)
self.meta = {"id": self.id, "config_hash": h, "seed": seed, "status": "running", "start": time.time(),
"python": platform.python_version(), "argv": sys.argv[1:], **git_state()}
atomic_write_json(self.dir / "meta.json", self.meta)
self._f = open(self.dir / "metrics.jsonl", "a", buffering=1) # búfer de línea: cada registro pasa al sistema operativo
def log(self, step: int, **metrics: float) -> None:
self._f.write(json.dumps({"step": step, **metrics}) + "\n")
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
self._f.close()
self.meta.update(status="done" if exc is None else "failed", end=time.time(),
error=None if exc is None else f"{exc_type.__name__}: {exc}")
atomic_write_json(self.dir / "meta.json", self.meta)
return False # la excepción sigue su camino
root = Path(tempfile.mkdtemp(prefix="runs-"))
with Run(root, Config(), seed=0) as run:
for step in range(0, 50, 10):
run.log(step, **{"train/loss": 1 / (1 + step)})
print(run.id)
for f in sorted(run.dir.iterdir()):
print(f" {f.name:14s} {f.stat().st_size:5d} B")
print((run.dir / "meta.json").read_text())In the browser there is no git or processes, so commit and dirty are None and logging continues: precisely the robust behavior desired. Three design decisions deserve attention. Fingerprint is sha256 of canonical configuration form (sorted keys, fixed separators): equal configurations written in another order yield the same hash. JSONL opens line-buffered: each line reaches the OS on write, so if the process dies none already logged is lost (power failure would also require os.fsync), and each complete line is valid JSON by itself: if the last is partial, discard it. And __exit__ returns False: the logger records failure but does not swallow it.
TensorBoard
A JSONL file per run suffices for pandas analysis, but looking at curves during training, comparing dozens of runs and seeing a distribution evolve require an interface. TensorBoard is PyTorch’s default free local option.
Scalars, histograms, images and hyperparameters
torch.utils.tensorboard.SummaryWriter writes event files (events.out.tfevents.*) in a directory. Each directory containing event files is a TensorBoard run, and tensorboard --logdir runs shows all under runs/. Four important calls:
add_scalar(tag, value, step): a time series. Slash-separated tags (train/loss,val/loss,opt/lr) group into UI sections.add_histogram(tag, values, step): a tensor’s distribution at that step (weights, gradients, activations). TensorBoard displays stacked histograms over time and percentile bands.add_image(tag, img, step): an image, by default shapeC×H×Wand values in (oruint8).add_hparams(hparam_dict, metric_dict): run hyperparameters and final metrics, for the HPARAMS tab’s table and parallel-coordinates view.
Step (global_step) must mean the same in every compared run: optimizer steps, not batches or epochs, because gradient accumulation or another batch size would misalign curves. To compare by data volume seen, record a second series with processed examples.
Three PyTorch implementation details worth knowing (all in torch.utils.tensorboard source):
add_scalarwith a CUDA tensor synchronizes. It converts the value with.cpu()before writing, sowriter.add_scalar("loss", loss, step)every step synchronizes every step. We return to this next section.add_histogramcomputes on CPU. It copies the tensor to CPU and callsnp.histogram. Millions of parameters cost tens or hundreds of milliseconds.add_hparamsdefaults to creating another directory inside the run (named with timestamp), which TensorBoard displays as a separate run.run_name="."writes in the same one.
Organizing tags and comparing runs
To compare runs, place them all under a common directory and point TensorBoard there: each subdirectory is a run, the sidebar filter accepts regular expressions on names, and in a sweep the generated name (or a tag in meta.json) lets you select, for example, all seeds of lr=3e-4. The scalars tab overlays selected runs’ curves with adjustable exponential smoothing, and the hyperparameters tab tabulates add_hparams values.
Reading logs from Python
The next cell, running on your machine, trains a small MLP four times on GPU (two learning rates, two seeds) and logs what we just saw. Notice how loss is logged: accumulate it in a GPU tensor and read with one .item() every 25 steps. Then read events with EventAccumulator, the same component used by the UI.
import os, time, tempfile
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from tensorboard.backend.event_processing.event_accumulator import EventAccumulator
dev = "cuda" if torch.cuda.is_available() else "cpu"
tb_root = Path(tempfile.mkdtemp(prefix="tb-"))
gen = torch.Generator().manual_seed(123) # datos fijos: no dependen de la semilla del experimento
X = torch.randn(8192, 32, generator=gen)
y = torch.sin(X[:, :4].sum(1)) + 0.1 * torch.randn(8192, generator=gen)
X, y = X.to(dev), y.to(dev)
Xtr, ytr, Xva, yva = X[:7168], y[:7168], X[7168:], y[7168:]
def train_tb(lr, seed, steps=1500, log_every=25, hist_every=250):
torch.manual_seed(seed)
g = torch.Generator(device=dev).manual_seed(seed)
model = nn.Sequential(nn.Linear(32, 128), nn.ReLU(), nn.Linear(128, 1)).to(dev)
opt = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
w = SummaryWriter(tb_root / f"lr{lr:g}-s{seed}")
acc = torch.zeros((), device=dev) # suma de pérdidas en la GPU: sin sincronizar
for step in range(1, steps + 1):
idx = torch.randint(0, len(Xtr), (256,), device=dev, generator=g)
loss = F.mse_loss(model(Xtr[idx]).squeeze(-1), ytr[idx])
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
acc += loss.detach()
if step % log_every == 0:
w.add_scalar("train/loss", (acc / log_every).item(), step) # una sincronización cada 25 pasos
acc.zero_()
if step % hist_every == 0:
for name, p in model.named_parameters():
w.add_histogram(f"weights/{name}", p, step)
with torch.no_grad():
w.add_scalar("val/loss", F.mse_loss(model(Xva).squeeze(-1), yva).item(), step)
W1 = model[0].weight.detach()
w.add_image("weights/layer0", ((W1 - W1.min()) / (W1.max() - W1.min()))[None], steps) # 1×128×32, CHW
with torch.no_grad():
val = F.mse_loss(model(Xva).squeeze(-1), yva).item()
w.add_hparams({"lr": lr, "seed": seed}, {"hparam/val_loss": val}, run_name=".")
w.close()
return val
t0 = time.perf_counter()
for lr in (0.01, 0.05):
for seed in (0, 1):
print(f"lr={lr:<5g} seed={seed} val/loss = {train_tb(lr, seed):.4f}")
print(f"4 ejecuciones en {time.perf_counter() - t0:.1f} s en {dev}")
run0 = tb_root / "lr0.01-s0"
ea = EventAccumulator(str(run0), size_guidance={"scalars": 0, "histograms": 0, "images": 0})
ea.Reload()
for kind, tags in ea.Tags().items():
if tags and kind in ("scalars", "histograms", "images"):
print(f"{kind:10s}", tags)
pts = ea.Scalars("train/loss")
print(f"train/loss: {len(pts)} puntos, del paso {pts[0].step} ({pts[0].value:.3f}) al {pts[-1].step} ({pts[-1].value:.3f})")
for p in sorted(run0.iterdir()):
print(f" {p.name[:44]:46s} {p.stat().st_size:8d} B")
print("para verlo: tensorboard --logdir", tb_root)npm run lab and open the connection link.size_guidance={"scalars": 0, ...} tells the accumulator to keep everything instead of sampling. The run directory contains two event files: training’s and add_hparams’s, which with run_name="." remains in the same run. To analyze dozens of runs, rather than reading events, it is more convenient for each run also to write JSONL, as the previous section’s logger: TensorBoard for viewing, JSONL for analysis.
Logging frequency and cost
Logging is not free, and cost is not where it appears. Writing 49 bytes to a file is cheap; what costs is obtaining the number to write. As in lesson 16, asynchronous CUDA execution lets CPU queue kernels several steps ahead of GPU. Reading a value computed by GPU (.item(), .tolist(), .cpu(), or add_scalar with a tensor) forces CPU to wait for the queue to drain. That itself costs nothing because GPU keeps working. What costs is what follows: while CPU logs and prepares the next step, GPU has nothing queued and is idle. This bubble is paid at every synchronization.
Unit costs, measured on an RTX 4060 Laptop with Windows, PyTorch 2.11 and tensorboard 2.21 without TensorFlow installed:
| Operation | Cost | Disk size |
|---|---|---|
.item() with GPU already idle | 13 µs | |
add_scalar, main thread | about 40 µs | 49 B per event |
add_scalar, writer thread | about 0.3 ms per event | |
| JSONL line with 8 metrics | about 15 µs | 274 B |
add_histogram | about 25 ns per element | about 10 kB per histogram |
add_image, 256×128 PNG | 35 ms | 99 kB (noise: upper bound) |
The interactive simulates 100 000 training steps with these unit costs. Model sizes and per-step CPU and GPU times are illustrative assumptions; logging costs are measured.
With the medium model (30 ms GPU per step), initial state costs 27% more than no logging, almost all due to histograms: each scans 25 million CPU parameters, about 0.65 s with GPU idle, and every 100 steps gives a thousand snapshots (one hundred thousand histograms, one per tensor) and almost 1 GB disk. Every 1000 steps, histogram overhead falls to 2.3% and disk to 100 MB, and the resulting 100 snapshots suffice to see distribution evolution. Eight scalars per step with .item() add 3.9%; accumulated on GPU and read every 10 steps, 0.4%.
The general calculation is simple. If a step takes and a read every steps creates a bubble of duration , relative overhead is approximately
and the same for each logging type with its own and . For a histogram, is proportional to parameter count; for scalars, it is CPU work between synchronization and the next step’s first kernel. That is why overhead depends so much on model, in opposite directions: the same 8 scalars with .item() slowing the small model 13% (8 ms per step) slow the large one 1.3% (110 ms), because its does not grow with model; histograms every 100 steps, by contrast, slow the small one 18% and large one 24%, because is proportional to parameters and, with assumed step times, grows somewhat more slowly.
Rules
- Scalars: accumulate on GPU (
acc += loss.detach()) and read every 10 to 100 steps with one.tolist()of atorch.stackof all metrics. Besides being cheap, window average estimates better than a single batch value. Do not call.item()per metric. - Histograms: about 100 snapshots per training run (every 1000 steps in a 100 000-step run), and only layers of interest.
- Images and samples: dozens per run, not thousands; generating them usually costs a GPU step and PNG tens of milliseconds.
- Bursts: if logging many events at once, raise
max_queue(for example to 1000) so the main thread does not wait for the writer. - Measure: with lesson 17’s profiler (measurement methodology), compare step time with and without logging. If the difference exceeds a couple of percentage points, one of the above is failing.
Local sweeps
A sweep answers questions like “what learning rate?” or “does regularization improve things at every batch size?”. On a machine with a single 8 GB GPU it must be sequential, therefore long and therefore interruptible.
Cost of a sweep
Grid size is the product of axis sizes multiplied by number of seeds: 4 learning rates, 3 batch sizes and 5 seeds make runs. If each takes , the sweep takes on one GPU. This multiplication motivates two practices:
- Do not grid-search what is unnecessary. In multiple dimensions, random search with the same budget explores better than a grid, because it does not repeat values of unimportant dimensions; methods like Hyperband or Bayesian optimization allocate budget based on results. All use the same launcher: only generation of the next configuration changes.
- Sweep briefly with few seeds first, repeating only candidates with more seeds. Seeds measure uncertainty of final comparisons (quantified in the next section), not exploration.
Running two processes simultaneously on one GPU helps only if each leaves much of it idle (tiny models, CPU- or data-bound training) and their combined memory fits; usually they share the GPU and each takes almost twice as long. Measure before doing it.
A sweep that also records failures
The next cell launches 25 runs of a toy problem (linear regression by stochastic gradient descent, fixed data and seed controlling initialization and batch order) with the earlier Run logger. Highest learning rate diverges.
import numpy as np
@dataclass
class ToyCfg:
lr: float = 0.03
batch: int = 32
steps: int = 300
seed: int = 0
# datos fijos (su identidad no depende de la semilla del experimento)
rd = np.random.default_rng(1234)
d = 20
w_true = rd.normal(size=d)
X_tr, X_va = rd.normal(size=(2000, d)), rd.normal(size=(500, d))
y_tr = X_tr @ w_true + 0.5 * rd.normal(size=2000)
y_va = X_va @ w_true + 0.5 * rd.normal(size=500)
def train(cfg: ToyCfg, run: Run):
rng = np.random.default_rng(cfg.seed) # inicialización y orden de los lotes
w = 0.1 * rng.normal(size=d)
for step in range(1, cfg.steps + 1):
idx = rng.integers(0, len(X_tr), cfg.batch)
r = X_tr[idx] @ w - y_tr[idx]
loss = float(r @ r) / cfg.batch
if not np.isfinite(loss) or loss > 1e6:
raise FloatingPointError(f"la pérdida diverge en el paso {step}")
w -= cfg.lr * (2 / cfg.batch) * (X_tr[idx].T @ r)
if step % 20 == 0:
rv = X_va @ w - y_va
run.log(step, **{"train/loss": loss, "val/loss": float(rv @ rv) / len(y_va)})
sweep_root = Path(tempfile.mkdtemp(prefix="sweep-"))
t0 = time.perf_counter()
for lr in [0.003, 0.01, 0.03, 0.1, 1.5]:
for seed in range(5):
cfg = ToyCfg(lr=lr, seed=seed)
try:
with Run(sweep_root, cfg, seed=seed) as run:
train(cfg, run)
except FloatingPointError:
pass # queda registrada como failed: no se borra
print(f"25 ejecuciones en {time.perf_counter() - t0:.2f} s, {len(list(sweep_root.iterdir()))} directorios")The five lr=1.5 runs remain on disk with status: failed and error message. They are not deleted: they show the method diverges above a certain learning rate, information about the method (and a reviewer’s first question). A sweep with failures deleted overstates robustness of what remains.
A sequential, resumable launcher
To survive interruption, the launcher needs three things: a deterministic directory per configuration (its fingerprint, not time), an atomically written status file at start and finish, and the rule to skip completed runs. The cell simulates power loss halfway through the sweep with an exception not inheriting Exception, so nothing catches or records it, as in real failure, then relaunches.
import itertools
class Apagon(BaseException):
"""Simula un corte: no es una Exception, y nada lo captura ni lo registra."""
def sweep_grid(grid: dict, seeds) -> list:
keys = list(grid)
return [{**dict(zip(keys, vals)), "seed": s} for vals in itertools.product(*grid.values()) for s in seeds]
def launch(configs, root, train_fn, retry_failed=False):
root = Path(root)
root.mkdir(exist_ok=True)
hechas = 0
for cfg in configs:
key = config_hash(cfg)[:12] # misma configuración, mismo directorio: idempotente
d_ = root / key
st = d_ / "status.json"
estado = json.loads(st.read_text())["status"] if st.exists() else None
if estado == "done" or (estado == "failed" and not retry_failed):
continue # «running» significa interrumpida: se repite
d_.mkdir(exist_ok=True)
atomic_write_json(d_ / "config.json", cfg)
atomic_write_json(st, {"status": "running", "start": time.time()})
try:
result = train_fn(cfg)
except Exception as e:
atomic_write_json(st, {"status": "failed", "error": repr(e)})
continue
atomic_write_json(d_ / "result.json", result)
atomic_write_json(st, {"status": "done", "end": time.time()})
hechas += 1
return hechas
def recuento(root):
estados = [json.loads(p.read_text())["status"] for p in Path(root).glob("*/status.json")]
return {s: estados.count(s) for s in sorted(set(estados))}
configs = sweep_grid({"lr": [0.01, 0.03, 0.1], "batch": [16, 64]}, seeds=range(3))
print(len(configs), "ejecuciones en el barrido")
contador = {"n": 0}
def entrenar_toy(cfg, cortar_en=None):
contador["n"] += 1
if cortar_en is not None and contador["n"] == cortar_en:
raise Apagon()
rng = np.random.default_rng(cfg["seed"])
w = np.zeros(d)
for _ in range(200):
idx = rng.integers(0, len(X_tr), cfg["batch"])
r = X_tr[idx] @ w - y_tr[idx]
w -= cfg["lr"] * (2 / cfg["batch"]) * (X_tr[idx].T @ r)
rv = X_va @ w - y_va
return {"val_loss": float(rv @ rv) / len(y_va)}
root5 = Path(tempfile.mkdtemp(prefix="barrido-"))
try:
launch(configs, root5, lambda c: entrenar_toy(c, cortar_en=8))
except Apagon:
print("¡apagón! estado en disco:", recuento(root5))
print("relanzar ejecuta", launch(configs, root5, entrenar_toy), "ejecuciones; estado:", recuento(root5))
print("relanzar otra vez ejecuta", launch(configs, root5, entrenar_toy))After interruption 7 runs are complete and one running; relaunch executes the remaining 11 (the interrupted one from scratch), and another relaunch runs nothing. Restarting an interrupted run is acceptable if each lasts minutes. If hours, the launcher should pass the directory to train_fn, and train_fn should resume from its latest checkpoint using lesson 21’s exact resumption, making the resumed curve identical to the uninterrupted one.
Hydra has its own sweep: python train.py -m optim.lr=1e-4,3e-4,1e-3 seed=0,1,2 launches 9 combinations with the basic launcher, one at a time, each in its multirun/ subdirectory with composed configuration, overrides and Hydra configuration in .hydra/. The basic launcher does not skip completed combinations on relaunch: add idempotence inside main by checking a status file as in the cell.
From logging to analysis
With all runs in uniformly structured directories, analysis is a pandas problem: two tables and a groupby.
- One row per run: identifier, status and flattened configuration (
optim.lr,model.depth…), usingpd.json_normalize. - Metrics in long format: one row per (run, step), one column per metric.
Joining by identifier and grouping by configuration keys except seed is lesson 9’s split-apply-combine pattern: each group is replicas of one configuration, and aggregation gives mean and between-seed spread.
import pandas as pd
def load_runs(root):
"""Dos tablas: una fila por ejecución (configuración aplanada y metadatos) y las métricas en formato largo."""
runs, metrics = [], []
for d_ in sorted(Path(root).iterdir()):
meta = json.loads((d_ / "meta.json").read_text())
cfg = json.loads((d_ / "config.json").read_text())
runs.append({"run": meta["id"], "status": meta["status"], "error": meta.get("error"),
**pd.json_normalize(cfg, sep=".").to_dict("records")[0]})
f = d_ / "metrics.jsonl"
if f.stat().st_size:
metrics.append(pd.read_json(f, lines=True).assign(run=meta["id"]))
return pd.DataFrame(runs), pd.concat(metrics, ignore_index=True)
runs, metrics = load_runs(sweep_root)
print(runs.groupby("lr")["status"].value_counts().unstack(fill_value=0))
print(runs.loc[runs.status == "failed", ["lr", "seed", "error"]].head(2).to_string(index=False))
long = metrics.merge(runs[["run", "lr", "seed", "status"]], on="run")
ok = long[long.status == "done"]
final = ok[ok.step == ok.step.max()]
tabla = final.groupby("lr")["val/loss"].agg(["mean", "std", "count"])
tabla["sem"] = tabla["std"] / np.sqrt(tabla["count"])
print(tabla.round(4))With metrics in long format, mean curves and bands are another groupby, now by configuration and step:
import matplotlib.pyplot as plt
curvas = ok.groupby(["lr", "step"])["val/loss"].agg(["mean", "std"]).reset_index()
fig, ax = plt.subplots(figsize=(6.4, 3.6))
for lr, g in curvas.groupby("lr"):
ax.plot(g.step, g["mean"], label=f"lr = {lr:g}")
ax.fill_between(g.step, g["mean"] - g["std"], g["mean"] + g["std"], alpha=0.2)
ax.set_yscale("log"); ax.set_xlabel("paso"); ax.set_ylabel("pérdida de validación")
ax.set_title("media ± desviación típica entre 5 semillas"); ax.legend(); plt.show()The status table shows failures where they belong, alongside successes. Curves have one between-seed standard-deviation band, describing how much one run varies. To communicate uncertainty of the mean, the appropriate band is standard error, (the sem column), or a confidence interval: with , Student’s -based 95% interval is mean . Which to draw is an uncertainty visualization decision, and the caption must say which.
How many seeds are needed
With lr=0.01 and lr=0.03, final means differ by 0.0042, with between-seed standard deviations of 0.0025 and 0.0070. Is the difference real, or could another five seeds reverse it? The simplest model of between-seed variability answers how much to trust a comparison.
Proof
The means are and , independent, so . Error is , and .
∎What matters is , real difference in units of between-seed noise:
| 1 seed | 3 seeds | 5 seeds | 10 seeds | 20 seeds | |
|---|---|---|---|---|---|
| 0.5 | 36% | 27% | 21% | 13% | 5.7% |
| 1 | 24% | 11% | 5.7% | 1.3% | 0.08% |
| 2 | 7.9% | 0.7% | 0.08% | less than 0.01% | less than 0.01% |
With one seed, an improvement the size of noise appears reversed one time in four. The model is optimistic in two ways: it assumes the same for both configurations and, especially, compares only two. Choosing the best of twenty sweep configurations means the winner tends to win partly through luck, and its advantage in a new sweep will be smaller; confirm with new seeds. This is lesson 20’s multi-seed evaluation and the design of ablation studies in the research module.
Free alternatives
TensorBoard is not the only free local option, nor always the best. Reasonable single-machine alternatives:
| Option | What it stores | Interface | Pros | Cons |
|---|---|---|---|---|
| Custom JSONL and Parquet | whatever you decide | none (pandas, matplotlib) | open format, trivial to read in ten years, arbitrary queries | no live UI, you program everything |
| TensorBoard | scalars, histograms, images, text, hyperparameters | good for curves and histograms | integrated into PyTorch, no data server | limited cross-run analysis; opaque event format |
| Local MLflow | parameters, per-step metrics, artifacts, models | good for run comparison and parameter search | parameter and metric queries, model registry | large dependency; another data model to learn |
In MLflow, log the same run with mlflow.start_run(), mlflow.log_params(cfg), mlflow.log_metric("val/loss", v, step=s) and mlflow.log_artifact(ruta), with storage in a local file (for example mlflow.set_tracking_uri("sqlite:///mlflow.db")), and mlflow ui starts the local interface.
Three selection questions:
- What queries will you make? “Curve of this run”: any option. “Best final loss of all runs with
dropout > 0.1grouped by model”: pandas over JSONL or MLflow. - How many runs? For dozens, reading hundreds of JSONL files suffices. For thousands, consolidate into one Parquet per sweep (
df.to_parquet), columnar and compressed, which pandas reads in a fraction of the time. - How long must it last? A published result’s record must be readable years later without the tool that wrote it. JSON and Parquet guarantee this; others less so.
The course combination: JSONL and provenance files as source of truth, TensorBoard as viewer during training, and pandas for analysis.
Course experiment infrastructure
The final cell combines the pieces into a compact version of project infrastructure: typed frozen configuration, automatic provenance (with lock-free git, CUDA, cuDNN, GPU and driver), JSONL and TensorBoard metrics with one synchronization per log, a resumable launcher and analysis with between-seed bands. It runs on your machine on GPU.
import hashlib, json, platform, subprocess
from dataclasses import dataclass, field, asdict, replace
import pandas as pd
import matplotlib.pyplot as plt
def _run(cmd):
return subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=10).stdout
def provenance():
p = {"python": platform.python_version(), "torch": torch.__version__,
"cuda": torch.version.cuda, "cudnn": torch.backends.cudnn.version(),
"gpu": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None}
try:
p["commit"] = _run(["git", "rev-parse", "HEAD"]).strip()
status = _run(["git", "--no-optional-locks", "status", "--porcelain"])
p["dirty"] = any(line and not line.startswith("??") for line in status.splitlines())
p["untracked"] = sum(line.startswith("??") for line in status.splitlines())
top = Path(_run(["git", "rev-parse", "--show-toplevel"]).strip())
lock = top / "uv.lock"
p["uv_lock_sha256"] = hashlib.sha256(lock.read_bytes()).hexdigest()[:16] if lock.exists() else None
except (OSError, subprocess.SubprocessError):
p.update(commit=None, dirty=None)
try:
p["driver"] = _run(["nvidia-smi", "--query-gpu=driver_version", "--format=csv,noheader"]).splitlines()[0].strip()
except (OSError, subprocess.SubprocessError, IndexError):
p["driver"] = None
return p
prov = provenance()
for k, v in prov.items():
print(f" {k:15s} {v}")
@dataclass(frozen=True)
class OptimCfg:
lr: float = 0.01
momentum: float = 0.9
@dataclass(frozen=True)
class TrainCfg:
seed: int = 0
steps: int = 1200
batch: int = 256
width: int = 128
optim: OptimCfg = field(default_factory=OptimCfg)
def cfg_hash(cfg):
return hashlib.sha256(json.dumps(asdict(cfg), sort_keys=True).encode()).hexdigest()
def write_json(path, obj):
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(obj, indent=1, sort_keys=True, default=str))
os.replace(tmp, path)
def train_run(cfg, run_dir):
torch.manual_seed(cfg.seed)
g = torch.Generator(device=dev).manual_seed(cfg.seed)
model = nn.Sequential(nn.Linear(32, cfg.width), nn.ReLU(), nn.Linear(cfg.width, 1)).to(dev)
opt = torch.optim.SGD(model.parameters(), lr=cfg.optim.lr, momentum=cfg.optim.momentum)
tb = SummaryWriter(run_dir / "tb")
acc = torch.zeros((), device=dev)
with open(run_dir / "metrics.jsonl", "w", buffering=1) as f:
for step in range(1, cfg.steps + 1):
idx = torch.randint(0, len(Xtr), (cfg.batch,), device=dev, generator=g)
loss = F.mse_loss(model(Xtr[idx]).squeeze(-1), ytr[idx])
opt.zero_grad(set_to_none=True)
loss.backward()
opt.step()
acc += loss.detach()
if step % 50 == 0:
with torch.no_grad():
v = F.mse_loss(model(Xva).squeeze(-1), yva)
tr, va = torch.stack([acc / 50, v]).tolist() # una sola sincronización
acc.zero_()
f.write(json.dumps({"step": step, "train/loss": tr, "val/loss": va}) + "\n")
tb.add_scalar("train/loss", tr, step)
tb.add_scalar("val/loss", va, step)
tb.close()
return {"val/loss": va}
def launch_runs(cfgs, root):
root.mkdir(parents=True, exist_ok=True)
n = 0
for cfg in cfgs:
d = root / cfg_hash(cfg)[:12]
st = d / "status.json"
if st.exists() and json.loads(st.read_text())["status"] == "done":
continue
d.mkdir(exist_ok=True)
write_json(d / "config.json", asdict(cfg))
write_json(d / "meta.json", {**prov, "start": time.time()})
write_json(st, {"status": "running"})
try:
write_json(d / "result.json", train_run(cfg, d))
write_json(st, {"status": "done"})
n += 1
except Exception as e:
write_json(st, {"status": "failed", "error": repr(e)})
return n
base = TrainCfg()
cfgs = [replace(base, seed=s, optim=replace(base.optim, lr=lr)) for lr in (0.003, 0.01, 0.05) for s in range(3)]
sweep_dir = Path(tempfile.mkdtemp(prefix="sweep-"))
t0 = time.perf_counter()
n = launch_runs(cfgs, sweep_dir)
print(f"ejecutadas: {n} en {time.perf_counter() - t0:.1f} s; relanzar ejecuta: {launch_runs(cfgs, sweep_dir)}")
rows = []
for d in sweep_dir.iterdir():
cfg = pd.json_normalize(json.loads((d / "config.json").read_text())).to_dict("records")[0]
rows.append(pd.read_json(d / "metrics.jsonl", lines=True).assign(**cfg, run=d.name))
df = pd.concat(rows, ignore_index=True)
summary = df[df.step == df.step.max()].groupby("optim.lr")["val/loss"].agg(["mean", "std", "count"])
print(summary.round(4))
band = df.groupby(["optim.lr", "step"])["val/loss"].agg(["mean", "std"]).reset_index()
fig, ax = plt.subplots(figsize=(6.4, 3.4))
for lr, g in band.groupby("optim.lr"):
ax.plot(g.step, g["mean"], label=f"lr = {lr:g}")
ax.fill_between(g.step, g["mean"] - g["std"], g["mean"] + g["std"], alpha=0.2)
ax.set_xlabel("paso"); ax.set_ylabel("pérdida de validación"); ax.legend(); plt.show()npm run lab and open the connection link.Output begins with your machine’s real provenance: commit of the repository from which it runs, whether the tree has tracked-file changes, how many untracked files (which git diff would miss), and CUDA, cuDNN and driver versions. The 9-run sweep takes about twenty seconds on the reference RTX 4060, and relaunching executes nothing. Two things already covered are missing to turn it into your project tool: reading configuration from command line (first exercise) and checkpoints for resuming long runs (lesson 21).
Common mistakes
Exercises
parse_overrides(cfg, overrides), receiving a dataclass (possibly frozen and containing nested dataclasses) and a list of strings 'a.b.c=valor', returning a copy with overrides applied in order without modifying the original. Convert each value to the field’s declared type: int and float by Python rules ('6.5' is not an int; '3e-4' is a float), bool only from case-insensitive true or false, and str unchanged. Raise ValueError with a message containing the full key if the key does not exist, value cannot be converted, key names a section (nested dataclass) rather than a value, or = is missing.import dataclasses
import typing
def parse_overrides(cfg, overrides):
"""Devuelve una copia de cfg con las sobrescrituras 'a.b.c=valor' aplicadas en orden."""
for item in overrides:
clave, _, raw = item.partition("=")
# tu código: recorre la ruta, comprueba que la clave existe y convierte raw al tipo del campo
pass
return cfgcollect_provenance(run=None, packages=('numpy', 'torch')), returning a dictionary with keys commit (output of git rev-parse HEAD stripped), dirty (True if git --no-optional-locks status --porcelain produces any line), python (platform.python_version()), packages (dictionary name → version from importlib.metadata, or None if not installed), gpu and driver (from first line of nvidia-smi --query-gpu=name,driver_version --format=csv,noheader, format nombre, versión). run(cmd) receives the command as a list and returns standard output, or raises an exception (FileNotFoundError if program is absent, subprocess.CalledProcessError if it fails); by default use subprocess.run. The function must never raise: what cannot be obtained is None (without git, commit and dirty are None; without GPU, gpu and driver).import platform
import subprocess
import importlib.metadata as md
def _default_run(cmd):
return subprocess.run(cmd, capture_output=True, text=True, check=True, timeout=10).stdout
def collect_provenance(run=None, packages=("numpy", "torch")):
run = run or _default_run
commit = run(["git", "rev-parse", "HEAD"]).strip() # falla sin git
return {"commit": commit, "python": platform.python_version()}meta.json contains: commit: a3f9c21, dirty: true, argv: ['train.py', 'optim.lr=3e-4'], seed: 0, python: 3.13.1, packages: {torch: 2.11.0, numpy: 2.3.4}, gpu: RTX 4060 Laptop, driver: 596.49, data: {path: data/train.parquet}. No other files exist in the directory except metrics. Which pieces are missing to rerun it and obtain an equivalent result? Select all.More than one answer may be correct.
add_histogram over all weights takes about 0.65 s (CPU copy and np.histogram), with GPU idle, and occupies about 1 MB per snapshot (100 tensors). What frequency do you choose for weight histograms?config.yaml contains lr: 3e-4 and is loaded with yaml.safe_load (PyYAML). Then the optimizer is created with torch.optim.AdamW(model.parameters(), lr=cfg['lr']). What happens?More than one answer may be correct.
Summary
- Configuration has one typed source of truth (dataclasses, OmegaConf, Hydra), composes by groups, accepts overrides validated for keys and types before training, and is saved resolved. PyYAML reads
3e-4as a string andNOasFalse. - Each run lives in a generated-name directory (date, fingerprint, random suffix) storing resolved configuration, commit, tree state and diff, environment (
uv.lock), GPU and driver, seed, data fingerprint and final status, even if failed. SummaryWriterlogs scalars, histograms, images and hyperparameters; each event directory is one TensorBoard run.add_scalarwith a CUDA tensor synchronizes,add_histogramcomputes on CPU and UI samples 1000 points per series.- Logging cost is in synchronizations and CPU work with GPU idle: accumulate scalars on GPU and read every 10 to 100 steps; histograms and images about 100 times per training run.
- A local sweep is a list of configurations and seeds run one at a time by an idempotent launcher: fingerprint directory, atomically written status, skip completed, retain failures.
- Analysis uses pandas: one run table and one metrics table,
groupbyconfiguration without seed and between-seed bands with declared meaning. With one seed, a difference the size of noise appears reversed one in four times.