Neural-net foundations13 / 15

Lesson 13 · Practical engineering

Debugging training

The problem

Most bugs in ordinary code crash. Most bugs in training code don't. Pass probabilities where PyTorch wants logits, or forget to clear the gradients. The loop still runs, the loss prints, and the network learns something. It learns worse, and nothing tells you why.

Andrej Karpathy put it this way in his much-shared blog post "A Recipe for Training Neural Networks" (2019): neural net training "fails silently". A wrong setting usually still trains, a bit worse, so you can't find the bug by waiting for an error.

This lesson is a set of cheap checks that catch most of these bugs, and a guide to reading loss curves. Everything uses the course's default setup: the Lesson 4 template, the 2-16-16-2 network and the 200 rush-hour deliveries.

Bug hunt

Here is the Lesson 4 trainer five more times. Each of runs A to E has one real bug hidden in it. Train a run, watch the curves, run the two checks under the plot, and guess the bug. Then fix it and train again. "Healthy" has no bug, for comparison.

on time late P = 0.5

Step 0 · epoch 0

00.20.40.60.8100.20.40.60.81epochloss00.20.40.60.810%50%100%epochaccuracy
train 0.891 (51%)validation 0.963 (47%)

Check 1, the loss before training: 0.891 (for 2 classes, expect about ln 2 = 0.693).

Check 2, overfit one batch of 8 for 300 steps: (a working loop gets close to 0).

The Lesson 4 trainer (2-16-16-2, AdamW at learning rate 0.01, batches of 32) with one hidden bug per run. The checks under the curves are the first two items of this lesson's checklist.

Every one of these bugs runs without an error. Some still reach good accuracy, which makes them harder to spot. The rest of the lesson explains each check, and names the bug in each run, so try the hunt first.

Before you train: four checks

1. Look at the data and the labels

Before any model code, print a few examples with their labels and check them by eye. Plot them if you can. For the deliveries: is a 7 km trip at 21:00 marked late? Is a 1 km trip at 18:00 marked on time?

Do it at the point where the data enters the model, after every loading, shuffling and scaling step. Karpathy's advice is the same: look at your data right before it goes into the network. Two of the five bugs above live in the data:

  • Run D shuffles the labels on their own, so each delivery carries a random other delivery's label. A plot of the training deliveries looks like confetti: late and on-time marks with no pattern.
  • Run A feeds in the raw numbers. Distances run from 0 to 8, but hours run from 17 to 23. Every first-layer sum is dominated by the hour, and the starting weights are badly matched to inputs that size. The template standardises both features for this reason.

2. Check the loss before training

A freshly built classifier hasn't learned anything, so it should be unsure. With small random weights, its logits are all close to 0. The softmax of equal logits gives every class the same probability, 1/C1/C for CC classes. The cross-entropy loss is then

−ln⁡1C=ln⁡C-\ln \frac{1}{C} = \ln C

For 2 classes that's ln⁡2≈0.693\ln 2 \approx 0.693. Karpathy's post calls this "verify loss @ init".

Worked example

The starting loss for the deliveries

  1. Two classes, on time and late. If both logits are 0, the softmax gives e0/(e0+e0)=0.5e^0 / (e^0 + e^0) = 0.5 to each.

The check needs no training at all. A starting loss far above ln⁡C\ln C means the network starts out confidently wrong: badly scaled inputs, a too-large initialisation, or a bug in the loss. A starting loss far below ln⁡C\ln C is suspicious too: is the label leaking into the input?

Predict first

A 10-class classifier, freshly initialised with small random weights. What should its first loss be?

3. Overfit one batch

Take one small batch, say 8 deliveries, and train on it alone for a few hundred steps. A network with 354 weights can memorise 8 examples. So if the code is right, the loss on that batch should go almost to 0.

This is overfitting one batch. It tests the model, the loss, the backward pass and the optimiser together, in seconds. If the loss won't go near 0, look for the bug before training on everything. Karpathy's post lists it as "overfit one batch".

In PyTorch, from the seed-0 starting weights, 300 steps on the first 8 deliveries give:

RunLoss after 300 steps
Healthy0.0002
C: softmax before the loss0.3134
A: raw inputs0.2438

Run C's number isn't random. That's the floor Lesson 2 worked out: softmax(1, 0) gives the right class only 0.731, so the loss can't drop below −ln⁡0.731=0.313-\ln 0.731 = 0.313.

The figure's run C stalls at the same number. It's the bug Lesson 2 warned about: F.cross_entropy wants logits, not probabilities.

Overfitting one batch doesn't catch everything. Run D, with shuffled labels, memorises its 8 wrong labels as easily: 0.0004. A network can memorise anything, true or not. That's why check 1, looking at the data, comes first.

