Lecture 6

Neural networks 2

Introduction to Machine Learning
KU Leuven, campuses Diepenbeek and Geel
Academic year 2026–2027

Where lecture 5 stopped

Minibatch SGD trains the networks of lecture 5, but:

  • in a long valley the steps zigzag,
  • one rate serves gradients of very different sizes,
  • the noisy steps never settle,
  • a wide network memorises its training data,
  • a deep network may not train at all.

Today

Better steps, limits on memorising, a cure for depth, and the whole training loop in PyTorch.

What that looks like

Two panels. Left, the training loss of the bearing network under the minibatch SGD of lecture 5, which falls in the first epoch and then jumps up and down for nineteen more. Right, the training and test error of a wide network on twenty turbine measurements: the training error falls towards zero while the test error reaches a minimum near epoch 1000 and then rises.
Left: the 2-16-1 bearing network, \(\eta = 1\). The loss falls to 0.16 in one epoch and then jumps between 0.13 and 0.17 for nineteen more. Right: a wide network on twenty turbine measurements. Training error 9.5 kW, test error 205 kW.

Today in three choices

Model

composed nonlinear layers

unchanged since lecture 5

Loss

cross-entropy, squared error, plus a penalty

the penalty of lecture 2

Optimiser

momentum, Adam

with a schedule for the learning rate

The plan

  1. Optimisers and schedules
  2. Regularising networks
  3. PyTorch

Exercise 3 uses all three: Adam, weight decay and dropout, in PyTorch.

Block 1

Optimisers and schedules

One rate, three problems

\(\eta\) is shared bythe problemthe cure
every directioncurvature 172 times larger across the valley than along itmomentum
every weightgradients spanning a factor of 1,382Adam
every stepa step that suits the start is too large near the minimuma schedule

Each cure keeps the gradient of backpropagation and changes only the step taken with it. The 172 and the 1,382 are measured on the slides that follow.

A long valley

Contours of the toy loss of lecture 1, a long narrow valley, with the path of 100 steps of gradient descent. The path zigzags across the valley in its first steps, then creeps along the valley floor and is still far from the minimum after 100 steps.
The toy loss of lecture 1, gradient descent with \(\eta = 0.024\), nine tenths of the largest rate that does not diverge. The steps zigzag across the valley and crawl along it: 612 steps to the minimum.

Each step multiplies the error by \(1 - \eta\lambda\)

\[ \loss(w) = \tfrac{1}{2} \lambda \, e^2, \quad e = w - w^\star \qquad \Longrightarrow \qquad \frac{\partial \loss}{\partial w} = \lambda e \]
\[ e \leftarrow e - \eta \lambda e = (1 - \eta \lambda) \, e \]
\[ \eta\lambda = 0.5 \to \times 0.5, \qquad \eta\lambda = 1.5 \to \times (-0.5), \qquad \eta\lambda = 2.5 \to \times (-1.5) \]

Near its minimum a smooth loss is a parabola like this one. \(\lambda\), its second derivative, is the curvature. A small \(\eta\) shrinks the error, a larger one flips its sign as well, and \(\eta\lambda > 2\) makes it grow.

Why it zigzags

\[ \text{each direction } i \text{ of curvature } \lambda_i: \qquad e_i \leftarrow (1 - \eta \lambda_i) \, e_i \]
\[ |1 - \eta \lambda| < 1 \quad \text{for every } \lambda \qquad \Longrightarrow \qquad \eta < \frac{2}{\lambda_{\max}} \]
\[ \text{the flat direction then shrinks by } \Bigl|1 - \eta \lambda_{\min}\Bigr| \text{ per step} \]

One rate must satisfy the steepest direction and is then far too small for the flattest. The ratio \(\lambda_{\max} / \lambda_{\min}\) decides how much too small.

The error flips across the valley and crawls along it

acrossalong
curvature \(\lambda\)74.50.43
\(\eta \lambda\) at \(\eta = 0.024\)1.800.010
error \(\times\) per step0.800.990
steps to shrink it 100-fold21438

\(\lambda_{\max} / \lambda_{\min} = \) 172, so \(\eta\) must stay below \(2 / 74.5 = 0.027\).

Across the valley \(1 - \eta\lambda\) is negative: the sign of the error flips every step, which is the zigzag. Along it the error barely moves, which is the crawl.

Momentum

Two panels of the same valley. Left, gradient descent zigzags and crawls. Right, momentum overshoots a few times across the valley but moves quickly along it and reaches the minimum within 100 steps.
\(v \leftarrow \beta v + g\), then \(w \leftarrow w - \eta v\), with \(\beta = 0.9\) and a third of the rate on the left: 86 steps. Opposite steps cancel in \(v\), and steps in one direction add up.

