Module 4

Optimisation and generalisation

A gradient says which way is downhill. It does not say how far to step, and it does not say whether the bottom of the training loss is where you want to end up. This module is about both.

Why it matters

Plain gradient descent is slow on exactly the kind of surface neural networks produce: long, curved valleys that are steep across and shallow along. Momentum and Adam are the two ideas that make training practical, and Adam is what trains the transformer later in this course. Getting to the minimum is only half the job, though. A network with enough parameters can drive its training loss to zero by memorising noise, so you also need ways to notice that happening and to stop it.

The idea

Stochastic gradient descent

With a large dataset, computing the loss over every example for one step is wasteful. Stochastic gradient descent (SGD) estimates the gradient from a small random batch instead, and steps along that estimate $g_t$:

$$\theta \leftarrow \theta - \eta\, g_t .$$

Each step is cheap and noisy. The demos here are small enough to use every example at every step, so their gradients are exact; the update rule is the same.

Why plain descent is slow

Module 1 showed that the step size $\eta$ is capped by the steepest direction of the surface. In a narrow valley that cap is tiny compared with what the shallow direction needs, so descent creeps along the floor. The ratio of the largest to the smallest curvature, the condition number $\kappa$, measures how bad this is: on a quadratic bowl, gradient descent needs a number of steps proportional to $\kappa$.

Momentum

Give the parameters a velocity $v$ that remembers previous gradients:

$$v \leftarrow \beta\, v - \eta\, g_t, \qquad \theta \leftarrow \theta + v .$$

Gradient components that keep flipping sign, as they do across a valley, cancel in the running sum. Components that keep pointing the same way, along the valley, build up: under a constant gradient the velocity settles at $-\eta g / (1 - \beta)$, ten times a plain step when $\beta = 0.9$. On a quadratic bowl a well-chosen $\beta$ improves the dependence on the condition number from $\kappa$ to $\sqrt{\kappa}$.

Adam

Adam keeps two running averages, one of the gradient and one of its square, and uses their ratio to give every parameter its own step size:

$$m \leftarrow \beta_1 m + (1 - \beta_1)\, g_t, \qquad v \leftarrow \beta_2 v + (1 - \beta_2)\, g_t^2,$$ $$\hat m = \frac{m}{1 - \beta_1^{\,t}}, \qquad \hat v = \frac{v}{1 - \beta_2^{\,t}}, \qquad \theta \leftarrow \theta - \eta\, \frac{\hat m}{\sqrt{\hat v} + \varepsilon} .$$

Squares and square roots are taken entry by entry, and $t$ counts steps from 1. The usual settings are $\beta_1 = 0.9$, $\beta_2 = 0.999$ and $\varepsilon = 10^{-8}$. Because the update divides a gradient average by the root of a squared-gradient average, its size is about $\eta$ whatever the scale of the gradients: a parameter with tiny gradients moves as fast as one with huge ones. The divisions by $1 - \beta^{\,t}$ are the bias correction. Both averages start at zero, so early on they underestimate; the correction undoes that exactly, and makes the very first step $-\eta\, \operatorname{sign}(g_1)$.

Generalisation

The loss you can compute is on the training set. The loss you care about is on data the model has not seen. Hold some data back as a validation set, track its loss during training, and the typical picture appears: both losses fall at first, then the training loss keeps falling while the validation loss turns and rises. From that point the model is fitting noise. This is overfitting. Three standard defences:

Once the validation set has been used to pick $\lambda$ or the stopping step, its loss is no longer an honest estimate of performance on new data: the choices were tuned to it. That is why a third, untouched test set is kept for the final number.

Live demos

A race of optimisers

Three optimisers, one curved valley

The surface (darker is higher). The cross is the minimum. Click to move the start.

Where each one is now

OptimiserfDistance to minimum

The function is $f(x, y) = (1 - x)^2 + 10\,(y - x^2)^2$, a gentler version of Rosenbrock's test function, with its minimum at $(1, 1)$. All three optimisers start from the same point and take 400 steps using the exact gradient.

Overfitting, and three ways to stop it

Twelve noisy points and a network with 1,153 parameters

The data and the network's fit

training points (12)validation points (60)dashed: the true curve · solid: the network

Loss during training

A 1 → 32 → 32 → 1 tanh network trained with Adam for up to 1,500 steps on the twelve orange points. The noise in the data has variance 0.16, so no model can get a validation loss much below that. The vertical line marks the step with the lowest validation loss so far.

Try this

  1. Start the race. SGD crawls along the valley floor; momentum and Adam reach the cross. Then set β to 0 and race again: momentum without memory is SGD, and the two paths coincide.
  2. Click near the bottom right corner of the surface to start there. Adam is no longer the winner. No optimiser is best on every surface.
  3. In the second demo, press Train with everything off. The training loss goes to zero and the fitted curve threads every orange point, while the validation loss bottoms out early and then climbs.
  4. Set λ to about 0.003 and train again. The fit is smoother and the validation loss ends lower than before, though the training loss is now higher. Push λ to 0.02 and the fit becomes too stiff.
  5. Put λ back to 0 and tick Early stopping. Training now halts soon after the validation minimum and rewinds to it.

Exercise

Implement Adam, overfit, then fix it

Part 1. Replace the plain gradient step in adam_step with Adam, keeping the running averages and the step count in state.

Part 2. The provided fit uses your Adam to fit a polynomial with 12 coefficients to 12 noisy points. With no penalty it reproduces the overfitting curve: training loss near zero, validation loss far above its best value. Choose LAMBDA, the strength of an L2 penalty, so that the final validation loss comes in below 0.2.

Check yourself

With β = 0.9 and the same gradient $g$ at every step, what velocity does momentum settle at?

Setting $v = \beta v - \eta g$ gives $v = -\eta g / (1 - \beta) = -10\, \eta g$: ten times a plain gradient step. That build-up along consistent directions is where the speed comes from.

What is Adam's very first update, and what would it be without bias correction?

At $t = 1$, $\hat m = g$ and $\hat v = g^2$, so the update is $-\eta\, g / |g| = -\eta \operatorname{sign}(g)$. Without the correction, $m = 0.1\,g$ and $v = 0.001\,g^2$, and the ratio is $0.1 / \sqrt{0.001} \approx 3.2$: the first steps would be about three times larger than intended.

You used the validation loss to choose λ and the stopping step. Why should it not also be your reported accuracy?

Those choices were made because they scored well on that particular set, so its loss is biased low. An honest estimate needs data that played no part in any decision: a separate test set, looked at once.

Where this leads

Everything so far has been trained by descent on a surface with many minima. Module 5 looks at a model built the other way round: the support vector machine, whose training problem has a single best answer, and whose kernel trick gets curved boundaries out of a linear method.

Sources: B. T. Polyak, “Some methods of speeding up the convergence of iteration methods”, USSR Computational Mathematics and Mathematical Physics 4 (1964); D. P. Kingma and J. Ba, “Adam: a method for stochastic optimization”, ICLR (2015); N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever and R. Salakhutdinov, “Dropout: a simple way to prevent neural networks from overfitting”, Journal of Machine Learning Research 15 (2014); I. Goodfellow, Y. Bengio and A. Courville, Deep Learning, MIT Press (2016), ch. 7 and 8; H. H. Rosenbrock, “An automatic method for finding the greatest or least value of a function”, The Computer Journal 3 (1960).