Here is the same small network, trained on the same 16 examples, three times. In the first run the loss falls from to . In the second, a data loader hands the network labels that are re-drawn (and so wrong) at every step, and the loss stays near . In the third, one sign in the update is wrong, and the loss reaches . None of the three runs raises an error. All three print a number at every step.
That is why training a neural network is hard to debug: a broken network still trains. It just trains badly, and the only visible symptom is a loss curve. This lesson is a routine for the two situations you will meet most: before a first run (how to be fairly sure the code is right) and after a bad run (how to find out what is wrong). It does not teach the tools again. The learning rate, the batch size, regularization and normalization have their own lessons, and each check below points to the lesson that explains it.
The routine in one list
From the cheapest step to the most expensive: (1) look at the data, (2) fix the seed and get a baseline, (3) check that the first loss is about , (4) overfit one small batch, (5) train on everything and read the curves, (6) run sanity checks when a curve looks wrong.
Andrej Karpathy’s blog post “A Recipe for Training Neural Networks” (25 April 2019) is a well-known write-up of the same stages: become one with the data, set up the training and evaluation code with simple baselines, overfit, regularize, tune. It is worth reading after this lesson.
Before you train
Look at the data. Print ten examples and their labels, the number of examples per class, and the smallest and largest input value. Most data bugs show up here: labels that do not match the inputs, an image stored as to where the code expects to , a class with five examples. Everything later assumes that the labels belong to the inputs, and no loss curve can tell you if they do not (see the run with labels shuffled once in Cell 2).
Fix the seed. With a seed (P1.G3) the same run gives the same curve, so you can tell whether a change helped or whether it was luck. Seeds only make a run repeatable. They do not make it correct.
Get a baseline. Find the score of a trivial model before the network trains. For classification, always answering with the most common class is the simplest one, and a linear model such as logistic or softmax regression (P3.A1, P3.A7, P3.A8) is the next. Suppose of the examples belong to one class. Then that trivial answer has accuracy and a cross-entropy loss of if it predicts those probabilities. A network with accuracy has not learned much. For regression, predicting the mean of the training targets gives a mean squared error equal to their variance.
Compute the expected first loss. With starting weights of ordinary size, the output of a softmax classifier is close to equal probabilities. Then each example has probability about for its true class, and the cross-entropy loss (P4.6) is
For this is , for it is , for it is , and for a language model with a vocabulary of tokens it is . Compute the loss of the first batch before any update and compare. Cell 1 below does it for a 10-class problem with the last layer of the network scaled three ways:
- last layer scaled by : first loss , close to ;
- last layer at the usual scale (the scale of P4.12): ;
- last layer times larger: , which is times .
A first loss near is a good sign. A moderately higher one, such as here, is common and not a bug: the initial outputs are not exactly equal. A loss far above means the network starts out confidently wrong, which points to starting weights that are too large (P4.12) or to a loss function used the wrong way. A first loss far below is also a warning: the network may be seeing the labels, which is a data leak (P3.A11). These cut-offs are rules of thumb, not laws.
Overfit one small batch
Take one batch of 16 or so examples, switch off regularization and augmentation, and train on that batch alone for a few hundred steps. A correct network with enough capacity memorizes 16 examples, so the loss should reach a value close to and the predictions should match the labels. In Cell 1 the loss goes at steps , , and .
This test is cheap and it checks the whole chain at once: data, labels, forward pass, loss, backward pass, optimizer step. When it fails, the way it fails tells you where to look:
- The loss stays near (the “redrawn” column: labels re-drawn at every step, so there is nothing to learn: , , , ). The network gets no usable signal. Usual causes: a learning rate far too small, a frozen layer, gradients that never reach the weights, or labels that change between steps (for example a loader that reshuffles inputs and labels separately each epoch). Labels that are wrong but fixed are not caught by this test, because a network can memorize them; the shuffled-labels test below and the data check catch those.
- The loss goes up or becomes NaN (the “flipped” column: at step 50). The update goes the wrong way (a sign error), or the learning rate is much too large.
- The loss falls and then stalls above . The model may be too small for the batch, the learning rate may be too large for a fine fit, or some examples may have two different labels.
Only when this passes is it worth training on all the data. Then every later failure is a failure of learning from more data, which is the subject of the curves below, and not of the basic code.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The cell prints, in order, the loss at the start for three scales of the last layer (, , ), a check of two gradients, and the overfit table. Two things to notice in the gradient check. The backpropagation values and the numerical ones agree to five decimals ( and ). And the gradient norms of the two weight matrices are and , which is a ratio of about : the two layers are of the same order, with no sign of vanishing or exploding gradients (P4.16). The cell also reports that none of the hidden units is inactive on every example of the batch ( of ).
Sanity checks for a run that looks wrong
When a run misbehaves, these checks each take a few minutes. They are listed from the cheapest.
- Gradient check on a tiny model. Compare the gradient from backpropagation with the numerical one, (P1.C1, P4.9, P4.10). If your own backward code or a custom layer is wrong, this finds it. Use a small model and a handful of weights, as in Cell 1.
- Gradient norms. Log the total gradient norm and the norm of each layer (P4.16). Norms that fall steeply towards the input mean vanishing gradients, a sudden jump of a hundred times is a spike, and
nanorinfneeds attention at once. - Dead ReLUs. A hidden unit whose input is negative for every example outputs and gets no gradient (P4.4). Count the units that are inactive on a whole batch. A large fraction usually comes from a learning rate that was too high or from a poor initialization.
- Train and eval mode. Dropout and BatchNorm behave differently in training and evaluation (P4.17, P4.19). Call
model.train()before the training steps andmodel.eval()before measuring the validation loss. Forgettingeval()gives noisy, worse validation numbers. - Shapes and broadcasting. Print the shape of every tensor once (P4.5). A prediction of shape minus a target of shape broadcasts to an table, and the mean of that table is a valid number that is silently wrong.
- The shuffled-labels test. Shuffle the training labels once, so that they no longer match the inputs, and train. The validation loss must not improve. In Cell 2, with real labels the best validation loss is . With labels shuffled once the training loss still falls to (the network memorizes the wrong labels) but the validation loss never gets clearly below chance: its best value is , against , and it ends at . If a shuffled run does improve on validation, the pipeline leaks information (P3.A11).
Reading loss curves
A loss curve plots the loss against the number of training steps. Plot two lines: the training loss and the validation loss (P3.A4), measured on examples the network does not train on. One more name to keep apart: a learning curve (P3.A3) plots the error against the number of training points, while a loss curve plots the loss against training steps. Both show the same two stories (a gap that is too wide, or both errors too high), but on different horizontal axes.
Below are eight real runs of small networks, each from NumPy code that you can run in Cell 2. Training loss is the solid line, validation loss is the dashed line with a square at its end, and the dotted line marks , the loss of a model that says 50/50. Try to name each curve first, then tap it to see what it says.
What the shapes say
Each shape has an ordinary cause and a first thing to try. The runs use two small tasks with 10 inputs. In one, the class depends on whether the first two inputs have the same sign. In the other, it is the sign of their sum, with of the labels flipped.
- Healthy. Both losses fall from to (training) and (validation). They stay close, and the validation line sits a little above the training line.
- Learning rate too low. The same network with goes from to only in 400 steps, in a nearly straight line. A short sweep of the rate finds the fix. Final validation loss was at , at and at (P4.14).
- Learning rate too high. At the losses spike to (training) and (validation), partly recover and spike again; the validation loss ends at ( trains fine, with a final validation loss of ). The same overshoot in one weight is the zig-zag and divergence of P1.F3. Lower the rate, add warmup, and log the gradient norm (P4.14, P4.16).
- Overfitting. 100 training examples, 64 hidden units, wrong labels. The training loss falls to while the validation loss reaches its lowest value, , at step and then climbs to . Stop near the lowest point, or add regularization or data (P4.17, P4.18, P3.A3).
- Underfitting. Without a hidden layer, the network cannot separate the first task, so both losses stay near for the whole run. Training longer does nothing. Give the model more capacity (P3.A3, P4.3).
- Plateau, then a drop. With very small starting weights the loss stays at for about 75 steps, is below at step , and reaches at the end. A plateau is not always a failure. A plateau that never ends is: look at the learning rate, the initialization (P4.12) and the dead units.
- Validation below training. With dropout (P4.17) at , the training loss ends at and the validation loss at . The training loss is measured with half the units switched off and the validation loss with the full network. Other causes: augmentation applied only to the training data (P4.18), a training loss averaged over an epoch while the model improves, an easier validation set, or a leak (P3.A11). Measure both in the same mode before you worry.
- Noisy batch loss. With batches of 8 examples, the logged batch loss swings widely (up to ) while the validation loss on one fixed set falls much more smoothly (it ends at ). Single batch values jump even when training is healthy (P4.15).
Judge the trend, not the step
A batch is a small sample, so its loss is a noisy estimate (P1.F4). Averaging over a window shows the trend. In the noisy run a moving average over logged points goes from to , a clear decline that the raw line hides. Two habits help: judge the trend over many steps, and compare the loss on a fixed validation set, which has no batch noise.
The same shapes appear in one weight (P1.F3). Gradient descent on from starts at loss : creeps down to only after 60 steps (too low), converges, zig-zags and settles, and diverges.
Go deeper The validation score chosen by early stopping is slightly optimistic
Choosing the step with the lowest validation loss means you looked at the validation set to choose. The chosen score is then a little better than what fresh data gives. In the overfitting setup of Cell 2, averaged over 5 starting seeds, the loss on a fresh test set at the chosen step was higher than the best validation loss when the validation set had 50 examples, and higher with 500 examples. The effect is small here and grows when the validation set is small or many models are compared. That is why a separate test set is kept for the final number (P3.A4).
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running Cell 2 prints the start and end of each curve (healthy: training , validation ), the lowest validation loss of the overfitting run, the learning-rate sweep, the moving-average numbers, and then the shuffled-labels test and the early-stopping check. The curves in the gallery are these same numbers: the test suite checks that the widget’s data equals the output of this code.
The debugging checklist
When a run is bad, go down this list. Stop at the first item that explains the symptom, fix it, and change one thing at a time.
- Does it run on one batch? Overfit one batch (above). If not, look at the code, the learning rate and labels that change between steps, not at the model size.
- Is the data right? Look at examples and labels, the class counts, the shapes, the scaling. Check the first loss against .
- Is the loss the right one for the outputs? For example,
CrossEntropyLosswants raw scores and class indices (P4.6). - Are the modes right?
model.train()for training,model.eval()for validation (P4.19). - Is the learning rate sensible? Compare the curve with the low and high shapes above, and run a short sweep (P4.14).
- Are the gradients healthy? Total and per-layer norms (P4.16).
- Is the model the right size? Both curves high: bigger or longer. A wide gap: more data or regularization (P4.17, P4.18).
- Then tune. Only now compare batch sizes, optimizers and other hyperparameters (P4.13, P4.15, P4.23).
Common bugs and what they look like
- Forgot
zero_grad. Gradients add up across steps (P2.6, P2.7, P4.9). Each update uses the sum of all earlier gradients, so steps grow and the loss often becomes unstable or diverges, with no error message. - Softmax applied twice. If the network ends in a softmax and the loss is
CrossEntropyLoss, which applies softmax itself (P4.6), the loss gets probabilities as if they were scores. With 10 classes the loss cannot go below , even for perfect predictions. A loss that stalls well above where it should is the symptom. - Wrong label type or shape. By default
CrossEntropyLossexpects raw scores of shape and class indices of shape as integers (torch.long). One-hot targets only work as floats of shape . A mix-up raises an error or, worse, gives a wrong loss. An against mix-up in a regression loss silently broadcasts (P4.5). - Data not shuffled. If the data is sorted by class, each batch holds one class, and the batch loss jumps between batches.
- Statistics from the whole data set. A mean and a standard deviation computed before the split leak validation information into training (P3.A11).
- Eval mode forgotten. Dropout stays on and BatchNorm uses batch statistics while measuring (P4.17, P4.19).
- Images and labels shuffled separately. The pairs no longer match. The training loss can still fall, because the network memorizes the wrong pairs, but the validation loss stays at about or worse.
What to log
Log these for every run, at least once per few steps: the training loss, the validation loss (and the metric you care about, such as accuracy), the learning rate (P4.14) and the gradient norm (P4.16). Also keep the seed and the settings of the run, so that a good result can be repeated (P12.3). With only the loss you often cannot tell why a run failed. With the other three you usually can.
Depth: three ways to see it
Intuition
Training a network is like flying with a pilot’s checklist. A pilot does not wait until the plane is in the air to find out that a control does not work. They check each system on the ground, from the cheapest check to the most expensive, and a failed check is cheap to fix. Overfitting one batch is the engine test on the runway: if the engine cannot hold a small load, it will not hold a big one.
The analogy breaks where checklists are short and complete. A training checklist is never complete, because a network can be wrong in ways that no check was written for. Treat a passed check as evidence, not as proof.
Math
- Expected first loss. If the softmax gives equal probabilities, and .
- Majority baseline. With class frequencies , always predicting those frequencies gives the loss , the entropy of the labels (P1.E2). For it is nats.
- Gradient check. For a parameter and a small (for example ): . The error of this central difference is of order .
- Moving average of window over losses : . The noise of a batch loss shrinks by about if the batch losses are roughly independent.
- Softmax twice. With probabilities used as scores, the best case is , and the loss is . For this is .
Code
A PyTorch version of the routine (P2.7), on a tiny random data set so that it runs as it stands. Output from a local run with PyTorch 2.9.1:
import math
import torch
from torch import nn
torch.manual_seed(0)
X = torch.randn(16, 20) # ONE batch of 16 examples
y = torch.randint(0, 10, (16,)) # class indices (torch.long)
model = nn.Sequential(nn.Linear(20, 32), nn.ReLU(), nn.Linear(32, 10))
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
print("ln 10 =", round(math.log(10), 3))
print("first loss", round(loss_fn(model(X), y).item(), 3))
model.train()
for step in range(301): # overfit one batch
optimizer.zero_grad()
loss = loss_fn(model(X), y)
loss.backward()
gnorm = nn.utils.clip_grad_norm_(model.parameters(), max_norm=1e9)
optimizer.step() # (huge max_norm: only reports)
if step % 100 == 0:
print(step, round(loss.item(), 4), round(gnorm.item(), 3))
model.eval() # validation: eval mode, no grad
with torch.no_grad():
Xv, yv = torch.randn(200, 20), torch.randint(0, 10, (200,))
print("val loss", round(loss_fn(model(Xv), yv).item(), 2))ln 10 = 2.303
first loss 2.288
0 2.2877 0.785
100 0.0887 0.141
200 0.0237 0.046
300 0.0124 0.025
val loss 4.25The labels are random, so the network can only memorize them: the loss on the batch falls to about , while the validation loss on fresh random data is far above . The huge max_norm makes clip_grad_norm_ only report the gradient norm and clip nothing (P4.16).
A worked example: reading the three runs
Use the overfit table that Cell 1 prints, and suppose you only had its numbers.
- The first loss. and all three runs start at to . The starting point is fine, so the network and the loss function are not the first suspects.
- The “redrawn” run. It stays at ( at step 50, at step 300), while the “correct” run falls to by step 50. The model and the loss are the same, so the difference is the labels: they change at every step, and the network cannot find a rule that links inputs to them.
- The “flipped” run. It does not stall, it explodes ( at step 50). The rate is the same that works in the first run, so the sign of the update is the suspect.
Each conclusion came from comparing with the one run that works and from changing one thing at a time. That is the point of the one-batch test: it gives you a run that works to compare with.
Common mistakes
Quiz
Check your understanding
A classifier with 100 balanced classes prints a first-batch loss of before any update. What does that tell you?
With equal probabilities the loss is , and , so is what an untrained network should give. The learning rate has not acted yet, because no update has happened. Overfitting needs training first. A loss that is too low, not one above , is the sign of a leak.
You train on one batch of 16 examples with no regularization, and after 500 steps the loss is still for a 10-class problem. What is the most useful conclusion?
A working network memorizes 16 examples easily, so a loss stuck at means no useful signal reaches the weights: labels that change at every step, a bug in the update, or a rate far too small. A model with too many parameters memorizes more easily, not less. Training longer on more data hides the bug. No validation set is involved in this test.
The training loss falls steadily for 400 steps. The validation loss falls until step 35 and then climbs. What is the diagnosis and a first fix?
A widening gap with training loss still falling is the overfitting shape: the network memorizes the training set. A rate that is too low shows both lines almost flat. Underfitting shows both lines high together. Validation loss rising is the expected signature of overfitting, not a sign of a broken validation set.
A network with dropout and a clean training and validation split shows a training loss of and a validation loss of at the end. What is the most likely reason that the validation loss is lower?
The training loss is measured with units switched off, which makes the network worse, and the validation loss uses the full network. The split is stated to be clean, so training on validation examples is ruled out. A rate that is too high gives jumps, not a steady gap. The relation is not fixed: for an overfitting model the validation loss is higher.
The batch loss printed at each step jumps between and , but the loss on a fixed validation set falls steadily. What should you do?
A batch of a few examples gives a noisy estimate of the loss, so the batch loss jumps even when training works, and the fixed validation set removes that noise. Cutting the learning rate would slow a healthy run. Evaluation mode is for validation, and using it during training would switch off dropout. The validation set is what shows the trend.
Exercises
- A language model has a vocabulary of tokens. What loss should it have before training, and what does a first loss of suggest?
Show answer
. A first loss of is about times larger, which suggests starting weights that are too large or a loss used in the wrong way (see the rule of thumb above). - A data set has of its examples in one class. What accuracy and what cross-entropy loss does the baseline that predicts the frequencies get?
Show answer
Accuracy with the majority answer, and loss . A network must beat these before it has learned anything. - A 2-class network ends in a softmax, and its two output probabilities are given to
CrossEntropyLoss, which applies a softmax again. What is the lowest loss it can reach?Show answer
With probabilities used as scores, the loss is . It cannot go lower, so a loss that stalls there while accuracy is perfect points to this bug. - The batch losses of four steps are , , , . Compute the moving average with window .
Show answer
, and . The averages fall steadily even though the raw values go up and down. - Your run has a training loss and a validation loss that both stay at for 400 steps, on a two-class problem. Name two different things you would check first, in order.
Show answer
1. Overfit one batch: if the loss does not reach near , the code or labels are at fault. 2. If it does, raise the learning rate in a short sweep: a rate that is too low and an underfitting model both give flat curves at , and only the first improves with a bigger rate; if the sweep does not help, give the model more capacity.
Next: P4.23 searches over hyperparameters once this routine passes, and P4.24 explains why very large networks can still generalize. P5.7 applies the routine to a CNN on CIFAR-10, and P12.3 shows how to track many runs.