Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

The training recipe and debugging

P4.2240 min●●○ IntermediateReviewed Dec 3, 2026

Why this matters for machine learning

A network that is broken usually does not crash: it trains, prints a loss and gives poor results. A fixed routine of cheap checks, run in order, finds most problems in minutes instead of after a day of training.

  • Training a CNN on CIFAR-10 in PyTorch is the first full run where you apply this routine to real images. (P5.7: Build a CNN)
  • Searching over learning rates and other hyperparameters only makes sense once the training code passes these checks. (P4.23: Hyperparameter tuning)
  • Large language model pretraining is monitored through its loss curve, and spikes and plateaus are read exactly as in this lesson. (P10.B2: The pretraining objective and loss curves, coming soon)
  • Logging the loss, the learning rate and the gradient norm of every run is the basis of experiment tracking. (P12.3: Experiment tracking and reproducibility, coming soon)

Before this: The PyTorch training loop, Train, validation and test sets, Optimizers, Vanishing and exploding gradients, Regularization for neural nets

After this lesson you can

  • Compute the loss a network should have before training (ln K for K balanced classes) and compare it with the first batch
  • Overfit one small batch as a test of the whole training code, and say what each way of failing points to
  • Read training and validation loss curves, and name the likely cause and the first fix for eight common shapes
  • Run a set of cheap sanity checks (gradient check, gradient norms, dead units, train and eval mode, shuffled labels) and a debugging checklist in order

Here is the same small network, trained on the same 16 examples, three times. In the first run the loss falls from 2.352.35 to 0.0040.004. 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 2.32.3. In the third, one sign in the update is wrong, and the loss reaches 107310^{73}. 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 ln⁡K\ln K, (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 00 to 255255 where the code expects 00 to 11, 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 90%90\% of the examples belong to one class. Then that trivial answer has accuracy 0.900.90 and a cross-entropy loss of −(0.9ln⁡0.9+0.1ln⁡0.1)=0.325-(0.9\ln0.9+0.1\ln0.1)=0.325 if it predicts those probabilities. A network with 91%91\% 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 1/K1/K for its true class, and the cross-entropy loss (P4.6) is

−ln⁡1K=ln⁡K.-\ln\frac1K=\ln K .

For K=2K=2 this is ln⁡2=0.693\ln 2=0.693, for K=10K=10 it is ln⁡10=2.303\ln10=2.303, for K=1000K=1000 it is ln⁡1000=6.908\ln1000=6.908, and for a language model with a vocabulary of 50,00050{,}000 tokens it is ln⁡50000=10.82\ln50000=10.82. 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 0.10.1: first loss 2.352.35, close to ln⁡10\ln10;
  • last layer at the usual scale (the scale of P4.12): 3.783.78;
  • last layer 1010 times larger: 30.2030.20, which is 1313 times ln⁡10\ln 10.

A first loss near ln⁡K\ln K is a good sign. A moderately higher one, such as 3.783.78 here, is common and not a bug: the initial outputs are not exactly equal. A loss far above ln⁡K\ln K 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 ln⁡K\ln K 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 00 and the predictions should match the labels. In Cell 1 the loss goes 2.35→0.037→0.015→0.0042.35\to0.037\to0.015\to0.004 at steps 00, 5050, 100100 and 300300.

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 ln⁡K\ln K (the “redrawn” column: labels re-drawn at every step, so there is nothing to learn: 2.342.34, 2.202.20, 2.312.31, 2.302.30). 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: 9×10119\times10^{11} 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 00. 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.

Try it: the first loss, three checks, and overfitting one batch

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 (2.352.35, 3.783.78, 30.2030.20), 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 (−0.00811-0.00811 and 0.041490.04149). And the gradient norms of the two weight matrices are 0.17180.1718 and 2.59462.5946, which is a ratio of about 1515: 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 3232 hidden units is inactive on every example of the batch (00 of 3232).

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, (L(w+h)−L(w−h))/2h\bigl(L(w+h)-L(w-h)\bigr)/2h (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 nan or inf needs attention at once.
  • Dead ReLUs. A hidden unit whose input is negative for every example outputs 00 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 and model.eval() before measuring the validation loss. Forgetting eval() gives noisy, worse validation numbers.
  • Shapes and broadcasting. Print the shape of every tensor once (P4.5). A prediction of shape (N,1)(N,1) minus a target of shape (N,)(N,) broadcasts to an (N,N)(N,N) 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 0.180.18. With labels shuffled once the training loss still falls to 0.260.26 (the network memorizes the wrong labels) but the validation loss never gets clearly below chance: its best value is 0.670.67, against ln⁡2=0.693\ln2=0.693, and it ends at 1.191.19. 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 ln⁡2\ln 2, the loss of a model that says 50/50. Try to name each curve first, then tap it to see what it says.

training loss validation loss 0.69 = ln 2, a model that says 50/50

Look at each curve first, then tap it: What does this curve say?

Eight loss curves from real training runs (400 steps each). Explore: tap a chart to open its diagnosis, the usual fix and the lesson that explains it. Quiz me: the curves are shuffled and you pick the diagnosis from four options (6 of 8 right means you can read the common shapes). Solid blue is training loss, dashed pink is validation loss, dotted grey is ln 2.

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 20%20\% of the labels flipped.

  • Healthy. Both losses fall from 0.700.70 to 0.070.07 (training) and 0.120.12 (validation). They stay close, and the validation line sits a little above the training line.
  • Learning rate too low. The same network with η=0.003\eta=0.003 goes from 0.700.70 to only 0.680.68 in 400 steps, in a nearly straight line. A short sweep of the rate finds the fix. Final validation loss was 0.6780.678 at η=0.003\eta=0.003, 0.6010.601 at 0.030.03 and 0.1240.124 at 0.30.3 (P4.14).
  • Learning rate too high. At η=10\eta=10 the losses spike to 5.55.5 (training) and 5.95.9 (validation), partly recover and spike again; the validation loss ends at 1.141.14 (η=3\eta=3 trains fine, with a final validation loss of 0.1410.141). 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, 20%20\% wrong labels. The training loss falls to 0.210.21 while the validation loss reaches its lowest value, 0.6020.602, at step 3535 and then climbs to 0.850.85. 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 0.690.69 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 0.690.69 for about 75 steps, is below 0.650.65 at step 120120, and reaches 0.100.10 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 0.50.5, the training loss ends at 0.480.48 and the validation loss at 0.360.36. 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 1.111.11) while the validation loss on one fixed set falls much more smoothly (it ends at 0.360.36). 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 1010 logged points goes from 0.7230.723 to 0.2650.265, 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 f(x)=x2f(x)=x^2 from x=3x=3 starts at loss 99: η=0.02\eta=0.02 creeps down to only 0.0670.067 after 60 steps (too low), η=0.1\eta=0.1 converges, η=0.6\eta=0.6 zig-zags and settles, and η=1.05\eta=1.05 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 0.0330.033 higher than the best validation loss when the validation set had 50 examples, and 0.0010.001 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).