Momentum unrolled

\[ v_t = g_t + \beta g_{t-1} + \beta^2 g_{t-2} + \dots \]
\[ g \text{ constant:} \qquad v \to g \, (1 + \beta + \beta^2 + \dots) = \frac{g}{1 - \beta} \]
\[ w \leftarrow w - \frac{\eta}{1 - \beta} \, g = w - 10 \, \eta g \quad \text{for } \beta = 0.9 \]

A steady direction speeds up tenfold, while a direction whose sign flips cancels itself.

\(\beta = 0.9\) reaches the minimum first

\(\beta\)\(1/(1-\beta)\)steps to the minimum
011,841
0.52914
0.91086
0.952095
0.99100667

The same \(\eta\) throughout, a third of the rate of the valley slide. \(\beta = 0\) is gradient descent, and three times slower than its 612 steps there.

Too little memory and the steps along the valley stay small. Too much and the velocity carries the weights past the minimum and back, which costs more than it saves. 0.9 is the usual default.

Checkpoint

Along the valley, momentum with \(\beta = 0.9\) steps ten times as far as gradient descent at the same \(\eta\). Why not run gradient descent at ten times the rate instead?

How different are the gradients?

The size of the gradient of each of the 65 parameters of the bearing network, sorted from largest to smallest, on a logarithmic axis. At the initial weights the sizes run from about 0.6 down to 0.0004. After ten epochs the whole curve has dropped and runs from about 0.01 to 0.00002.
The 65 weights and biases of the 2-16-1 bearing network, on all the training data. At the initial weights the largest gradient is 0.60 and the smallest 0.00043, a factor of 1,382. After ten epochs: 0.013 and 0.000021, a factor of 598.

One rate, many scales

The gradient of one weight can be a thousand times that of another.

One \(\eta\) is then too large for the first and too small for the second.

\[ s \leftarrow \beta_2 s + (1 - \beta_2) \, g^2 \] \[ w \leftarrow w - \eta \, \frac{g}{\sqrt{s} + \varepsilon} \]

This rule is RMSProp. \(s\): the running mean of \(g^2\), per weight. The step no longer grows with the size of \(g\).

Adam

Pseudocode

η=10⁻³, β1=0.9, β2=0.999
for t = 1, 2, ...:
  g ← gradient
  m ← β1 m + (1 − β1) g
  s ← β2 s + (1 − β2) g²
  m̂ ← m / (1 − β1ᵗ)
  ŝ ← s / (1 − β2ᵗ)
  w ← w − η m̂ / (√ŝ + ε)

numpy

m = b1 * m + (1 - b1) * g
s = b2 * s + (1 - b2) * g**2
m_hat = m / (1 - b1**t)
s_hat = s / (1 - b2**t)
root = np.sqrt(s_hat) + eps
w = w - lr * m_hat / root

\(m\) is the momentum of this block, \(s\) the RMSProp of the previous slide, and \(\hat{m}\), \(\hat{s}\) a bias correction.

Why the bias correction

\[ m_1 = (1 - \beta_1) \, g = 0.1 \, g, \qquad s_1 = (1 - \beta_2) \, g^2 = 0.001 \, g^2 \]
\[ \frac{m_1}{\sqrt{s_1}} = \frac{0.1 \, g}{0.0316 \, |g|} = 3.16 \, \operatorname{sign}(g) \]
\[ \frac{\hat{m}_1}{\sqrt{\hat{s}_1}} = \frac{m_1 / 0.1}{\sqrt{s_1 / 0.001}} = \operatorname{sign}(g) \]

Both averages start at zero, so both are too small at first — but by different factors. Without the correction the first step is 3.2 times \(\eta\).

Without the correction the step grows to 6.6\(\eta\)

The step size of Adam in units of eta against the step on a logarithmic axis from 1 to 1000, for one weight with a constant gradient. Without the correction the step starts at 3.2, rises to 6.6 at step 12, and falls slowly to 2 at step 300 and 1.3 at step 1000. With the correction it is 1 at every step.
One weight, a constant gradient. \(m\) fills up within about 30 steps, \(s\) only over thousands, so the uncorrected step peaks at 6.6\(\eta\) at step 12 and is still 2.0\(\eta\) at step 300. The corrected step is \(\eta\) from the first step.

What dividing by \(\sqrt{s}\) does

gradient \(g\)one plain step \(\eta g\)three Adam steps
0.5960.0060−0.0300
0.0660.00066−0.0300
0.000430.0000043−0.0300