4. Find a sensible learning rate

A learning rate that's 100 times too big doesn't crash either. Run E uses 1.0 instead of the template's 0.01. Its loss bounces around and never settles.

To find a good rate quickly, Leslie Smith suggested a short run with a growing rate (Cyclical Learning Rates for Training Neural Networks, WACV 2017). Start tiny, multiply the rate by the same factor every step, and record the loss. This is often called a learning-rate range test. Here it is on the default network, with the whole training set as the batch: 100 steps from 0.0001 to 10.

0.00010.0010.010.111000.20.40.60.811.2learning rate (log scale)losslowest

Step 40: learning rate 0.01048, loss 0.546

A learning-rate range test on the default network: 100 AdamW steps on all 200 deliveries, with the learning rate growing 10 times every 20 steps, from 0.0001 to 10.

Things to notice:

  • Below about 0.001, nothing happens. The loss sits near 0.68. Each step is too small to matter.
  • Between about 0.005 and 0.05, the loss falls fastest. The template's 0.01 is in this range.
  • Near 0.3, the loss is lowest. Past it, the curve turns ragged and climbs. By 2 it's back near the start, and by 10 it's above it.

A common rule of thumb is to pick a rate somewhat below the lowest point, often about a tenth of it. Here that's about 0.03. Treat the result as a starting point, not an answer: the test mixes "this rate is good" with "the network has already learned a bit". Karpathy's post offers a simpler start: Adam at a learning rate of 3e-4 is "safe" for many problems.

Reading loss curves

The loss curve is the one thing you watch during every run. Its shape usually tells you where to look first. Here are six real curves, each from a short run of the default network with one thing changed. Pick a diagnosis for each.

0102030405000.20.40.6epochloss
train 0.672validation 0.684

Pick a diagnosis to see what caused this curve.

Six loss curves: training (solid) and validation (dashed). Each is a real PyTorch run of the default network with one thing changed, stored with the page. Pick what went on, then read the cause.

The shapes, in short:

The curveLook first at
Flat, near ln⁡C\ln Ca learning rate far too small, or no gradient reaching the weights
Up, or jumping around above where it starteda learning rate too high
Noisy, but trending downnothing: small batches are noisy; smooth it before judging
Ends suddenly in NaNa blow-up: too high a rate, no clipping, or a log⁡0\log 0
Training falls, validation turns upoverfitting: see Lesson 7
Validation below trainingusually fine: dropout acts only in training, or the training set is noisier

During training: watch for NaNs

A loss of NaN ("not a number") poisons everything after it. Any arithmetic with NaN gives NaN, so one bad step turns every weight into NaN. The usual causes are:

  • A learning rate that's too high, or that jumps. One huge step makes the logits enormous, the loss becomes infinite, and its gradient NaN. Curve 6 in the figure above is this: the rate jumped 1,000 times at epoch 31.
  • Exploding gradients. Clipping caps their size.
  • log⁡0\log 0 in a hand-written loss. The logarithm of 0 is −∞-\infty, and 0×(−∞)0 \times (-\infty) is NaN. PyTorch's built-in losses work from logits with logsumexp, which never takes log⁡0\log 0. Use them.

Two habits find the trouble early. First, log the gradient norm every step. clip_grad_norm_ returns it for free, and a jump in it can come before the jump in the loss. Second, stop the run on the first non-finite loss, rather than training on for hours.

To find which operation made the NaN, PyTorch has an anomaly mode. Inside torch.autograd.detect_anomaly(), the backward pass checks every gradient as it's made. When one is NaN, it raises an error naming the operation, with the line of your code that created it. The PyTorch docs say to use it only for debugging, because the checks slow everything down.

Finding the operation that made a NaN
def find_the_nan() -> str:
    """A hand-written loss that takes log(0). detect_anomaly names the operation whose gradient is NaN."""
    p = torch.tensor([0.0, 0.7], requires_grad=True)  # predicted P(late): the first is exactly 0
    y = torch.tensor([0.0, 1.0])
    with torch.autograd.detect_anomaly():  # slow: only switch it on while hunting a NaN
        loss = -(y * torch.log(p) + (1 - y) * torch.log(1 - p)).mean()  # 0 · log(0) = 0 · (−inf) = nan
        try:
            loss.backward()
        except RuntimeError as err:
            return str(err)
    return "no error"
Function 'LogBackward0' returned nan values in its 0th output.

The culprit is the logarithm. With F.binary_cross_entropy_with_logits on the logit, the same loss would never have taken log⁡0\log 0.

