Deep learning in practice · lesson 10 of 13
Parts in this lesson
Axb, yb = X[:32], y[:32]one fixed batch, to train on until the loss is almost 0
Bprint(pred.shape, target.shape)the cheapest debugging tool there is
CF.cross_entropy(logits, y)takes raw scores (logits): it applies softmax itself

Debugging training

Last updated

Most bugs in training code raise no error. The loop runs, the loss prints, and the model is quietly worse than it should be, or learning nothing at all. This lesson is a method for finding them: make the model memorise one batch, check every shape, read the loss curves, and look at the data and the predictions. Eight real training runs, each with a different fault, are there for practice.

By the end of this lesson you can

  • Check a model and its training loop by overfitting one batch
  • Find shape bugs that broadcasting hides
  • Diagnose common faults from training and validation loss curves
  • Work through a checklist before training for real

Overfit one batch first

Before training on everything, train on one batch of 32 examples, over and over, until the model knows them by heart. A network with thousands of weights can memorise 32 examples easily, so the loss should fall to nearly 0. If it can't, something is broken, and it's far quicker to find out in seconds on one batch than after an hour on the whole dataset (Karpathy, 2019).

This script tries it on a correct model and on one with a common bug, a softmax at the end of the model:

"""Overfit one batch first: a correct model drives the loss on 32 images to almost 0; a buggy one can't."""
import torch
from sklearn.datasets import load_digits
from torch import nn
from torch.nn import functional as F

X, y = load_digits(return_X_y=True)
xb, yb = torch.tensor(X[:32] / 16, dtype=torch.float32), torch.tensor(y[:32])

for name, buggy in (("correct", False), ("softmax twice", True)):
    torch.manual_seed(0)
    model = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))
    if buggy:
        model.append(nn.Softmax(dim=1))  # the bug: cross_entropy applies softmax itself, so this one is extra
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
    losses = {}
    for step in range(501):
        loss = F.cross_entropy(model(xb), yb)
        if step in (0, 100, 200, 500):
            losses[step] = loss.item()
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    accuracy = (model(xb).argmax(1) == yb).float().mean().item()
    print(f"{name:14} loss at steps 0, 100, 200, 500: " + " ".join(f"{v:.4f}" for v in losses.values()) + f"   accuracy {accuracy:.2f}")
Terminal, in ml-local/7-10
(.venv) $ python one_batch.py
correct        loss at steps 0, 100, 200, 500: 2.3230 0.2206 0.0332 0.0045   accuracy 1.00
softmax twice  loss at steps 0, 100, 200, 500: 2.3040 1.5521 1.4986 1.4922   accuracy 0.97

The correct model gets the loss down to 0.0045 and all 32 right. The buggy one gets 97% right too, so accuracy alone would have hidden the bug, but its loss stops at about 1.49 and won't go lower.

The reason: F.cross_entropy applies softmax itself, so it expects raw scores. Feed it probabilities, numbers between 0 and 1, and it applies softmax a second time. The best this second softmax can do with inputs between 0 and 1 is a 1 against nine 0s, which gives the right answer a probability of only e/(e+9)≈0.232, and a loss of −ln⁡0.232≈1.461. The model can never be confident, so even on examples it already gets right the loss stays high and the gradients keep pushing: the loss no longer measures what it should.

A loss that can't reach 0 on one batch is the symptom. Its causes are almost always in the code, not the data: an extra softmax, a missing zero_grad(), the wrong loss for the task, or labels that don't match their inputs.

Check shapes

Broadcasting (lesson 0.5) lets PyTorch combine arrays of different shapes without complaint. That's convenient, until it combines two that you never meant to:

"""A shape bug that raises no error: predictions of shape (32, 1) against targets of shape (32,)."""
import torch

torch.manual_seed(0)
pred = torch.randn(32, 1)       # a regression model's output: one number per example, as a column
target = torch.randn(32)        # the true values, as a flat row of 32

diff = pred - target            # broadcasting: (32, 1) - (32,) becomes (32, 32)
print("pred:", tuple(pred.shape), " target:", tuple(target.shape), " pred - target:", tuple(diff.shape))
print(f"mean squared error, wrong: {diff.pow(2).mean().item():.3f}")
print(f"mean squared error, right: {(pred.squeeze(1) - target).pow(2).mean().item():.3f}")
Terminal, in ml-local/7-10
(.venv) $ python shapes.py
pred: (32, 1)  target: (32,)  pred - target: (32, 32)
mean squared error, wrong: 2.187
mean squared error, right: 2.318