Try it: the eight curves, a sweep, shuffled labels, early stopping

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 0.70→0.070.70\to0.07, validation 0.69→0.120.69\to0.12), 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.

  1. 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.
  2. Is the data right? Look at examples and labels, the class counts, the shapes, the scaling. Check the first loss against ln⁡K\ln K.
  3. Is the loss the right one for the outputs? For example, CrossEntropyLoss wants raw scores and class indices (P4.6).
  4. Are the modes right? model.train() for training, model.eval() for validation (P4.19).
  5. Is the learning rate sensible? Compare the curve with the low and high shapes above, and run a short sweep (P4.14).
  6. Are the gradients healthy? Total and per-layer norms (P4.16).
  7. Is the model the right size? Both curves high: bigger or longer. A wide gap: more data or regularization (P4.17, P4.18).
  8. 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 −1+ln⁡(e+9)=1.461-1+\ln(\mathrm{e}+9)=1.461, even for perfect predictions. A loss that stalls well above where it should is the symptom.
  • Wrong label type or shape. By default CrossEntropyLoss expects raw scores of shape (N,K)(N,K) and class indices of shape (N,)(N,) as integers (torch.long). One-hot targets only work as floats of shape (N,K)(N,K). A mix-up raises an error or, worse, gives a wrong loss. An (N,1)(N,1) against (N,)(N,) 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 ln⁡K\ln K 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, py=1/Kp_y=1/K and L=−ln⁡py=ln⁡KL=-\ln p_y=\ln K.
  • Majority baseline. With class frequencies πk\pi_k, always predicting those frequencies gives the loss −∑kπkln⁡πk-\sum_k\pi_k\ln\pi_k, the entropy of the labels (P1.E2). For π=(0.9,0.1)\pi=(0.9,0.1) it is 0.3250.325 nats.
  • Gradient check. For a parameter ww and a small hh (for example 10−510^{-5}): ∂L∂w≈L(w+h)−L(w−h)2h\dfrac{\partial L}{\partial w}\approx\dfrac{L(w+h)-L(w-h)}{2h}. The error of this central difference is of order h2h^2.
  • Moving average of window mm over losses ℓ1,ℓ2,…\ell_1,\ell_2,\dots: ℓˉt=1m∑j=0m−1ℓt−j\bar\ell_t=\frac1m\sum_{j=0}^{m-1}\ell_{t-j}. The noise of a batch loss shrinks by about 1/m1/\sqrt m if the batch losses are roughly independent.
  • Softmax twice. With probabilities p\mathbf{p} used as scores, the best case is p=(1,0,…,0)\mathbf{p}=(1,0,\dots,0), and the loss is −1+ln⁡(e+K−1)-1+\ln(\mathrm{e}+K-1). For K=10K=10 this is 1.4611.461.

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.25

