Lesson 7 · Building networks
Keeping networks general
The problem
Give a big network a small, noisy dataset, and it will learn the noise.
Take only the first 80 rush-hour deliveries, and flip 8 of their labels on purpose. With the few that were already wrong, about 1 in 7 is now wrong. Then train a network far bigger than the job needs: 2-64-64-2, with 4,482 weights for 80 deliveries. Validation still uses the usual 200 deliveries.
| Epoch | Training loss | Validation loss |
|---|---|---|
| 27 | 0.352 | 0.320 (the lowest) |
| 400 | 0.012 | 1.394 |
By epoch 400 the network gets every training delivery right, including the wrong labels. On new deliveries its loss is more than four times what it was at epoch 27. This is overfitting: the network has memorised its training data instead of learning the rule.
ML fundamentals calls any way of holding a model back from this regularisation. This lesson covers the three that networks use most: dropout, weight decay and early stopping.
See it: overfit, then fix it
The training loop is the Lesson 4 template with these changes:
- the data is the 80 noisy deliveries, all in one batch, so one step is one epoch;
- the network is 2-64-64-2, with an optional dropout layer after each hidden ReLU;
- AdamW's weight decay is a setting (the template uses PyTorch's default, 0.01);
- an optional early-stopping rule, explained below.
Press play with every fix off. Then switch them on one at a time.
Predict first
You turn on dropout with p = 0.5. What happens to the training loss, and to the validation loss?
Step 0 · epoch 0
Press play. Each epoch is one step on all 80 deliveries.
Things to notice:
- With no fixes, the boundary grows small islands around single deliveries, often the flipped ones. Validation loss bottoms out near epoch 27, then climbs for the rest of the run.
- Dropout 0.5 keeps the boundary smooth. Training loss stays well above 0, and the lowest validation loss is the best of any setting.
- Weight decay 1 slows the climb, so the last epoch is far better than with no fixes. At this size it hardly changes the lowest point.
- Early stopping ends the run about 20 epochs after the lowest point, and goes back to those weights.
The PyTorch run gives the same picture:
| Setting | Best val. loss (epoch) | Final train loss | Final val. loss |
|---|---|---|---|
| no fixes | 0.320 (27) | 0.012 | 1.394 |
| dropout 0.2 | 0.289 (130) | 0.223 | 0.455 |
| dropout 0.5 | 0.244 (259) | 0.316 | 0.265 |
| decay 0.1 | 0.322 (27) | 0.031 | 0.949 |
| decay 1 | 0.322 (36) | 0.149 | 0.442 |
| early stop | 0.320 (27) | stops at 47 | 0.320 (kept) |
"Val." is validation; "decay" is the weight decay . Every fix pays for itself the same way: a worse training loss for a better validation loss. Your browser draws different dropout masks from PyTorch, so its dropout numbers differ a little. Without dropout, the two follow almost the same path; small rounding differences add up over 400 epochs. While it plays, the figure checks validation every other epoch to keep up, so its best epoch can be one off.
Dropout: switch off random units while training
Overfitting often means a few units have teamed up to handle a few odd training examples. Dropout breaks up such teams. At every training step, it switches off each hidden unit at random, with probability . A unit can't rely on any particular partner being there, so each unit has to be useful on its own.
Step through it on a small 2-6-6-2 network, trained with dropout 0.2, for one delivery: 3 km, sent at 19:30. That trip is late, and the network says so with P(late) about 0.8.
Training step 1: P(late) = 0.78
Switched off: hidden 1 none; hidden 2 units 1. Each surviving output is multiplied by 1/(1 − 0.2) = 1.3.
Average P(late) over 1 training step: 0.78. Evaluation mode gives 0.81.
Things to notice:
- Each step trains a different, thinned network. About 1 unit in 5 is off at , and half of them at , a different set each time.
- The answer jumps from step to step. The same delivery gets a different P(late) depending on which units survived.
- The average over many training steps comes out close to the evaluation-mode answer, though not exactly. Press "New training step" twenty times and compare.
This is dropout. The number (the dropout rate) is the chance that each unit is switched off. In evaluation mode, dropout does nothing.
Why scale the survivors up?
If half the units are switched off, the next layer gets about half its usual input. In evaluation mode, every unit is on, so it would suddenly get twice as much. The fix is to scale the surviving outputs up by while training. Then each unit's output is right on average, and evaluation needs no change at all.
Worked example
Dropout on four outputs, p = 0.5
A layer outputs . Their sum is 10.
In symbols: for each unit, draw with probability or otherwise, and output . Then
Read it back: the dropped share contributes nothing, and the kept share is scaled up by exactly enough to make up for it.
DeeperWhy dropout works like averaging many networksEach mask picks out one thinned network. Evaluation mode is a cheap stand-in for averaging all of them. · 3 min
The 2-64-64-2 network has 128 hidden units. Each can be on or off, so there are thinned networks, about . Each training step trains one of them, chosen at random. They all share the same weights, so training one nudges the others too.
An ensemble averages the predictions of many models, and usually beats any one of them, because their mistakes partly cancel. Dropout gives you a huge ensemble for the price of one network. Averaging networks exactly is impossible. Evaluation mode, with every unit on and nothing scaled, is a cheap approximation of that average. The figure above lets you check how close it is for one delivery: average twenty training steps and compare.
The approximation is exact for a single linear layer. With ReLUs in between, it isn't exact, but it works well in practice. This view comes from the paper that introduced dropout (Hinton and others, 2012, then Srivastava and others, Journal of Machine Learning Research, 2014).
In PyTorch: nn.Dropout
nn.Dropout(p) is a layer. Put it after each hidden activation, and never after the output layer, which gives the logits:
def make_big_mlp(p: float = 0.0, hidden: int = HIDDEN) -> nn.Sequential:
"""2 → hidden → hidden → 2, with dropout after each hidden ReLU. 4,482 weights for 80 deliveries."""
return nn.Sequential(
nn.Linear(2, hidden),
nn.ReLU(),
nn.Dropout(p), # zeroes each output with probability p, in training mode only
nn.Linear(hidden, hidden),
nn.ReLU(),
nn.Dropout(p),
nn.Linear(hidden, 2), # logits: no dropout on the output
)Dropout is one of the layers that model.train() and model.eval() switch. Here is one nn.Dropout(0.5) on eight 1s, in each mode:
def dropout_modes() -> tuple[list[float], list[float]]:
"""nn.Dropout(0.5) on eight 1s, in training mode and in evaluation mode."""
torch.manual_seed(0)
drop = nn.Dropout(p=0.5)
x = torch.ones(8)
drop.train()
trained = drop(x) # each entry is 0 (dropped) or 1 / (1 - 0.5) = 2 (kept, scaled up)
drop.eval()
evaluated = drop(x) # evaluation mode: does nothing
return trained.tolist(), evaluated.tolist()dropout in train and eval mode: [0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 2.0, 2.0] [1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]In training mode, each entry is 0 or 2. Five of the eight were dropped this time; on average it would be four. In evaluation mode, the layer passes its input through unchanged. The template's evaluate calls model.eval(), so validation always sees the full network.
Weight decay: shrink every weight a little
A network that wraps a boundary around single deliveries needs some large weights to make the sharp bends. Weight decay pulls every weight a little way towards zero at each step. Weights the data needs get pushed back up by their gradients. Weights that only fit noise fade away.
ML fundamentals did this with L2 regularisation: add a penalty to the loss. Its gradient is , so plain gradient descent becomes
The second line says it plainly. Each step, shrink the weights by the fraction , then take the usual step. This shrinking is weight decay, and is the weight-decay rate. For plain SGD, L2 regularisation and weight decay are the same thing.
Worked example
One step of weight decay
A weight is , with and . The shrink factor is .
That arithmetic explains the table above. With , shrinks each weight by only 0.1% per step, which barely touches the fit in 400 steps. shrinks by 1% per step, which is enough to hold the network back.
Adam breaks the equivalence: AdamW
With Adam, adding to the gradient doesn't give an even shrink. Adam divides each weight's gradient by that gradient's typical size. The term gets divided too. So a weight with large gradients gets its decay divided by a large number, and barely shrinks. A weight with small gradients gets its decay divided by a small number, and shrinks a lot.
Loshchilov and Hutter pointed this out (Decoupled Weight Decay Regularization, ICLR 2019). Their fix takes the decay out of the gradient and applies it to the weight directly, before the Adam step:
Here and are Adam's running averages from Lesson 5, built from the data's gradient only. This is AdamW, the optimiser every network in this course has used.
Watch the difference on two weights the data has no use for. Their gradients flip sign every step, so on average the data pushes them nowhere. Weight 's gradient is and weight 's is . Both start at 1, with .
| after 300 steps | a | b |
|---|---|---|
| Adam + L2 | 0.953 | 0.0643 |
| AdamW | 0.728 | 0.728 |
Things to notice, at :
- AdamW shrinks and together. Both end at 0.728 after 300 steps. That's close to ; the flip-flopping Adam steps almost cancel.
- Adam + L2 barely touches . It ends at 0.953. Its decay term, 0.1, is tiny next to its gradient of 10, and Adam divides both by about 10.
- Adam + L2 crushes . It ends at 0.064. Its decay term, 0.1, is as big as its gradient, so it takes over the step.
So with Adam + L2, how much a weight decays depends on the size of its gradients. That has nothing to do with whether the weight is needed. AdamW decays every weight by the same fraction. In Loshchilov and Hutter's image-classification experiments, the decoupled version generalised better. Good values of and also depended less on each other.
Predict first
Which optimiser shrinks every weight by the same fraction at each step, whatever the size of its gradient?
In PyTorch
torch.optim.AdamW(params, lr=0.01, weight_decay=0.01)is decoupled weight decay. Its defaultweight_decayis 0.01, which is what the template uses. The PyTorch docs write the decay step as , with the learning rate.torch.optim.Adam(params, weight_decay=0.01)is L2: it adds to the gradient. Its default is 0. In torch 2.15,Adam(..., decoupled_weight_decay=True)behaves as AdamW.torch.optim.SGD(params, weight_decay=0.01)adds to the gradient, which for SGD is the same as decay (with momentum, the decay term also passes through the velocity).
A common practice is to decay only the weight matrices, not the biases or the scale and shift of normalisation layers. Those are few, and shrinking them doesn't make the function smoother. This is a rule of thumb, not a law. Parameter groups give each set its own settings:
def adamw_no_decay_on_biases(model: nn.Module, lr: float, weight_decay: float) -> torch.optim.AdamW:
"""AdamW that decays weight matrices but not biases or normalisation parameters (all 1-D)."""
decay = [p for p in model.parameters() if p.ndim >= 2]
no_decay = [p for p in model.parameters() if p.ndim < 2]
return torch.optim.AdamW(
[{"params": decay, "weight_decay": weight_decay}, {"params": no_decay, "weight_decay": 0.0}],
lr=lr,
)Early stopping: stop at the lowest point
The first figure's validation loss falls, bottoms out, then climbs. The simplest fix is to stop near the bottom. The template's fit already keeps the weights from the epoch with the lowest validation loss; Lesson 4 called that half of early stopping. The other half is to stop the run, instead of training on for hundreds of epochs you'll throw away.
But you can't know you've passed the lowest point until the loss has climbed for a while: a single bad epoch might be noise. So wait. Count the epochs since the last new best, and stop when the count reaches a limit, called the patience.
Worked example
Patience 20 on the no-fixes run
The validation loss reaches a new low, 0.320, at epoch 27. The count resets to 0, and the weights are copied.
Early stopping limits how far the weights can travel from their small starting values, so it acts a little like weight decay. It costs nothing, and it needs no new hyperparameter except the patience. Its weakness is that it needs an honest validation loss. The validation data must never be trained on (see train, validation and test sets).
Here is the template's fit with the patience counter added. Everything else is unchanged:
def fit_early_stopping(
model: nn.Module,
train_loader: DataLoader,
val_loader: DataLoader,
*,
epochs: int = EPOCHS,
lr: float = 0.01,
weight_decay: float = 0.0,
patience: int | None = PATIENCE,
device: torch.device | None = None,
) -> tuple[list[dict], int]:
"""The template's fit, plus early stopping: stop once `patience` epochs pass with no new best
validation loss (None: never stop). Ends with the best weights. Returns the history and the
best epoch."""
device = device or get_device()
model.to(device)
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=weight_decay)
history: list[dict] = []
best_val_loss, best_state, best_epoch, waited = float("inf"), None, 0, 0
for epoch in range(1, epochs + 1):
train_loss, train_acc = train_one_epoch(model, train_loader, loss_fn, optimizer, device)
val_loss, val_acc = evaluate(model, val_loader, loss_fn, device)
history.append(
{"epoch": epoch, "train_loss": train_loss, "train_acc": train_acc, "val_loss": val_loss, "val_acc": val_acc}
)
if val_loss < best_val_loss:
best_val_loss, best_state, best_epoch, waited = val_loss, copy.deepcopy(model.state_dict()), epoch, 0
else:
waited += 1 # one more epoch with no new best
if patience is not None and waited >= patience:
break # stop early
model.load_state_dict(best_state)
return history, best_epochThe copy uses copy.deepcopy(model.state_dict()), as in the template. A state_dict() shares memory with the live weights, so without the copy the "best" weights would keep changing.
DigressionData augmentation: making more data from the data you haveThe best regulariser is more data. Sometimes you can make it, by changing examples in ways that don't change their label. · 2 min
Every method in this lesson holds the network back. Another option is to give it more to learn from. A photo of a pizza is still a photo of a pizza when it's flipped, rotated a little, cropped or made slightly darker. Data augmentation applies changes like these at random each time an example is used, so the network never sees exactly the same image twice.
The changes must keep the label true. Flipping a photo of a cat is fine; flipping a photo of the digit 6 upside down makes it a 9. For the rush-hour deliveries, there's no obvious change that keeps "late" true, which is why this lesson doesn't use it. Images are where augmentation matters most; the Convolutional networks course uses it.
DigressionDouble descent: when bigger keeps getting betterThe textbook picture says too big a model overfits. Very large networks sometimes don't follow it. This is still being worked out. · 2 min
The usual picture from ML fundamentals is the bias–variance trade-off. As a model grows, validation error first falls, then rises as it starts to overfit. So pick a model in the middle.
Large networks don't always behave that way. Belkin and others (PNAS, 2019) described a double descent. Validation error peaks when the model is barely big enough to fit the training data exactly. Then it falls again as the model keeps growing. Nakkiran and others (ICLR 2020) saw the same shape in deep networks, as model size or training time grows.
Why this happens is an active research question, and it doesn't always happen. It doesn't mean regularisation is useless. Large models in practice are still trained with weight decay, data augmentation and early stopping. It does mean "my network has more weights than examples" isn't enough on its own to say it will overfit.
Putting it together
Back to the 80 noisy deliveries, with everything switched on: dropout , weight decay and patience 20. In PyTorch, the run stops at epoch 87 and keeps epoch 67, with a validation loss of 0.302 and 89.5% accuracy. The no-fixes network ended at 1.394.
That's not the best single number in the table: dropout alone, run for all 400 epochs, reached 0.244. Fixes interact, and too much regularisation underfits. The working recipe:
- Start with early stopping and AdamW's default decay. They're nearly free. The template already keeps the best weights, and the stop is a few more lines.
- If validation loss still climbs well above its best, add dropout, 0.1 to 0.5 after the hidden layers, and try a larger .
- Compare settings by their best validation loss, and keep the validation set out of training.
- If training loss can't get low any more, you've regularised too much. Back off.
These are rules of thumb. Lesson 13, on debugging, shows how to tell "regularised too much" from other ways training goes wrong.
Common misconceptions
"Dropout is on at test time too." It acts only in training mode. In evaluation mode, nn.Dropout passes its input through unchanged. That's why model.eval() matters before validation.
"Dropout makes the outputs smaller, so evaluation needs rescaling." PyTorch scales the survivors up by during training. So each output is right on average, and evaluation needs no change.
"Validation loss below training loss means a bug." With dropout on, training loss comes from a handicapped network. So it often sits above validation loss.
"Adam's weight_decay and AdamW's are the same." Adam adds to the gradient, and its scaling then weakens the decay on weights with large gradients. AdamW shrinks every weight by the same fraction .
"Early stopping means stopping at the lowest validation loss." You can't know an epoch is the lowest until later. You keep a copy of the best weights, wait out the patience, then load the copy.
Recap
- Overfitting shows as training loss falling while validation loss rises. A big network on little, noisy data will do it.
- Dropout switches off each hidden unit with probability during training, and scales the survivors by . Each step trains a different thinned network; evaluation uses them all.
- Weight decay shrinks every weight by the fraction each step. For SGD it equals L2 regularisation. For Adam it doesn't, which is why AdamW applies the decay to the weights directly.
- Early stopping keeps the best weights and stops after
patienceepochs with no new best validation loss. - Every fix trades a higher training loss for a lower validation loss. Too much of them underfits.
- PyTorch names in this lesson:
nn.Dropout(p)withmodel.train()andmodel.eval();torch.optim.AdamW(weight_decay=…),torch.optim.Adam(weight_decay=…)and parameter groups;copy.deepcopyof astate_dict().