The pitfalls checklist

The mistakes that cost the most time in practice. Each one runs without an error.

  1. Forgetting optimizer.zero_grad(). Gradients add up across steps (gradient accumulation). Run B.
  2. A softmax before F.cross_entropy. The loss wants logits. Run C; overfit-one-batch stalls at 0.313.
  3. The wrong mode. Forgetting model.eval() before validation leaves dropout on and batch norm using batch statistics. Forgetting model.train() afterwards trains with them off. The template's evaluate and train_one_epoch each set the mode for this reason (train and eval mode).
  4. Inputs and labels shuffled separately. Shuffle indices, then use the same indices for both, as DataLoader(shuffle=True) does. Run D.
  5. Inputs not standardised, or standardised with the validation set's numbers. Run A.
  6. A learning rate 10 or 100 times too high. Run E. Do a range test.
  7. A log⁡0\log 0 in a hand-written loss. Use the built-in losses on logits.
  8. Validation data leaking into training. Duplicates across the split, or scaling fitted on all the data. Validation then looks better than the model is. See data leakage.

Case studies

A published checklist: Karpathy's recipe

Karpathy's 2019 post is the most widely shared checklist of this kind. Its opening observations are the ones this lesson started with: training is a "leaky abstraction", and it "fails silently". The recipe has six stages, done in order:

  1. Become one with the data. Spend time looking at examples before writing model code: duplicates, corrupted labels, imbalances.
  2. Set up the end-to-end skeleton and get dumb baselines. Among its tips: "fix random seed", "verify loss @ init" and "overfit one batch", and looking at the data right before it enters the network.
  3. Overfit. Get a model big enough to fit the training set well. "Adam is safe" here, with a learning rate of 3e-4; add complexity one piece at a time.
  4. Regularise. Trade training loss for validation loss. The post calls more real data "by far" the best way; then come the methods of Lesson 7.
  5. Tune. Random search over hyperparameters, rather than a grid.
  6. Squeeze out the juice. Ensembles, and training for longer.

This lesson's checks are mostly from stage 2. The order matters as much as the checks: change one thing at a time, and check it worked before the next.

Made-up case: the classifier stuck at 50%

This case is invented, to show the pattern. A team trains a classifier for "will this order be refunded?". The training loss falls from 0.69 to 0.61 and stalls. Validation accuracy hovers around 52%, about as good as guessing. They try a bigger network, a smaller learning rate and a different optimiser, with no luck.

The cause: inputs and labels were loaded from two files and shuffled separately, so each order got a random other order's label. The starting loss looked right, and overfitting one batch passed, because a network can memorise random labels. Printing five orders next to their labels found it in a minute. This is run D.

Made-up case: the loss that turned into NaN at step 3,000

This case is invented, to show the pattern. A run trains smoothly for 3,000 steps, then the loss prints nan and stays there. The schedule had a bug: at step 3,000, a warm-up meant to end at a learning rate of 0.001 jumped to 1.0. The first big step made the logits huge, the loss infinite, and every weight NaN.

The gradient-norm log showed the jump on the step before the NaN. Two lines would have contained it: clip_grad_norm_ to cap the step, and a check that stops the run on the first non-finite loss. Curve 6 in the loss-curve figure is the same story on the deliveries.

In PyTorch: a checked template

Here are the checks as small functions you can run before every long training run. The loop is the template's train_one_epoch with three additions. It checks each batch's shapes and labels, stops on a non-finite loss, and logs the gradient norm at every step.

train_one_epoch, with checks
def train_one_epoch_checked(
    model: nn.Module,
    loader: DataLoader,
    loss_fn: nn.Module,
    optimizer: torch.optim.Optimizer,
    device: torch.device,
    n_classes: int = 2,
) -> tuple[float, list[float]]:
    """The template's train_one_epoch with checks. Returns the mean loss and each step's gradient norm."""
    model.train()
    total, count, grad_norms = 0.0, 0, []
    for x, y in loader:
        x, y = x.to(device), y.to(device)
        assert x.ndim == 2 and y.shape == (x.shape[0],), f"bad batch shapes {x.shape}, {y.shape}"
        assert y.min() >= 0 and y.max() < n_classes, "a label is out of range"
        optimizer.zero_grad()
        logits = model(x)  # (batch, n_classes)
        assert logits.shape == (x.shape[0], n_classes), f"logits have shape {logits.shape}"
        loss = loss_fn(logits, y)
        if not torch.isfinite(loss):
            raise RuntimeError(f"loss is {loss.item()} after {len(grad_norms)} steps of this epoch")
        loss.backward()
        # max_norm=inf measures the norm without clipping; use a real limit to clip as well
        grad_norms.append(nn.utils.clip_grad_norm_(model.parameters(), max_norm=float("inf")).item())
        optimizer.step()
        total += loss.item() * len(y)
        count += len(y)
    return total / count, grad_norms

