Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 30 min · revision 2

Lab: Reading Loss Curves and Fixing a Broken Run

Train a healthy baseline, then break training three ways on the digits data (a learning rate that is too high, a deep sigmoid network whose gradients vanish, and a large network that overfits 150 images), read each failure from its loss curves and gradient norms, and fix it with a lower rate or clipping, He initialisation and batch normalisation, and dropout, weight decay and early stopping.

Contentsand lesson path

What you will learn

  • Diagnose training from loss and metric curves (underfitting, overfitting, divergence, vanishing or exploding gradients) and apply fixes such as learning-rate schedules, initialization, normalization, dropout, weight decay and early stopping.

Prerequisites: Machine Learning Fundamentals, Linear Algebra & Calculus for ML

01. Goal and setup

Most training problems announce themselves in two curves: the training loss and the validation loss, epoch by epoch. In this lab you learn to read them by breaking a working setup on purpose, one fault at a time, and then repairing it. Each broken run is a pattern you will meet in real projects.

Everything runs on the scikit-learn digits images (8 × 8 pixels, 10 classes), split 70/30 into training and validation rows. One shared file, harness.py, holds the data, a configurable MLP and a training loop that records both losses and the gradient norm of every layer at the first step. Each run also saves its curves as a PNG file, so you can look at the shapes the text describes.

You need: Python 3.12, PyTorch 2 (CPU build), scikit-learn 1.9 and Matplotlib. harness.py calls torch.set_num_threads(1) so that floating-point sums always happen in the same order; with PyTorch 2.15 the outputs below then repeat on most x86-64 machines, while other CPUs or versions can differ in the last digits. Each script runs in under a minute on a laptop.

Project layout at the end of the lab
curves-lab/
├── harness.py        data, a configurable MLP, the training loop, plots
├── baseline.py       step 1: a healthy run
├── lr_runs.py        step 2: learning rate too high
├── depth.py          step 3: vanishing gradients in a deep network
├── overfit_runs.py   step 4: a large network on 150 images
└── *.png             the curves of every run
Terminal
mkdir curves-lab && cd curves-lab
python3.12 -m venv .venv
source .venv/bin/activate      # Windows: .venv\Scripts\activate
python -m pip install "torch==2.15.*" --index-url https://download.pytorch.org/whl/cpu
python -m pip install "scikit-learn==1.9.*" "matplotlib==3.11.*"

02. Step 1: The harness and a healthy run