The largest, the middle and the smallest gradient of the 65 bearing weights, each held constant, \(\eta = 0.01\). The first step is \(\eta\) in every direction, since \(\hat{m}_1 = g\) and \(\hat{s}_1 = g^2\), and so is every step after it.

Plain steps differ by the same factor of 1,382 as the gradients. Divided by their own root mean square, all three weights move by \(\eta\) per step.

On the valley, momentum is fastest

Three panels of the valley with 100 steps each. Gradient descent zigzags and crawls. Momentum overshoots and reaches the minimum. Adam moves diagonally at first, then along the valley, and is close to the minimum.
Steps to the minimum: 612 for gradient descent, 86 for momentum, 207 for Adam with \(\eta = 0.1\). Adam's steps have about the size \(\eta\), whatever the size of the gradient. Its rescaling has only two weights to act on here, and momentum wins.

Momentum also leads on the bearings

Training loss against epochs for the 2-16-1 network on the bearings. Momentum falls fastest and is slightly noisy, Adam falls smoothly, and plain SGD is the slowest over ten epochs.
The 2-16-1 network of lecture 5, batches of 32. SGD and momentum share \(\eta = 0.1\), so their gap is momentum alone, and Adam runs at its best rate, 0.01. On 65 weights Adam buys no speed. It is the default for large networks, which these data cannot show.

What the optimiser remembers

rulestate per weight784-128-10
SGDnothing0.4 MB
momentum\(v\)0.8 MB
Adam\(m\) and \(s\)1.2 MB

101,770 parameters in 32-bit floats, with the weights themselves counted.

Harmless here. On a model with a billion parameters, 4 GB of weights become 12 GB before a single activation is stored, and lecture 5 showed that the activations also have to be kept.

Adam does not choose \(\eta\) for you

Training loss against twenty epochs for Adam at four learning rates. At 0.0001 the loss falls from 1.3 to about 0.95 and is still falling. At 0.001 it reaches about 0.2. At 0.01 and 0.1 it reaches about 0.13, the second one noisily.
The same network, the same twenty epochs. Mean loss over the last epoch: 0.96 at \(\eta = 10^{-4}\), 0.20 at the default \(10^{-3}\), 0.136 at \(10^{-2}\), 0.144 at \(10^{-1}\).

Finding the rate in one sweep

The loss of each minibatch against the learning rate of the step about to be taken, rising geometrically from 0.00001 to 100 over 240 steps, for SGD and Adam. Both curves are flat at small rates, fall, reach a minimum, and then rise steeply. Markers sit at 0.03 for Adam and 0.32 for SGD.
One sweep of 240 batches, raising \(\eta\) geometrically after every step. Nothing happens, then the loss falls, then it explodes. Take about a tenth of the lowest point: \(\eta = 0.03\) for Adam, within a factor of three of the best full run, and \(0.32\) for SGD, between the 0.3 and 1 that lecture 5 found fast.

Schedules

The factor applied to the learning rate over 640 steps for four schedules. Constant stays at one. Step decay drops to 0.1 at half of the steps and to 0.01 at three quarters. Cosine falls smoothly from one to zero. Warm-up rises linearly over the first 64 steps, then follows the cosine.
The factor applied to \(\eta\) over 640 steps, i.e. 20 epochs of 32 batches. Warm-up, the fourth, comes after the next slide.

Why decay

Training loss against epochs on the bearings with SGD at a learning rate of 1.0. With a constant rate the loss keeps jumping until the end. With step decay the jumps stop at epoch 10, and with cosine decay the loss settles smoothly at the lowest value.
SGD with \(\eta = 1\), the best rate of lecture 5 at batches of 32, as on the opening slide. Constant: the loss keeps jumping, 0.138 on average over the last epoch. Step decay: 0.135. Cosine: it settles at 0.133.

Warm-up

Adam's first step is \(\eta\) in every direction, whatever the gradient.

At the start the weights are random, the gradient says little, and a large \(\eta\) sends every weight the same distance into the dark.

Warm-up raises \(\eta\) from near zero over the first steps, by which time \(s\) has seen enough gradients to mean something.

On the bearing network it gains nothing: with Adam at \(\eta = 0.1\), the largest rate of the sweep and the one where warm-up has most to do, it ends at 0.1305 against 0.1311 for the same cosine schedule without it.

A recipe for the optimiser

  1. Start with Adam at its default \(\eta = 10^{-3}\), a starting point and no more: on the bearings the sweep moved it to \(10^{-2}\).
  2. Sweep \(\eta\) over powers of ten, or run the finder once.
  3. Add a cosine decay over the whole run.