clip_grad_norm_(..., max_norm=float("inf")) measures the gradient norm without clipping. Give it a real limit to clip as well, as in Lesson 6. The assert lines cost almost nothing; they catch a wrong shape the moment it appears, instead of 50 lines later.

The starting-loss check:

Check the loss before training
@torch.inference_mode()
def initial_loss(model: nn.Module, loader: DataLoader) -> float:
    """The mean loss before any training. For C balanced classes it should be close to ln C."""
    model.eval()
    total, count = 0.0, 0
    for x, y in loader:
        total += nn.functional.cross_entropy(model(x), y, reduction="sum").item()
        count += len(y)
    return total / count


def check_initial_loss(model: nn.Module, loader: DataLoader, n_classes: int, tolerance: float = 0.3) -> float:
    loss = initial_loss(model, loader)
    expected = math.log(n_classes)  # 0.69 for 2 classes, 2.30 for 10
    if abs(loss - expected) > tolerance:
        print(f"warning: starting loss {loss:.3f}, expected about {expected:.3f}")
    return loss

Overfitting one batch:

Overfit one batch
def overfit_one_batch(model: nn.Module, x: torch.Tensor, y: torch.Tensor, steps: int = 300, lr: float = 0.01) -> float:
    """Train on one small batch only. A working model and loop drive its loss close to 0."""
    optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.0)
    model.train()
    for _ in range(steps):
        optimizer.zero_grad()
        loss = nn.functional.cross_entropy(model(x), y)
        loss.backward()
        optimizer.step()
    return loss.item()

The learning-rate range test:

A learning-rate range test
def lr_range_test(
    model: nn.Module, x: torch.Tensor, y: torch.Tensor, lr_min: float = 1e-4, lr_max: float = 10.0, steps: int = 100
) -> tuple[list[float], list[float]]:
    """Raise the learning rate from lr_min to lr_max by the same factor every step, and record the
    loss at each rate. Uses the whole batch every step, so the run is exactly repeatable."""
    optimizer = torch.optim.AdamW(model.parameters(), lr=lr_min)
    factor = (lr_max / lr_min) ** (1 / (steps - 1))
    lrs, losses = [], []
    model.train()
    for t in range(steps):
        lr = lr_min * factor**t
        for group in optimizer.param_groups:
            group["lr"] = lr
        optimizer.zero_grad()
        loss = nn.functional.cross_entropy(model(x), y)
        loss.backward()
        optimizer.step()
        lrs.append(lr)
        losses.append(loss.item())
        if not math.isfinite(loss.item()):
            break  # no point going on
    return lrs, losses
starting loss 0.678 (ln 2 = 0.693)
overfit one batch of 8, bug=None: loss 0.0002
overfit one batch of 8, bug=softmax-first: loss 0.3134
lr range test: lowest loss 0.300 at lr 0.305

Common misconceptions

"If it trains without an error, the code is right." Every bug in this lesson runs without an error. Some still reach over 90% accuracy.

"Overfitting one batch proves the data is fine." It tests the model, loss and loop. A network memorises shuffled labels as easily as true ones. Look at the data too.

"A starting loss of 0.69 is a bad sign." For 2 balanced classes, an untrained network should give about that. It's a problem only if it's still there after training.

"Validation loss below training loss means a bug." Dropout makes training loss look worse, and the training set may hold more noisy labels. Check those first.

"model.eval() is enough for validation." It sets dropout and batch norm to test behaviour. It doesn't stop gradients being tracked; that's torch.inference_mode(). Use both: eval() for correct outputs, inference_mode() for speed.

Recap

  • Training bugs rarely crash. Find them with cheap checks before a long run, not by waiting.
  • Look at the data and labels at the point they enter the model.
  • An untrained classifier's loss should be about ln⁡C\ln C: 0.69 for 2 classes, 2.30 for 10.
  • A working model and loop can overfit one small batch to almost 0. If it can't, there's a bug; if it can, the data may still be wrong.
  • A learning-rate range test shows where the loss falls fastest and where it blows up. Start below the lowest point.
  • Read the loss curve's shape: flat, bouncing, noisy, NaN, splitting train and validation. Each points to a first place to look.
  • PyTorch names in this lesson: clip_grad_norm_ to log the gradient norm, torch.autograd.detect_anomaly(), torch.isfinite, F.cross_entropy on logits, and model.train() and model.eval().