Experiment Logging & Reproducibility
What to log for every training run, how to use TensorBoard and Weights & Biases, how to fix random seeds, and how to save checkpoints you can actually resume from.
After a week of experiments, the question is always the same: *which run was the good one, and how exactly did I get it?* If the answer lives in your memory or in a notebook cell you have since overwritten, the result is effectively lost. Experiment logging is the habit of recording every Run — its configuration, code version, data version, metrics over time and output files — so that results are comparable and reproducible. It is the foundation that tools like MLflow (covered in the MLOps module) build on.
What to log for every run
| Category | Examples | Why |
|---|---|---|
| Config / hyperparameters | lr, batch size, epochs, model size, optimizer, scheduler, augmentation, seed | To know what differed between runs. |
| Code version | git commit hash, uncommitted diff flag, library versions (pip freeze) | Same config + different code = different result. |
| Data version | dataset path + hash or DVC version, split seed, number of rows | Data changes silently more often than code. |
| Metrics over time | train/val loss, accuracy, LR, gradient norm, throughput (samples/s), GPU memory | Diagnose curves; compare runs at equal steps. |
| Artifacts | best/last checkpoints, confusion matrix plot, predictions on val set, the config file itself | Inspect failures later without re-training. |
| Environment | GPU type and count, CUDA/cuDNN version, hostname | Numerics differ across hardware and library versions. |
TensorBoard
TensorBoard is a local, file-based dashboard: your code writes *event files* into a log directory, and the TensorBoard web app reads them. PyTorch includes a writer in torch.utils.tensorboard. Each run gets its own subdirectory, and TensorBoard overlays all runs found under --logdir so you can compare them. Besides scalars it shows histograms of weights/gradients, images, text, the model graph, embeddings (projector) and a HParams tab for comparing hyperparameter settings.[1][2]
from torch.utils.tensorboard import SummaryWriter
config = {"lr": 3e-4, "batch_size": 64, "epochs": 20, "seed": 42}
writer = SummaryWriter(log_dir=f"runs/lr{config['lr']}_bs{config['batch_size']}")
for step in range(num_steps):
loss = train_step()
writer.add_scalar("loss/train", loss, step)
writer.add_scalar("lr", scheduler.get_last_lr()[0], step)
if step % 500 == 0:
for name, p in model.named_parameters():
writer.add_histogram(f"weights/{name}", p, step)
# one row per run in the HParams tab
writer.add_hparams(config, {"hparam/best_val_loss": best_val_loss})
writer.close()
# terminal: tensorboard --logdir runs -> open http://localhost:6006loss/train) groups charts.Weights & Biases (W&B)
W&B is a hosted tracking service (with a self-hosted option): runs are uploaded to a shared project, so a whole team sees the same dashboards. It automatically records git commit, system metrics (GPU utilization, memory) and the config, and adds sweeps (hyperparameter search), artifacts with lineage, and reports. MLflow covers similar ground and is open source; TensorBoard is the zero-setup option. The core API is three calls.[3]
import wandb
run = wandb.init(project="cats-vs-dogs",
config={"lr": 3e-4, "batch_size": 64, "epochs": 10})
for epoch in range(run.config.epochs):
train_loss, val_loss, val_acc = train_one_epoch()
wandb.log({"train/loss": train_loss, "val/loss": val_loss,
"val/acc": val_acc, "epoch": epoch})
run.finish()Seeds and determinism
Training uses randomness everywhere: weight initialization, data shuffling, dropout masks, augmentation, data splits. Fixing the Seed (random seed) of every random number generator makes a run repeatable *on the same hardware and software*. Full bitwise determinism on GPUs additionally requires deterministic kernels, which can be slower; PyTorch documents that complete reproducibility is not guaranteed across releases, platforms or CPU vs GPU.[4]
import os, random
import numpy as np
import torch
def set_seed(seed: int = 42, deterministic: bool = False):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed) # seeds CPU and all CUDA devices
if deterministic:
os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"
torch.use_deterministic_algorithms(True)
torch.backends.cudnn.benchmark = False
set_seed(42)
g = torch.Generator()
g.manual_seed(42)
loader = torch.utils.data.DataLoader(train_ds, batch_size=64, shuffle=True,
num_workers=4, generator=g)generator to the DataLoader so shuffling order is repeatable. For multi-worker loading, also seed workers with a worker_init_fn as shown in the PyTorch reproducibility notes.Checkpoints you can resume from
A Checkpoint that contains only model weights is enough for inference, but not for resuming training: the optimizer state (Adam's moment estimates), the LR scheduler position, the epoch/step, the AMP grad scaler and ideally RNG states must be saved too. Otherwise the resumed run behaves differently — for example, Adam restarts with zero moments and the LR schedule jumps back to warmup.[5]
# save
torch.save({
"epoch": epoch,
"step": step,
"model": model.state_dict(),
"optimizer": optimizer.state_dict(),
"scheduler": scheduler.state_dict(),
"best_val_loss": best_val_loss,
"config": config,
}, f"checkpoints/step_{step}.pt")
# resume
ckpt = torch.load("checkpoints/step_12000.pt", map_location="cpu")
model.load_state_dict(ckpt["model"])
optimizer.load_state_dict(ckpt["optimizer"])
scheduler.load_state_dict(ckpt["scheduler"])
start_step = ckpt["step"] + 1Knobs
- What it is
- How often (in steps) scalars are written; histograms/images usually at a much larger interval.
- ↑ If you increase it
- Less overhead and smaller log files, but short spikes and early instabilities can be missed.
- ↓ If you decrease it
- Fine-grained curves, but logging (and
.item()GPU syncs) can slow training and bloat storage. - Typical values
- Scalars every 10–100 steps; histograms every 500–5,000 steps.
- What it is
- How often to save a checkpoint, and how many to keep (e.g. last N + best by val metric; Hugging Face
save_steps,save_total_limit,load_best_model_at_end). - ↑ If you increase it
- (save more often / keep more) Less work lost on crashes or loss spikes, more choice of rollback points, but more disk and I/O time — large-model checkpoints can be many GB each.
- ↓ If you decrease it
- Saves disk, but a crash can cost hours, and you may not have a checkpoint near the best validation point.
- Typical values
- Every epoch for small models; every 30–60 minutes of compute for long runs; keep the last 2–3 plus the best.
- What it is
- Starting value for the random number generators (init, shuffling, dropout, augmentation, splits).
- ↑ If you increase it
- The value itself has no meaning — 'bigger' is not better. Changing it gives a different but equally valid sample of the run's randomness.
- ↓ If you decrease it
- Same as above. What matters is: fixed for debugging, varied (3–5 seeds) for drawing conclusions.
- Typical values
- Any integer; log it with the run.
.item() on GPU tensors every step in hot loops; and assuming a fixed seed gives identical results on a different GPU or library version.▸Go deeper: a minimal reproducibility checklist
- Config in a file (YAML/JSON or dataclass), logged as an artifact — no magic numbers in notebooks.
- Pinned environment (
requirements.txtwith versions, lock file, or a Docker image tag). - Git commit recorded; refuse to launch long runs from a dirty working tree.
- Data versioned (hash, DVC, or immutable dataset snapshots) and split indices saved.
- Seeds fixed and logged; results reported over several seeds.
- Evaluation script separate from training, runnable on any checkpoint.
Karpathy's recipe adds a cultural point: start with a fixed seed and a dumb baseline, change one thing at a time, and visualize the data and predictions at every stage — tracking only works if each run differs from the last in a single, recorded way.[6]
Quiz
model.state_dict(). Training uses Adam with a cosine LR schedule. What is likely to happen?References
- [1]TensorBoard: Get startedDocsTensorFlowtensorflow.org
- [2]torch.utils.tensorboardDocsPyTorchdocs.pytorch.org
- [3]Weights & Biases DocumentationDocsWeights & Biasesdocs.coreweave.com
- [4]Reproducibility (PyTorch notes on randomness)DocsPyTorchdocs.pytorch.org
- [5]Saving and loading a general checkpoint in PyTorchDocsPyTorchdocs.pytorch.org
- [6]A Recipe for Training Neural NetworksArticleAndrej Karpathy2019karpathy.github.io