Leave \(\beta = 0.9\), \(\beta_1 = 0.9\) and \(\beta_2 = 0.999\) alone.

Reach for SGD with momentum when memory is tight, or when a published result used it. Add warm-up when the model is large.

Checkpoint

Why lower \(\eta\) near the end of training, when the same \(\eta\) worked well at the start?

Block 2

Regularising networks

A network overfits

Twenty turbine measurements with the fit of a network with two hidden layers of 64 tanh units. The fit passes through every training point and swings sharply between them, with a spike near 4 m/s and a dip below zero near 3 m/s. The test data and the true curve are drawn behind it.
Twenty measurements, two hidden layers of 64 tanh units, 10,000 epochs of Adam. Training RMSE 9.5 kW, far below the noise. Test RMSE 205 kW, against 96 kW for the true curve.

Why it can

layerparameters
1 → 6464 + 64 = 128
64 → 644,096 + 64 = 4,160
64 → 164 + 1 = 65
total4,353

218 parameters for every training measurement.

Lecture 2 fitted a degree 12 polynomial, i.e. 13 numbers, to 50 points and it already swung. Nothing in the loss asks this network to be smooth, so it passes through all twenty points and does as it likes between them.

Weight decay is ridge

\[ \loss_\lambda = \loss + \lambda \textstyle\sum w^2 \]
\[ \frac{\partial \loss_\lambda}{\partial w} = g + 2 \lambda w \]
\[ w \leftarrow w - \eta \, (g + 2 \lambda w) = (1 - 2 \eta \lambda) \, w - \eta g \]

The penalty of lecture 2. Every step first shrinks each weight by the factor \(1 - 2\eta\lambda\): a decay.

Weight decay on the turbine

Three panels of the same network with weight decay. λ = 0.00001: the fit still swings between the points. λ = 0.001: a smooth S-shaped curve close to the true curve. λ = 0.1: an almost straight line that misses the plateau.
\(\lambda = 10^{-5}\): the swings remain, 230 kW. \(\lambda = 10^{-3}\): 128 kW. \(\lambda = 0.1\): too flat, 369 kW. \(\lambda\) is tuned on validation data, as in lecture 2.

Validation picks \(\lambda = 10^{-4}\)

Validation and test RMSE against the weight decay on a logarithmic axis, from zero to 1. Both curves sit near 200 kW for the smallest values, dip to about 120 kW at 0.0001, stay below 175 kW up to 0.01, and then climb steeply to over 650 kW at 1. A dashed line marks the validation minimum at 0.0001.
The curve of lecture 2 again, now for a network. The validation error is lowest at \(\lambda = 10^{-4}\) (121 kW, test 124 kW), and it chooses \(\lambda\) without ever looking at the test data. The figures of this block use \(10^{-3}\), whose validation error of 136 kW is within the wobble of a single run.

Early stopping

Training and validation RMSE against epochs for the unregularised network. The training error falls to about 10 kW. The validation error falls to about 140 kW, reaches its minimum at epoch 1126, marked by a dashed line, and then rises to about 210 kW.
The unregularised network. The validation error is lowest at epoch 1126. The weights of that epoch reach a test RMSE of 139 kW, against 205 kW at epoch 10,000.

Early stopping, written out

Pseudocode

after every epoch:
  if the validation loss
     is the best so far:
    keep these weights
    reset the counter
  else:
    count one epoch
    stop at the patience

numpy

best, kept, waited = np.inf, 0, 0
for epoch, value in enumerate(val):
    if value < best:
        best, kept = value, epoch
        waited = 0
    else:
        waited += 1
        if waited == patience:
            break

Dropout

A network with two inputs, two hidden layers of four units and one output. In each hidden layer, one unit is crossed out and has no connections for this training step.

In each training step, each hidden unit is dropped with probability \(p\).

Kept units are scaled by \(1/(1-p)\), so the next layer receives the same input on average.

keep = rng.random(H.shape) >= p
H = H * keep / (1 - p)

At test time nothing is dropped and nothing is scaled.

Why dropout works

No unit can rely on one particular other unit, since it may be gone in the next step.

Each step trains a different thinned network, sharing its weights with all the others.

At test time the full network approximates the average of the thinned networks: the bagging of lecture 4, inside one network.

Dropout, one step by hand