mlp() builds a network with a chosen depth, width and activation, optional dropout, optional batch normalisation (a layer that rescales each unit's outputs to zero mean and unit variance over the batch) and optional He initialisation. fit() is the loop from the training-loop lab with four additions: it records the gradient norm of each linear layer at the first step, can clip gradients, stops if the training loss stops being a finite number, and can stop early, restoring the best weights. The healthy run is two hidden layers of 128 ReLU units trained with AdamW.

Python · harness.py
"""Shared pieces: data, a configurable MLP, a training loop that records curves."""
import copy
import math

import matplotlib.pyplot as plt
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
from torch.utils.data import DataLoader, TensorDataset

torch.set_num_threads(1)  # one summation order, so runs repeat on the same set-up


def loaders(n_train=None, batch_size=64, seed=0):
    X, y = load_digits(return_X_y=True)
    X_tr, X_val, y_tr, y_val = train_test_split(X / 16.0, y, test_size=0.3,
                                                stratify=y, random_state=seed)
    if n_train:                                    # a deliberately small training set
        X_tr, y_tr = X_tr[:n_train], y_tr[:n_train]
    ds = lambda X, y: TensorDataset(torch.tensor(X, dtype=torch.float32),
                                    torch.tensor(y))
    g = torch.Generator().manual_seed(seed)
    return (DataLoader(ds(X_tr, y_tr), batch_size, shuffle=True, generator=g),
            DataLoader(ds(X_val, y_val), len(y_val)))  # one batch: all of it


def mlp(depth=2, width=128, act=nn.ReLU, dropout=0.0, norm=False, he_init=False):
    layers, n_in = [], 64
    for _ in range(depth):
        linear = nn.Linear(n_in, width)
        if he_init:                                # scale suited to ReLU
            nn.init.kaiming_normal_(linear.weight, nonlinearity="relu")
            nn.init.zeros_(linear.bias)
        layers += [linear] + ([nn.BatchNorm1d(width)] if norm else []) + [act()]
        layers += [nn.Dropout(dropout)] if dropout else []
        n_in = width
    return nn.Sequential(*layers, nn.Linear(n_in, 10))


def layer_grad_norms(model):
    return [m.weight.grad.norm().item() for m in model if isinstance(m, nn.Linear)]


def fit(model, opt, data, epochs, clip=None, patience=None, scheduler=None):
    train, val = data
    loss_fn, history = nn.CrossEntropyLoss(), []
    best = (math.inf, 0, None)
    for epoch in range(1, epochs + 1):
        model.train()
        total = n = 0
        for xb, yb in train:
            loss = loss_fn(model(xb), yb)
            opt.zero_grad()
            loss.backward()
            if epoch == 1 and n == 0:
                first_grads = layer_grad_norms(model)
            if clip:
                nn.utils.clip_grad_norm_(model.parameters(), clip)
            opt.step()
            total, n = total + loss.item() * len(xb), n + len(xb)
        if scheduler:
            scheduler.step()
        model.eval()
        with torch.no_grad():
            xv, yv = next(iter(val))
            logits = model(xv)
            val_loss = loss_fn(logits, yv).item()
            val_acc = (logits.argmax(1) == yv).float().mean().item()
        history.append((epoch, total / n, val_loss, val_acc))
        if not math.isfinite(total / n):
            print(f"stopped: training loss is {total / n} in epoch {epoch}")
            break
        if val_loss < best[0]:
            best = (val_loss, epoch, copy.deepcopy(model.state_dict()))
        if patience and epoch - best[1] >= patience:
            print(f"early stop at epoch {epoch}; best epoch {best[1]}")
            model.load_state_dict(best[2])
            break
    return history, first_grads, best


def show(history, epochs):
    print("epoch  train loss  val loss  val acc")
    for e, tr, vl, va in history:
        if e in epochs or e == history[-1][0]:
            print(f"{e:5d}  {tr:10.4f}  {vl:8.4f}  {va:7.3f}")


def plot(history, path, title):
    e, tr, vl, _ = zip(*history)
    plt.figure(figsize=(5, 3.2))
    plt.plot(e, tr, label="train loss")
    plt.plot(e, vl, label="validation loss")
    plt.xlabel("epoch"); plt.ylabel("cross-entropy"); plt.title(title); plt.legend()
    plt.tight_layout(); plt.savefig(path); plt.close()
Python · baseline.py
import torch

from harness import fit, loaders, mlp, plot, show

torch.manual_seed(0)
model = mlp()
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.01)
history, _, _ = fit(model, opt, loaders(), epochs=30)
show(history, epochs={1, 5, 10, 20})
plot(history, "baseline.png", "healthy run")
Terminal
python baseline.py
Expected output
epoch  train loss  val loss  val acc
    1      2.1969    2.0053    0.815
    5      0.3730    0.3355    0.924
   10      0.1514    0.1877    0.952
   20      0.0695    0.1154    0.969
   30      0.0356    0.1001    0.970

This is what healthy looks like: both losses fall quickly at first, then more slowly, and they stay close together; validation accuracy settles near 0.97. The gap that opens late (0.036 against 0.100) is normal, because a model usually fits its own training rows a little better. Keep baseline.png open as the reference shape.

03. Step 2: A learning rate that is too high

Switch to SGD with momentum 0.9 and try learning rates of 1.0, 0.5 and 0.05, plus 0.5 with gradient clipping. clip_grad_norm_(parameters, 1.0) computes the norm of all gradients taken together; if it exceeds 1.0, it scales every gradient by the same factor so that the total norm becomes 1.0, and it returns the norm measured before clipping. The direction of the step is kept, only its length is capped. The table shows the training loss at five epochs and the final validation accuracy.

Python · lr_runs.py
import torch

from harness import fit, loaders, mlp, plot

runs = [("SGD lr 1.0", 1.0, None), ("SGD lr 0.5", 0.5, None),
        ("SGD lr 0.5, clip 1.0", 0.5, 1.0), ("SGD lr 0.05", 0.05, None)]
print(f"{'run':<22}" + "".join(f"{'ep ' + str(e):>8}" for e in (1, 2, 3, 5, 10))
      + "   (training loss)")
for name, lr, clip in runs:
    torch.manual_seed(0)
    model = mlp()
    opt = torch.optim.SGD(model.parameters(), lr=lr, momentum=0.9)
    history, _, _ = fit(model, opt, loaders(), epochs=10, clip=clip)
    losses = {e: tr for e, tr, _, _ in history}
    print(f"{name:<22}" + "".join(f"{losses[e]:8.3f}" for e in (1, 2, 3, 5, 10))
          + f"   val acc {history[-1][3]:.3f}")
    plot(history, f"lr_{lr}_{clip}.png", name)