A regression model outputs one number per example as a column, shape (32, 1). The targets are a flat row, (32,). Subtracting them broadcasts to (32, 32): every prediction minus every target, 1,024 differences instead of 32. The mean of those squares is a number, 2.187, and gradient descent will happily make it smaller, but it's the wrong number, and the model learns to predict the average of all targets for every example. Nothing crashes.

The fix is one .squeeze(1). Finding it is the hard part, so print shapes: after loading the data, after every layer the first time you run a model, and on both sides of every loss. When a shape is a surprise, stop and find out why.

Check the data the same way. Print a few examples with their labels, and draw a few images. Count the classes. Look at the smallest and largest values (a forgotten / 16 is easy to see there).

Read the loss curves

Once the model trains on everything, record the training loss and the validation loss every epoch and plot both. Their shapes tell you a lot. This script trains the same network eight times; seven of the runs have something wrong:

"""Eight training runs, each with something different (or nothing) wrong, for the loss curve clinic."""
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
from torch.nn import functional as F

X, y = load_digits(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=500, stratify=y, random_state=0)
X_train, X_val = torch.tensor(X_train, dtype=torch.float32), torch.tensor(X_val, dtype=torch.float32)
y_train, y_val = torch.tensor(y_train), torch.tensor(y_val)
EPOCHS = 30


def run(lr=1e-3, sgd=False, n_train=None, zero_grad=True, scale_val=True, shuffle_labels=False, leak=False):
    torch.manual_seed(0)
    xt, yt, xv, yv = X_train, y_train, X_val, y_val
    xt = xt / 16                                  # pixels 0 to 16 become 0 to 1
    if scale_val:
        xv = xv / 16
    if n_train:
        xt, yt = xt[:n_train], yt[:n_train]
    if shuffle_labels:                            # the label column, out of step with the images
        yt = yt[torch.randperm(len(yt))]
    if leak:                                      # the answer hidden in the inputs: the first 10 pixels spell out the label
        xt, xv = xt.clone(), xv.clone()
        xt[:, :10], xv[:, :10] = F.one_hot(yt, 10).float(), F.one_hot(yv, 10).float()
    model = nn.Sequential(nn.Linear(64, 128), nn.ReLU(), nn.Linear(128, 10))
    opt = torch.optim.SGD(model.parameters(), lr=lr) if sgd else torch.optim.Adam(model.parameters(), lr=lr)
    train_losses, val_losses = [], []
    for epoch in range(EPOCHS):
        model.train()
        total = 0.0
        for idx in torch.randperm(len(xt)).split(32):
            loss = F.cross_entropy(model(xt[idx]), yt[idx])
            if zero_grad:
                opt.zero_grad()
            loss.backward()
            opt.step()
            total += loss.item() * len(idx)
        model.eval()
        with torch.no_grad():
            val_losses.append(F.cross_entropy(model(xv), yv).item())
        train_losses.append(total / len(xt))
    return train_losses, val_losses


runs = {
    "A": run(),                                   # nothing wrong
    "B": run(lr=0.3),                             # learning rate far too high for Adam
    "C": run(lr=1e-4, sgd=True),                  # learning rate far too low
    "D": run(n_train=100, lr=1e-2),               # 100 training images: overfitting
    "E": run(zero_grad=False),                    # a bug: zero_grad() forgotten
    "F": run(leak=True),                          # the label leaked into the inputs
    "G": run(shuffle_labels=True),                # labels shuffled
    "H": run(scale_val=False),                    # a bug: validation pixels not divided by 16
}
for name, (tr, va) in runs.items():
    print(f"run {name}")
    print("  train " + " ".join(f"{v:.3g}" for v in tr))
    print("  val   " + " ".join(f"{v:.3g}" for v in va))
Terminal, in ml-local/7-10
(.venv) $ python clinic.py
run A
  train 2.09 1.48 0.903 0.587 0.431 0.345 0.286 0.246 0.216 0.194 0.172 0.157 0.145 0.134 0.127 0.116 0.11 0.105 0.0977 0.0936 0.0886 0.083 0.0808 0.0757 0.0729 0.0689 0.0659 0.0631 0.0607 0.0591
  val   1.8 1.15 0.718 0.518 0.407 0.339 0.293 0.264 0.23 0.22 0.198 0.183 0.178 0.171 0.16 0.15 0.153 0.139 0.131 0.128 0.128 0.119 0.123 0.117 0.116 0.109 0.112 0.112 0.11 0.102