\[ h = (2.0,\; -1.0,\; 0.5,\; 3.0), \qquad p = 0.5, \qquad \text{mask} = (1,\, 0,\, 0,\, 1) \]
\[ h' = \frac{\text{mask}}{1 - p} \odot h = (\mathbf{4.0},\; 0,\; 0,\; \mathbf{6.0}) \]
\[ \frac{\partial \loss}{\partial h} = \frac{\text{mask}}{1 - p} \odot \frac{\partial \loss}{\partial h'} \]

The same mask on the way back. In that step a dropped unit receives no gradient, on either side of it.

Dropout on the turbine

Two panels. Left, the unregularised fit with its swings. Right, the same network trained with dropout of 0.1, a smooth curve close to the true curve.
The same network and training. With \(p = 0.1\): test RMSE 129 kW, against 205 kW without dropout.

Any \(p\) from 0.05 to 0.4 does about as well

Validation and test RMSE against the dropout probability. Both fall from about 205 kW at p = 0 to about 130 kW at p = 0.05, then stay between 115 and 135 kW for p up to 0.4.
Everything from 0.05 to 0.4 lands within 20 kW. The validation error is lowest at \(p = 0.4\) (117 kW). The figures of this block use 0.1, whose 123 kW is 6 kW away.

What the two methods leave behind

test RMSElargest \(|w|\)rms \(w\)steepest slope
no regularisation205 kW7.080.403,936
weight decay, \(\lambda = 10^{-3}\)128 kW1.070.029342
dropout, \(p = 0.1\)129 kW3.090.35719
the true curve———507

Slopes in kW per m/s over the training range. Weight decay shrinks the weights fourteenfold and leaves a fit flatter than the true curve. Dropout, at the same test error, leaves the weights almost as large as before.

Or simply a smaller network

hidden unitsparameterstrainingtest
41379151
164962197
64, 644,3539.5205

RMSE in kW, the same twenty measurements and the same training.

It helps, and it is the bluntest of the cures: the training error rises eightfold and the test error still does not reach the 128 kW of a penalty on the large network.

Or simply more data

Three panels of the same wide network on 20, 50 and 200 turbine measurements. With 20 the fit swings wildly between the points. With 50 it follows the true curve with small wobbles. With 200 it lies almost on the true curve.
The same network, the same 10,000 epochs, no penalty at all. Test RMSE 205, 116 and 99 kW. The measurements carry a noise of 96 kW, which the last fit comes within 3 kW of.

The same overfit, five cures

curetest RMSEwhat it costs
nothing205 kW—
a smaller network151 kWfreedom removed everywhere
early stopping139 kWa validation set
dropout, \(p = 0.1\)129 kWone \(p\), slower training
weight decay, \(\lambda = 10^{-3}\)128 kWone \(\lambda\)
ten times the data99 kW180 more measurements

The noise in the measurements is 96 kW, which only the last row comes near. The three rows between are within 11 kW of one another, which on twenty measurements is not a difference worth defending.

Batch norm lets a deep network train

Loss of each minibatch against epochs for a deep sigmoid network on the bearings. Without batch normalisation the epoch averages stay at about 0.32, on the dashed line of always predicting 10 percent faulty. With batch normalisation they fall to about 0.19 in ten epochs.
Eight hidden layers of 32 sigmoid units, SGD with \(\eta = 0.1\). Without batch norm the network stays at 0.325, the loss of always predicting 10% faulty: the vanishing gradient of lecture 5. With it, the loss falls to 0.19 in ten epochs.

How deep before it matters

Bars of the training loss after ten epochs at two, four and eight hidden layers, without and with batch normalisation. Without it the loss is 0.30 at two layers and sits on the dashed line of the constant model at four and eight. With it the loss is about 0.19 at every depth.
Without batch norm, two layers still learn a little (0.296) while four and eight sit at the constant model (0.327 and 0.320, against 0.325). With it, every depth reaches about 0.19.

Batch normalisation

\[ \mu = \frac{1}{B} \sum_{i} z_i, \qquad \sigma^2 = \frac{1}{B} \sum_{i} (z_i - \mu)^2 \]
\[ \hat{z}_i = \frac{z_i - \mu}{\sqrt{\sigma^2 + \varepsilon}}, \qquad z_i' = \gamma \, \hat{z}_i + \beta \]

For every unit, over the minibatch: the standardisation of lecture 2, inside the network, which keeps each sigmoid in its steep middle. \(\gamma\) and \(\beta\) are learned. At test time, running averages of \(\mu\) and \(\sigma^2\) replace the minibatch values.

Where it sits

layers.append(nn.Linear(n_in, 32))
layers.append(nn.BatchNorm1d(32))
layers.append(nn.Sigmoid())

Between the linear part of a layer and its activation, one normaliser per layer.

nn.BatchNorm1d(32) carries 64 learned numbers, a \(\gamma\) and a \(\beta\) per unit, and two running averages that are not learned.

For images the layer is nn.BatchNorm2d, which normalises each channel over the batch and over every pixel of it.

Batch norm at test time

unit 1unit 2unit 3
example 1123
example 2321
example 3222
example 4024

Unit 1 has mean 1.5 and variance 1.25 over the batch, so its first value becomes \((1 - 1.5)/\sqrt{1.25} = \) −0.45.

The running mean after this one batch is 0.15, a tenth of 1.5: PyTorch mixes in each new batch with a weight of 0.1. In eval() mode the same value becomes 0.82.

A batch of one in train mode has no variance, so PyTorch refuses it: Expected more than 1 value per channel when training.

Train mode, eval mode

Training

  • Dropout drops units
  • Batch norm uses the minibatch

Evaluation

  • Dropout keeps every unit
  • Batch norm uses its running averages

PyTorch switches both with one call, model.train() or model.eval(). Block 3 places both in the training loop.

Dropout left on, measured

One wind speed, 10 m/s, 100 forward passes of the same trained network.

modeprediction
eval923 kW
train847 to 1,040 kW

A standard deviation of 37 kW on a single prediction, from nothing but the masks.

This is the forgotten eval() of the previous slide. Over the whole test set the noise averages out: the RMSE moves from 129 to about 134 kW. The aggregate error nearly hides the bug. A single prediction does not.

Which one when

  • Weight decay changes the loss. Cost: one \(\lambda\) to tune.
  • Early stopping changes the training. Cost: a validation set.
  • Dropout changes the network while it trains. Cost: slower training, one \(p\) to tune.
  • Batch norm changes the network. Mostly faster training, and a little regularisation.

Checkpoint

The training loss is near zero and the validation loss rises after epoch 40. Name two changes, and what each does to the two curves.

Break

Ten minutes

Block 3

PyTorch

Why a framework

Lecture 5 wrote every backward line by hand, for one architecture.

A framework records the forward pass as it runs, and computes every gradient from that record.

The same code runs on a graphics processing unit (GPU).

Exercise 3 uses PyTorch, as does most research code.

Tensors

numpy

X = np.zeros((32, 2))
X.dtype   # float64

PyTorch

X = torch.zeros(32, 2)
X.dtype   # torch.float32

A tensor is an array that also knows its device and can record gradients.

torch.from_numpy(a).float() converts, since PyTorch works in 32-bit floats.

Autograd

X = torch.tensor([[1.0, 2.0]])
W1 = torch.tensor([[0.5, -0.3],
                   [0.2, 0.4]])
b1 = torch.tensor([0.0, 0.1])
W2 = torch.tensor([[0.8], [-0.5]])
b2 = torch.tensor([0.1])
for t in (W1, b1, W2, b2):
    t.requires_grad_()
H1 = torch.relu(X @ W1 + b1)
P = torch.sigmoid(H1 @ W2 + b2)
loss = -torch.log(P).mean()
loss.backward()

The worked network of lecture 5, with X @ W1 + b1 as there. The target is \(y = 1\), so the loss is \(-\ln p\).

W2.grad: −0.336, −0.224

W1.grad: −0.298, 0.186, −0.597, 0.373

The numbers of the backward slides of lecture 5, to a relative error below \(10^{-6}\).

The recorded graph

The computation graph of lecture 5: X, a linear step to Z1, ReLU to H1, a linear step to Z2, sigmoid to P, and cross-entropy to the loss, with a dashed backward arrow from the loss to X.
PyTorch builds this graph while the forward code runs, and loss.backward() sweeps it backwards. Gradients are added to .grad, so every step starts with zero_grad().

The graph, printed

node = loss.grad_fn
while node is not None:
    print(type(node).__name__)
    after = node.next_functions
    if not after:
        break
    node = after[0][0]
NegBackward0
MeanBackward0
LogBackward0
SigmoidBackward0
AddBackward0
MmBackward0
ReluBackward0
AddBackward0
MmBackward0

The forward pass of the previous slide, read from the bottom up. It stops at the matrix product that reads \(X\): the data need no gradient.

Gradients add up

The same forward pass and backward() twice, with no zero_grad() between them:

W1.grad[0]
after one−0.2983, 0.1864
after two−0.5966, 0.3729

Exactly doubled. .grad is added to, never replaced.

Leave zero_grad() out of a loop and step \(k\) uses the sum of the first \(k\) gradients, which is the gradient of nothing.

nn.Module

model = nn.Sequential(
    nn.Linear(2, 16),
    nn.ReLU(),
    nn.Linear(16, 1),
)

nn.Linear(2, 16) holds a weight of shape 16 × 2 and computes X @ W.T + b: the transpose of lecture 5. Weights copied from numpy are transposed.

class BearingNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.l1 = nn.Linear(2, 16)
        self.l2 = nn.Linear(16, 1)

    def forward(self, x):
        h = torch.relu(self.l1(x))
        return self.l2(h)

Every shape of one step

shape
xb32 × 2
l1.weight, l1.bias16 × 2, 16
l1(xb), after relu32 × 16
model(xb)32 × 1
yb32 × 1
lossa scalar

The batch size runs down the rows and never meets a weight.

Shape errors are the commonest failure of part 2 of exercise 3. Print them when something does not fit: print(xb.shape, out.shape, yb.shape) finds the mistake faster than reading the traceback.

Counting the parameters

sum(p.numel()
    for p in model.parameters())

65 for the 2-16-1 bearing network, the count of lecture 5.

101,770 for the 784-128-10 network of part 3 of exercise 3.

model.parameters() is also what the optimiser is given. To count only what is being trained when some weights are frozen, as in the transfer learning of lecture 7, add if p.requires_grad.

Loss and optimiser

loss_fn = nn.BCEWithLogitsLoss()
opt = torch.optim.SGD(
    model.parameters(), lr=0.1,
    momentum=0.9)
opt = torch.optim.Adam(
    model.parameters(), lr=1e-3,
    weight_decay=1e-4)

BCEWithLogitsLoss takes the score \(z\), not \(\sigma(z)\): it folds the sigmoid into the loss, which is numerically stable.

Block 1 in one line: momentum or Adam.

weight_decay adds weight_decay · w to the gradient, i.e. \(2\lambda\) of block 2, and it decays the biases too.

DataLoader

X = torch.from_numpy(X_np).float()
y = torch.from_numpy(y_np).float()
data = TensorDataset(X, y)
loader = DataLoader(data,
    batch_size=32, shuffle=True)

One pass over loader is one epoch of shuffled batches of 32: the loop of lecture 5, built in.

y is a column of shape \(n \times 1\), like the output. BCEWithLogitsLoss rejects labels of shape \(n\). MSELoss accepts them with a warning and broadcasts to an \(n \times n\) difference.

The training loop

Pseudocode

for each epoch:
  for each batch (xb, yb):
    reset the gradients
    out ← model(xb)
    loss ← L(out, yb)
    backward: the gradients
    one step of the optimiser

PyTorch

for epoch in range(epochs):
    for xb, yb in loader:
        opt.zero_grad()
        out = model(xb)
        loss = loss_fn(out, yb)
        loss.backward()
        opt.step()

The same loop, twice

lecture 5, by hand

dZ2 = (P - y) / len(y)
dW2 = H1.T @ dZ2
db2 = dZ2.sum(axis=0)
dH1 = dZ2 @ W2.T
dZ1 = dH1 * (Z1 > 0)
dW1 = X.T @ dZ1
db1 = dZ1.sum(axis=0)

lecture 6

loss.backward()

Seven lines written for one architecture, against one line that works for any. Change the activation, add a layer, branch the network: the left column is rewritten, the right one is not.

Block 2 in PyTorch

model = nn.Sequential(
    nn.Linear(1, 64), nn.Tanh(),
    nn.Dropout(p),
    nn.Linear(64, 64), nn.Tanh(),
    nn.Dropout(p),
    nn.Linear(64, 1),
)
opt = torch.optim.Adam(
    model.parameters(), lr=1e-3,
    weight_decay=2e-3)

The wide network of block 2, with dropout and weight decay.

nn.Dropout holds no parameters: still 4,353.

weight_decay=2e-3 is \(\lambda = 10^{-3}\) of block 2: PyTorch adds weight_decay · w to the gradient, i.e. \(2\lambda w\).

Batch normalisation would be nn.BatchNorm1d(64) between each nn.Linear and its nn.Tanh, not where the dropout sits. Early stopping is the only one of the four with no layer and no argument: it is written in the loop.

Evaluating

model.eval()
with torch.no_grad():
    P = torch.sigmoid(model(X))
model.train()
  • eval(): dropout off, batch norm on its running averages
  • no_grad(): no graph is recorded, which saves memory and time
  • train(): back to training before the next step

Train mode for the batches, eval mode for validation

for epoch in range(epochs):
    model.train()
    for xb, yb in loader:
        opt.zero_grad()
        out = model(xb)
        loss = loss_fn(out, yb)
        loss.backward()
        opt.step()
    model.eval()
    with torch.no_grad():
        out = model(X_val)
        val = loss_fn(out, y_val)

The training loop of this block, with a validation pass at the end of every epoch.

train() at the top of the epoch, since the validation pass of the last one left the model in eval mode.

This is what mlcourse.training.train() runs in exercise 3. Its printed lines are the next slide.

Watching it train

epoch 1/5  train loss 0.486
           val loss 0.282
epoch 2/5  train loss 0.197
           val loss 0.182
epoch 3/5  train loss 0.150
           val loss 0.176
epoch 4/5  train loss 0.144
           val loss 0.177
epoch 5/5  train loss 0.141
           val loss 0.176

Print both losses after every epoch and read the shape:

  • both falling: keep going
  • both flat and high: block 1
  • training falling, validation rising: block 2
  • validation below training: the training loss averages a model that improved during the epoch, or includes dropout

Validation on 500 fresh bearings. The real lines also carry an accuracy for each set, left out here for width.

On a GPU

ready = torch.cuda.is_available()
dev = "cuda" if ready else "cpu"
model = model.to(dev)
for xb, yb in loader:
    xb = xb.to(dev)
    yb = yb.to(dev)

Nothing else in the loop changes.

Every tensor in an operation must sit on the same device, or PyTorch raises an error.

It pays when the batches are large and the model has work to do. A model as small as today's gains little: every batch costs a copy to the device and back, and 32 rows through 65 weights is no work at all.

A correct loop can drive one batch to near-zero loss

Loss on one batch of 32 bearings against 300 steps, on a logarithmic axis. The correct loop falls steadily below 0.01 and reaches about 0.0015. The loop with a sigmoid before BCEWithLogitsLoss stays flat at about 0.65, just above a dashed line at 0.62.
Before training on everything, train on one batch until it is memorised. 32 training bearings, 6 of them faulty, Adam with \(\eta = 0.1\). The correct loop falls below 0.01 by step 134. With a sigmoid before BCEWithLogitsLoss, the loss cannot fall below 0.62.

Six ways to get it wrong

  • Labels of shape \(n\): Target size … must be the same as input size, or a silent broadcast from MSELoss
  • A float64 array: mat1 and mat2 must have the same dtype
  • The wrong width: shapes cannot be multiplied (32x3 and 2x16)
  • No zero_grad(): the loss falls, then wanders or diverges
  • No eval(): predictions that change between calls
  • A sigmoid before BCEWithLogitsLoss: a loss stuck above 0.62

The same code, a different answer

The 2-16-1 network, Adam, ten epochs, five seeds:

0.1336 to 0.1374, a spread of 0.004.

The seed fixes the initial weights and the order of the batches, and nothing else in this run is random.

torch.manual_seed(0) before the model and before the loader. Every figure of this lecture does it; without it, none of its numbers would hold.

Checkpoint

With opt.zero_grad() missing, SGD's loss falls for the first steps and then wanders. Why does it fall at all?

Takeaways

  1. Momentum averages the gradients over steps, and Adam scales the step of every weight.
  2. A decaying learning rate lets the weights settle.
  3. Weight decay, early stopping and dropout limit what a wide network memorises.
  4. Batch norm keeps deep networks trainable.
  5. PyTorch computes the gradient of any forward pass, and the loop stays five lines.
  6. More data beats every method in this lecture.
  7. The learning rate is still the number to get right.

What changed from lecture 5

lecture 5lecture 6
modelcomposed nonlinear layers, unchanged
losscross-entropy\(+ \lambda \sum w^2\)
step\(w - \eta g\)momentum, Adam
rateone constantper weight, with a schedule
network while trainingfixeddropout, batch norm
gradientseven lines of numpyloss.backward()

Today's new numbers to choose

Leave at the default

  • \(\beta = 0.9\) for momentum
  • \(\beta_1 = 0.9\), \(\beta_2 = 0.999\) for Adam
  • batch norm: its \(\gamma\) and \(\beta\) are learned

Choose on validation data

  • \(\eta\), first and most important
  • \(\lambda\), over powers of ten
  • \(p\), between 0.1 and 0.5
  • the schedule, and the patience

Lecture 6 in three choices

Model

composed nonlinear layers

unchanged from lecture 5

Loss

cross-entropy, squared error, plus \(\lambda \sum w^2\)

the penalty of lecture 2

Optimiser

momentum, Adam

with a schedule, in PyTorch

Further reading

All three books are free to read online.

Next

Exercise 3

Two moons and Fashion-MNIST: backpropagation in numpy, then the same network in PyTorch, trained with the loop of today and regularised with dropout and weight decay.

It uses lectures 5 and 6.

Lecture 7

Convolutional neural networks: structure for images.