Terminal
python lr_runs.py
Expected output
run                       ep 1    ep 2    ep 3    ep 5   ep 10   (training loss)
SGD lr 1.0               3.061   2.379   2.372   2.332   2.333   val acc 0.102
SGD lr 0.5               1.740   0.684   1.075   2.022   1.541   val acc 0.359
SGD lr 0.5, clip 1.0     1.556   0.537   0.448   0.310   0.325   val acc 0.891
SGD lr 0.05              2.255   1.725   0.608   0.247   0.082   val acc 0.959

At lr 1.0 the first epoch ends at a loss of 3.06, above the 2.30 of random guessing, and the loss then sits at 2.33 with accuracy 0.10: the huge first steps pushed most ReLU units into the region where they output zero for every input (after training, 88% of the first hidden layer and all of the second are zero for every validation image), and a network of dead units cannot recover. At lr 0.5 the loss falls to 0.68 in epoch 2 and then climbs back to 2.02: the steps overshoot more and more, which is divergence in slow motion. With other models or data the same fault ends with the loss jumping to inf or nan, which fit() would report and stop on. Clipping keeps lr 0.5 usable (0.891) because no single step can be huge, but the run is still noisier than the real fix: a ten times lower rate, which trains smoothly to 0.959. Clipping is a safety net against rare large gradients, not a cure for a rate that is too high.

04. Step 3: Vanishing gradients in a deep network

Now make the network ten hidden layers deep and keep a sensible learning rate. Backpropagation multiplies one factor per layer on the way from the loss to the first layer: the layer's weights and the slope of its activation. If those factors are mostly below 1, the gradient shrinks exponentially with depth, the vanishing gradient problem; mostly above 1, it grows, the exploding gradient problem. The script prints the gradient norm of layers 1, 6 and the output layer at the very first step, for four versions of the same depth.

Python · depth.py
import torch
from torch import nn

from harness import fit, loaders, mlp

runs = [("sigmoid, default init", dict(act=nn.Sigmoid)),
        ("ReLU, default init", dict()),
        ("ReLU, He init", dict(he_init=True)),
        ("ReLU, He init, BatchNorm", dict(he_init=True, norm=True))]
for name, options in runs:
    torch.manual_seed(0)
    model = mlp(depth=10, **options)       # ten hidden layers of 128 units
    opt = torch.optim.SGD(model.parameters(), lr=0.05, momentum=0.9)
    history, grads, _ = fit(model, opt, loaders(), epochs=15)
    print(f"{name}: val acc {history[-1][3]:.3f} after 15 epochs")
    print(f"  first-step gradient norm, layer 1: {grads[0]:.1e}  "
          f"layer 6: {grads[5]:.1e}  output layer: {grads[-1]:.1e}")
Terminal
python depth.py
Expected output
sigmoid, default init: val acc 0.100 after 15 epochs
  first-step gradient norm, layer 1: 2.1e-09  layer 6: 3.5e-05  output layer: 5.9e-01
ReLU, default init: val acc 0.102 after 15 epochs
  first-step gradient norm, layer 1: 1.1e-04  layer 6: 6.6e-04  output layer: 6.1e-02
ReLU, He init: val acc 0.911 after 15 epochs
  first-step gradient norm, layer 1: 1.8e-01  layer 6: 3.2e-01  output layer: 7.6e-01
ReLU, He init, BatchNorm: val acc 0.972 after 15 epochs
  first-step gradient norm, layer 1: 2.1e+00  layer 6: 9.4e-01  output layer: 1.0e+00

With sigmoid, the first layer receives a gradient of 2.1e-09, about 300 million times smaller than the output layer: the sigmoid slope is at most 0.25, and ten such factors leave nothing. The loss curve gives this away without any gradient print: it sits at ln(10) ≈ 2.30 from the first epoch and never moves, and accuracy stays at chance. ReLU alone is not enough here, because PyTorch's default initialisation for nn.Linear is scaled for neither ReLU nor this depth, so the signal still shrinks from layer to layer. He initialisation (kaiming_normal_) draws weights with variance 2 / fan-in, which keeps the size of the activations roughly constant through ReLU layers; now the printed layers get gradients between 0.18 and 0.76, and the network learns (0.911). Batch normalisation re-centres and rescales each layer's outputs during training, which keeps every layer's inputs in a stable range whatever the weights do; here it trains faster still and reaches 0.972. Very deep networks also add residual connections, which give the gradient a direct path around each block.

05. Step 4: A large network on too little data

Give a network with 512 units per layer only 150 training images, between 11 and 19 per digit, and no regularisation. Run A shows the classic overfitting shape. Run B adds three fixes: dropout 0.5, stronger weight decay (0.1, decoupled as in AdamW) and early stopping with a patience of 15 epochs, which ends training when the validation loss has not improved for 15 epochs and restores the best weights. Run C shows the effect of the cure that is often the strongest: more data.

Python · overfit_runs.py
import torch

from harness import fit, loaders, mlp, plot, show

small = loaders(n_train=150)                 # 150 images, 11 to 19 per digit

torch.manual_seed(0)
model = mlp(width=512)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.0)
history, _, best = fit(model, opt, small, epochs=80)
print("A. 150 images, 512 units, no regularisation")
show(history, epochs={1, 10, 26, 40, 60})
print(f"   lowest val loss {best[0]:.4f} at epoch {best[1]}")
plot(history, "overfit.png", "150 training images, no regularisation")

torch.manual_seed(0)
model = mlp(width=512, dropout=0.5)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.1)
print("B. same data, dropout 0.5, weight decay 0.1, early stopping (patience 15)")
history, _, best = fit(model, opt, small, epochs=80, patience=15)
show(history, epochs={1, 10, 30})
print(f"   lowest val loss {best[0]:.4f} at epoch {best[1]}; those weights restored")
plot(history, "regularised.png", "dropout, weight decay, early stopping")

torch.manual_seed(0)
model = mlp(width=512)
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=0.0)
history, _, best = fit(model, opt, loaders(), epochs=30)
print(f"C. all 1,257 training images: lowest val loss {best[0]:.4f} at epoch {best[1]}")
Terminal
python overfit_runs.py
Expected output
A. 150 images, 512 units, no regularisation
epoch  train loss  val loss  val acc
    1      2.2701    2.1551    0.356
   10      0.3800    0.4562    0.893
   26      0.0280    0.2467    0.917
   40      0.0096    0.2686    0.919
   60      0.0045    0.2760    0.919
   80      0.0025    0.2795    0.919
   lowest val loss 0.2467 at epoch 26
B. same data, dropout 0.5, weight decay 0.1, early stopping (patience 15)
early stop at epoch 78; best epoch 63
epoch  train loss  val loss  val acc
    1      2.3013    2.2301    0.106
   10      0.9629    0.8909    0.854
   30      0.1532    0.2688    0.917
   78      0.0516    0.2719    0.920
   lowest val loss 0.2311 at epoch 63; those weights restored
C. all 1,257 training images: lowest val loss 0.0672 at epoch 28

In run A the training loss falls towards zero (0.0025), while the validation loss reaches its lowest point, 0.2467, at epoch 26 and then rises steadily to 0.2795. The curves have split: the model is now memorising the 150 images. Notice that validation accuracy stays at 0.919 the whole time; the model keeps the same answers but grows more confident in them, including the wrong ones, and cross-entropy punishes confident mistakes. A rising validation loss is the earlier and more sensitive warning.

Run B learns more slowly (dropout makes each step noisier), reaches a lower best validation loss, 0.2311 at epoch 63, and stops at epoch 78 with the epoch-63 weights restored. Regularisation and early stopping limit the damage, but they cannot create information: with all 1,257 training images (run C) the best validation loss is 0.0672, three to four times lower. When curves show overfitting, more or better data is the first thing to ask for; regularisation is what you do while you cannot get it.

06. Check your understanding

Practice check · 3 questions

Read the run

Use the outputs of this lab.

Q1. In run B of step 4, training stops at epoch 78 and restores the weights of epoch 63. Why epoch 63 and not epoch 78?
Q2. During a run, `clip_grad_norm_(model.parameters(), 1.0)` returns 3.7 for one batch. What did it do to that batch's gradients?
Q3. In run A of step 4, validation accuracy stays at 0.919 from epoch 40 to 80 while validation loss rises from 0.2686 to 0.2795. How can both be true?
Practice only: not graded, not saved, not evidence.

07. Apply it

The practice project asks you to document two deliberately broken runs with their curves and fixes. Use this harness on your own data or on Fashion-MNIST.

  1. Break the run with an excessive learning rate and with a missing model.eval() in the evaluation function (dropout stays on), and save both sets of curves.
  2. For each, write a three-line report: what the curves showed, the cause, and the fix with the curves after the fix.
  3. Add early stopping to your best configuration and record which epoch it restores and how the validation score compares with the last epoch.

08. Review prompt

Without looking back, sketch the training and validation curves of a healthy run, an overfitting run, a diverging run and a run with vanishing gradients; for each, name the fix you would try first and one other; explain what clip_grad_norm_ does to the gradients; say why He initialisation suits ReLU networks; and explain why validation loss can warn of overfitting before validation accuracy does.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check