The labels are random, so the network can only memorize them: the loss on the batch falls to about 0.010.01, while the validation loss on fresh random data is far above ln⁡10\ln10. 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.

  1. The first loss. ln⁡10=2.303\ln10=2.303 and all three runs start at 2.342.34 to 2.352.35. The starting point is fine, so the network and the loss function are not the first suspects.
  2. The “redrawn” run. It stays at ln⁡10\ln10 (2.202.20 at step 50, 2.302.30 at step 300), while the “correct” run falls to 0.03670.0367 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.
  3. The “flipped” run. It does not stall, it explodes (9.18×10119.18\times10^{11} at step 50). The rate is the same 0.10.1 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

  1. A classifier with 100 balanced classes prints a first-batch loss of 4.614.61 before any update. What does that tell you?

  2. You train on one batch of 16 examples with no regularization, and after 500 steps the loss is still 2.302.30 for a 10-class problem. What is the most useful conclusion?

  3. 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?

  4. A network with dropout 0.50.5 and a clean training and validation split shows a training loss of 0.480.48 and a validation loss of 0.360.36 at the end. What is the most likely reason that the validation loss is lower?

  5. The batch loss printed at each step jumps between 0.20.2 and 1.21.2, but the loss on a fixed validation set falls steadily. What should you do?

Exercises

  1. A language model has a vocabulary of 50,00050{,}000 tokens. What loss should it have before training, and what does a first loss of 108108 suggest?
    Show answerln⁡50000=10.82\ln50000=10.82. A first loss of 108108 is about 1010 times larger, which suggests starting weights that are too large or a loss used in the wrong way (see the rule of thumb above).
  2. A data set has 95%95\% of its examples in one class. What accuracy and what cross-entropy loss does the baseline that predicts the frequencies (0.95,0.05)(0.95,0.05) get?
    Show answerAccuracy 0.950.95 with the majority answer, and loss −(0.95ln⁡0.95+0.05ln⁡0.05)=0.0487+0.1498=0.199-(0.95\ln0.95+0.05\ln0.05)=0.0487+0.1498=0.199. A network must beat these before it has learned anything.
  3. 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 answerWith probabilities (1,0)(1,0) used as scores, the loss is −1+ln⁡(e+1)=0.313-1+\ln(\mathrm{e}+1)=0.313. It cannot go lower, so a loss that stalls there while accuracy is perfect points to this bug.
  4. The batch losses of four steps are 0.90.9, 0.50.5, 0.80.8, 0.40.4. Compute the moving average with window 22.
    Show answer(0.9+0.5)/2=0.7(0.9+0.5)/2=0.7, (0.5+0.8)/2=0.65(0.5+0.8)/2=0.65 and (0.8+0.4)/2=0.6(0.8+0.4)/2=0.6. The averages fall steadily even though the raw values go up and down.
  5. Your run has a training loss and a validation loss that both stay at 0.690.69 for 400 steps, on a two-class problem. Name two different things you would check first, in order.
    Show answer1. Overfit one batch: if the loss does not reach near 00, 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 0.690.69, 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.

Key takeaways

  • Before training, look at the data, set a seed, get a simple baseline, and check that the loss of the first batch is about ln⁡K\ln K for KK balanced classes. A first loss about 10 times larger often points to starting weights that are too big (a rule of thumb).
  • Overfit one small batch. A correct pipeline drives its loss close to 0. If it does not, look for a bug in the code, the learning rate or labels that change between steps before trying anything else.
  • Training and validation loss against steps show the problem: both high is underfitting, training down and validation up is overfitting, wild jumps mean a learning rate that is too high, a flat line a rate that is too low.
  • Not every odd curve is a bug: a noisy batch loss, a plateau at the start and a validation loss below the training loss (dropout is on only in training) all have ordinary causes.
  • Debug from cheap to expensive, change one thing at a time, and log the loss, the validation metric, the learning rate and the gradient norm.
Found a mistake? Tell us