Neural-net foundations7 / 15

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.

EpochTraining lossValidation loss
270.3520.320 (the lowest)
4000.0121.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 λ\lambda 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?

on time late P = 0.5

Step 0 · epoch 0

Dropout p:
Weight decay λ:
00.20.40.60.8100.511.52epochloss
train –validation –

Press play. Each epoch is one step on all 80 deliveries.

The 2-64-64-2 network on 80 deliveries, 8 of them flipped on purpose (AdamW, learning rate 0.01, one step per epoch). Top: P(late) over the plane, with the 80 training deliveries. Bottom: training (solid) and validation (dashed) loss after each epoch.

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:

SettingBest val. loss (epoch)Final train lossFinal val. loss
no fixes0.320 (27)0.0121.394
dropout 0.20.289 (130)0.2230.455
dropout 0.50.244 (259)0.3160.265
decay 0.10.322 (27)0.0310.949
decay 10.322 (36)0.1490.442
early stop0.320 (27)stops at 470.320 (kept)

"Val." is validation; "decay" is the weight decay λ\lambda. 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 pp. 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.

3km20hour0.560.600.14000000.60.670.45inputhidden 1hidden 2output
+ weight− weightthicker = bigger

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.

p:
Dropout on a 2-6-6-2 network for one delivery. Each training step draws a new mask: switched-off units output 0 and their lines fade. The others are scaled up by 1/(1 − p). In evaluation mode every unit is on and nothing is scaled.

Things to notice:

  • Each step trains a different, thinned network. About 1 unit in 5 is off at p=0.2p = 0.2, and half of them at p=0.5p = 0.5, 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 pp (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 1/(1−p)1/(1-p) 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

  1. A layer outputs h=(2,4,1,3)\mathbf{h} = (2, 4, 1, 3). Their sum is 10.

In symbols: for each unit, draw r=0r = 0 with probability pp or r=1/(1−p)r = 1/(1-p) otherwise, and output r⋅hr \cdot h. Then

E[r⋅h]=p⋅0+(1−p)⋅h1−p=hE[r \cdot h] = p \cdot 0 + (1 - p) \cdot \frac{h}{1 - p} = h

Read it back: the dropped share pp contributes nothing, and the kept share 1−p1 - p 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 21282^{128} thinned networks, about 3×10383 \times 10^{38}. 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 21282^{128} 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:

The too-big network, with dropout
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:

nn.Dropout in training and evaluation 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 λ2∥w∥2\tfrac{\lambda}{2} \lVert \mathbf{w} \rVert^2 to the loss. Its gradient is λw\lambda \mathbf{w}, so plain gradient descent becomes

w←w−α(∇L+λw)=(1−αλ) w−α∇L\begin{aligned} \mathbf{w} &\leftarrow \mathbf{w} - \alpha \left( \nabla L + \lambda \mathbf{w} \right) \\ &= (1 - \alpha\lambda)\,\mathbf{w} - \alpha \nabla L \end{aligned}

The second line says it plainly. Each step, shrink the weights by the fraction αλ\alpha\lambda, then take the usual step. This shrinking is weight decay, and λ\lambda is the weight-decay rate. For plain SGD, L2 regularisation and weight decay are the same thing.

Worked example

One step of weight decay

  1. A weight is w=2w = 2, with α=0.01\alpha = 0.01 and λ=0.1\lambda = 0.1. The shrink factor is 1−αλ=1−0.001=0.9991 - \alpha\lambda = 1 - 0.001 = 0.999.

That arithmetic explains the table above. With α=0.01\alpha = 0.01, λ=0.1\lambda = 0.1 shrinks each weight by only 0.1% per step, which barely touches the fit in 400 steps. λ=1\lambda = 1 shrinks by 1% per step, which is enough to hold the network back.

Adam breaks the equivalence: AdamW

With Adam, adding λw\lambda \mathbf{w} to the gradient doesn't give an even shrink. Adam divides each weight's gradient by that gradient's typical size. The λw\lambda w 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:

w←(1−αλ) ww←w−α m^v^+ϵ\begin{aligned} w &\leftarrow (1 - \alpha\lambda)\, w \\ w &\leftarrow w - \alpha \, \frac{\hat m}{\sqrt{\hat v} + \epsilon} \end{aligned}

Here m^\hat m and v^\hat v 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 aa's gradient is ±10\pm 10 and weight bb's is ±0.1\pm 0.1. Both start at 1, with α=0.01\alpha = 0.01.

05010015020025030000.20.40.60.81stepweight
Adam + L2, a (big gradients)Adam + L2, b (small gradients)AdamW, a (big gradients)AdamW, b (small gradients)
after 300 stepsab
Adam + L20.9530.0643
AdamW0.7280.728
Weight decay λ:
Two weights, a (gradient ±10) and b (gradient ±0.1), both starting at 1. Adam + L2 adds λ·w to the gradient; AdamW shrinks the weight directly. Learning rate 0.01.

Things to notice, at λ=0.1\lambda = 0.1:

  • AdamW shrinks aa and bb together. Both end at 0.728 after 300 steps. That's close to 0.999300≈0.740.999^{300} \approx 0.74; the flip-flopping Adam steps almost cancel.
  • Adam + L2 barely touches aa. 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 bb. 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 α\alpha and λ\lambda 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 default weight_decay is 0.01, which is what the template uses. The PyTorch docs write the decay step as θ←θ−γλθ\theta \leftarrow \theta - \gamma\lambda\theta, with γ\gamma the learning rate.
  • torch.optim.Adam(params, weight_decay=0.01) is L2: it adds λθ\lambda\theta 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 λθ\lambda\theta 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:

No decay on biases and normalisation parameters
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

  1. 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:

fit, plus early stopping
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_epoch

The 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 p=0.5p = 0.5, weight decay λ=1\lambda = 1 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:

  1. 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.
  2. If validation loss still climbs well above its best, add dropout, 0.1 to 0.5 after the hidden layers, and try a larger λ\lambda.
  3. Compare settings by their best validation loss, and keep the validation set out of training.
  4. 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 1/(1−p)1/(1-p) 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 λw\lambda w to the gradient, and its scaling then weakens the decay on weights with large gradients. AdamW shrinks every weight by the same fraction αλ\alpha\lambda.

"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 pp during training, and scales the survivors by 1/(1−p)1/(1-p). Each step trains a different thinned network; evaluation uses them all.
  • Weight decay shrinks every weight by the fraction αλ\alpha\lambda 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 patience epochs 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) with model.train() and model.eval(); torch.optim.AdamW(weight_decay=…), torch.optim.Adam(weight_decay=…) and parameter groups; copy.deepcopy of a state_dict().