AILearn AI
LearnGlossarySources
ID/EN
Learn AI — open material for learning AIEvery lesson cites its original sources.
↘Training Results & Evaluation
  1. Reading Loss & Accuracy Curves
  2. Classification Metrics
  3. Regression Metrics & Validation
  4. Experiment Logging & Reproducibility
  5. Hyperparameter Tuning
Modules
  1. ◎ AI Foundations
  2. ∿ Classical Machine Learning
  3. ⌬ Neural Networks
  4. ↘ Training Results & Evaluation
  5. ▦ Deep Learning Architectures
  6. ✎ Large Language Models
  7. ◐ Image Generation
  8. ♪ Audio & Speech AI
  9. ◈ Multimodal, Video & 3D
  10. ↻ Reinforcement Learning
  11. ⚙ ML Development & MLOps
  12. ★ Advanced & Frontier Topics
Learn/Training Results & Evaluation

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.

Intermediate~20 min·6 references
Key terms
Experiment trackingTensorBoardRunCheckpointReproducibilitySeed (random seed)ArtifactHyperparameter

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.

≈
A lab notebook
A chemist writes down reagents, quantities, temperature and time for every experiment — not only the successful ones — so anyone can repeat it. A training run is an experiment too: the 'reagents' are the code commit, data snapshot, hyperparameters and random seed.

What to log for every run

CategoryExamplesWhy
Config / hyperparameterslr, batch size, epochs, model size, optimizer, scheduler, augmentation, seedTo know what differed between runs.
Code versiongit commit hash, uncommitted diff flag, library versions (pip freeze)Same config + different code = different result.
Data versiondataset path + hash or DVC version, split seed, number of rowsData changes silently more often than code.
Metrics over timetrain/val loss, accuracy, LR, gradient norm, throughput (samples/s), GPU memoryDiagnose curves; compare runs at equal steps.
Artifactsbest/last checkpoints, confusion matrix plot, predictions on val set, the config file itselfInspect failures later without re-training.
EnvironmentGPU type and count, CUDA/cuDNN version, hostnameNumerics 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]

python
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:6006
Name run directories after the settings that vary, so the run list is readable. The slash in tags (loss/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]

python
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]

python
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)
Pass a seeded 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.
✓
Seeds are for debugging, not for winning
A fixed seed lets you rerun and debug. But a result that only holds for seed 42 is not a result. When comparing two ideas, run each with 3–5 different seeds and compare means (and spread). Never 'tune the seed'.

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]

python
# 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"] + 1

Knobs

knobLogging interval
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.
knobCheckpoint frequency & retention
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.
knobRandom seed
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.
!
Pitfalls
Logging only final numbers (you cannot diagnose curves you did not record); re-using the same log directory for different runs (curves get mixed); forgetting to log the data version; saving checkpoints without optimizer/scheduler state; calling .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
  1. Config in a file (YAML/JSON or dataclass), logged as an artifact — no magic numbers in notebooks.
  2. Pinned environment (requirements.txt with versions, lock file, or a Docker image tag).
  3. Git commit recorded; refuse to launch long runs from a dirty working tree.
  4. Data versioned (hash, DVC, or immutable dataset snapshots) and split indices saved.
  5. Seeds fixed and logged; results reported over several seeds.
  6. 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

1.
You resume training from a checkpoint that contains only model.state_dict(). Training uses Adam with a cosine LR schedule. What is likely to happen?
2.
Idea B beats idea A by 0.3% accuracy, each measured with a single run using seed 42. What should you do before concluding B is better?
3.
Which of these is NOT needed to reproduce a training run?
4.
You set all seeds, but your run on a different GPU model gives slightly different numbers. Why?
Score: 0/4

References

  1. [1]
    TensorBoard: Get started
    DocsTensorFlowtensorflow.org
  2. [2]
    torch.utils.tensorboard
    DocsPyTorchdocs.pytorch.org
  3. [3]
    Weights & Biases Documentation
    DocsWeights & Biasesdocs.coreweave.com
  4. [4]
    Reproducibility (PyTorch notes on randomness)
    DocsPyTorchdocs.pytorch.org
  5. [5]
    Saving and loading a general checkpoint in PyTorch
    DocsPyTorchdocs.pytorch.org
  6. [6]
    A Recipe for Training Neural Networks
    ArticleAndrej Karpathy2019karpathy.github.io
← Previous
Regression Metrics & Validation
Next →
Hyperparameter Tuning