run B
  train 7.48 1.74 1.8 1.76 1.69 1.73 1.7 1.68 1.65 1.66 1.59 1.65 1.71 1.62 1.54 1.64 1.58 1.65 1.59 1.59 1.56 1.55 1.62 1.59 1.67 1.6 1.64 1.53 1.57 1.71
  val   1.71 1.74 1.86 2.02 1.94 1.74 1.98 1.78 1.7 1.65 1.7 1.74 1.77 1.67 1.72 1.72 1.79 1.69 1.75 1.61 1.61 1.79 1.62 1.92 1.74 1.72 1.63 1.64 1.88 1.74
run C
  train 2.31 2.31 2.31 2.31 2.31 2.31 2.31 2.31 2.31 2.31 2.31 2.31 2.31 2.31 2.31 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3
  val   2.31 2.31 2.31 2.31 2.31 2.31 2.31 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3 2.3
run D
  train 2.18 1.73 1.34 0.958 0.686 0.51 0.425 0.298 0.278 0.229 0.176 0.165 0.116 0.127 0.125 0.0824 0.062 0.0534 0.0526 0.038 0.0443 0.0344 0.0275 0.0286 0.0245 0.0206 0.0207 0.0176 0.016 0.0195
  val   2.01 1.71 1.36 1.06 0.886 0.739 0.616 0.65 0.624 0.563 0.498 0.491 0.468 0.511 0.493 0.479 0.448 0.426 0.411 0.491 0.471 0.435 0.424 0.424 0.42 0.431 0.429 0.431 0.443 0.415
run E
  train 2.01 1.06 0.673 1.01 1.41 0.874 0.871 0.709 0.592 0.524 0.589 0.4 0.514 0.417 0.482 0.624 0.38 0.569 0.379 0.309 0.487 0.451 0.392 0.367 0.45 0.431 0.442 0.324 0.226 0.292
  val   1.54 0.691 0.954 1.37 1.26 0.751 0.876 0.776 0.519 0.664 0.442 0.525 0.724 0.383 0.751 0.577 0.559 0.742 0.504 0.659 0.741 0.556 0.657 0.624 0.627 0.529 0.581 0.48 0.519 0.701
run F
  train 2.03 1.19 0.488 0.204 0.108 0.0675 0.0463 0.0338 0.0257 0.0202 0.0162 0.0134 0.0113 0.00957 0.00825 0.00715 0.00629 0.00557 0.00493 0.00442 0.00398 0.00359 0.00327 0.00299 0.00273 0.00252 0.00232 0.00214 0.00199 0.00185
  val   1.63 0.762 0.301 0.15 0.0915 0.0616 0.0451 0.0343 0.0272 0.022 0.0184 0.0155 0.0132 0.0117 0.01 0.00881 0.00802 0.00692 0.00633 0.00574 0.00524 0.00466 0.00429 0.00396 0.00371 0.00337 0.00314 0.00294 0.00276 0.00254
run G
  train 2.31 2.3 2.29 2.28 2.27 2.27 2.26 2.25 2.24 2.23 2.23 2.22 2.21 2.2 2.2 2.19 2.18 2.17 2.17 2.16 2.15 2.15 2.14 2.13 2.13 2.12 2.12 2.1 2.09 2.09
  val   2.32 2.32 2.34 2.35 2.36 2.37 2.37 2.39 2.4 2.41 2.42 2.42 2.43 2.43 2.45 2.45 2.46 2.47 2.47 2.47 2.47 2.48 2.49 2.49 2.5 2.49 2.51 2.51 2.5 2.51
run H
  train 2.09 1.48 0.903 0.587 0.431 0.345 0.286 0.246 0.216 0.194 0.172 0.157 0.145 0.134 0.127 0.116 0.11 0.105 0.0977 0.0936 0.0886 0.083 0.0808 0.0757 0.0729 0.0689 0.0659 0.0631 0.0607 0.0591
  val   0.521 1.2 1.04 1.17 1.15 1.05 0.9 0.986 0.875 0.964 0.872 0.767 0.889 0.943 0.819 0.851 0.916 0.781 0.765 0.718 0.774 0.706 0.761 0.776 0.735 0.703 0.749 0.807 0.768 0.683

The script's comments give the answers away, so cover them and try the clinic first. Each run is named by a letter only. Pick one, read its curves, and choose what you think happened:

Loss curve cliniceight real training runs; what happened in each?
0.0010.010.11102.30, a uniform guessepoch 130— training loss- - validation loss

Run A: training loss 2.09 → 0.0591, validation loss 1.8 → 0.102. The scale is logarithmic: each line is 10 times the one below. Choose a diagnosis and check it.

Some patterns to look for:

  • Both losses stuck at about 2.30: no learning at all. ln⁡10≈2.303 is the loss of a uniform guess over 10 classes. Check the learning rate first.
  • A loss that jumps around instead of falling: steps too big, or a bug in the loop.
  • Training falls, validation stops or rises: overfitting (lesson 7.8).
  • Validation much worse than training from the very first epoch: the two sets differ. Something was done to one and not the other.
  • Validation far better than it has any right to be: a leak. The answer got into the inputs somehow.

Look at the data and the predictions

Curves summarise; examples explain. Lesson 6.9 drew the confusion matrix and the digits the model got wrong. Do it for every model: the mistakes are where you learn what it hasn't understood, and sometimes that the label was wrong, not the model.

Karpathy's recipe puts it as a checklist. Before training for real:

  1. Look at the data. Dozens of examples, by eye. Duplicates, wrong labels, odd values.
  2. Set up the whole loop with a tiny model first, and check that the starting loss is what it should be: about ln⁡10 for 10 balanced classes.
  3. Overfit one batch (step 1).
  4. Print shapes everywhere (step 2).
  5. Get a simple baseline, such as logistic regression, so you know what a deep model has to beat.
  6. Change one thing at a time, and keep a record of every run (lesson 7.11).
  7. Plot both loss curves, every time (step 3).
  8. Look at the predictions, especially the wrong ones.

None of this is clever, and all of it is faster than staring at code.

Wrong way: a shuffled label column

A tempting test of a model is "does training accuracy go up?". Here's a dataset where the label column has been shuffled, so each image has a random digit's label: a bug that a careless merge of two files can cause. The network trains anyway:

"""The wrong way: the label column shuffled out of step with the images, and the network learns anyway."""
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from torch import nn
from torch.nn import functional as F

X, y = load_digits(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(X / 16, y, test_size=500, stratify=y, random_state=0)
X_train, X_val = torch.tensor(X_train, dtype=torch.float32), torch.tensor(X_val, dtype=torch.float32)
y_train, y_val = torch.tensor(y_train), torch.tensor(y_val)

torch.manual_seed(0)
y_train = y_train[torch.randperm(len(y_train))]   # the bug: labels no longer belong to their images

model = nn.Sequential(nn.Linear(64, 512), nn.ReLU(), nn.Linear(512, 512), nn.ReLU(), nn.Linear(512, 10))
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
for epoch in range(1, 201):
    model.train()
    for idx in torch.randperm(len(X_train)).split(32):
        loss = F.cross_entropy(model(X_train[idx]), y_train[idx])
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    if epoch in (1, 25, 50, 100, 200):
        model.eval()
        with torch.no_grad():
            train_acc = (model(X_train).argmax(1) == y_train).float().mean().item()
            val_acc = (model(X_val).argmax(1) == y_val).float().mean().item()
        print(f"epoch {epoch:3}: training accuracy {train_acc:.3f}, validation accuracy {val_acc:.3f}")
Terminal, in ml-local/7-10
(.venv) $ python shuffled.py
epoch   1: training accuracy 0.139, validation accuracy 0.030
epoch  25: training accuracy 0.787, validation accuracy 0.096
epoch  50: training accuracy 0.995, validation accuracy 0.068
epoch 100: training accuracy 1.000, validation accuracy 0.084
epoch 200: training accuracy 1.000, validation accuracy 0.080

Training accuracy climbs from 13.9% to 99.5% by epoch 50, and 100% from epoch 100. A large enough network can memorise 1,297 random labels, one image at a time (Zhang and others, 2017, did the same with 50,000 photographs). Validation accuracy never gets off the floor: 3.0% to 9.6%, no better than guessing one of 10 digits. There's no pattern to learn, so nothing it learns carries over.

Training accuracy measures how well a model fits its training data, which a big enough model can always do. Only the validation numbers say whether it learned anything. If training improves and validation sits at chance, stop and look at the data: print a few images with their labels, and see if the labels are right.

Check what you learned

Training on one batch of 32 images for 500 steps, the loss stops at 1.49 and won’t go lower. What does that suggest?
pred has shape (64, 1) and target has shape (64,). What shape is pred − target?
Training loss falls steadily, but validation loss rises from the first epoch, above 2.30. What should you check first?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning