✖

Gradient descent: how a neural network learns

Gradient descent is the procedure by which practically all of today’s neural networks learn, including the one ChatGPT runs on. So how does a neural network learn? Quite simply, from its mistakes. It is given an example, computes an answer and finds out by how much it got it wrong. Then it nudges each of its weights a little in the direction in which the error decreases, and reaches for the next example. Thousands of times, millions of times, over and over.

The network itself is one long calculation. Numbers go into it, get multiplied by weights and added up, and everything the network can do is stored in those very weights. At first they are random numbers and the network babbles nonsense. How a single neuron computes and why several layers of them are needed is described in the neural network part, and how text turns into numbers in the first part of the series How artificial intelligence computes. All we need here is that a weight is a number that can be moved.

The loss function: how badly the network got it wrong

We start with the smallest network imaginable: a single neuron with a single weight w. It multiplies the input x by the weight and sends the result out:

y=w⋅x

It will learn from a single example: for the input 1 it should answer 3. The correct weight is obviously w = 3, but the network does not know that. It sets off from w = 0 and answers 0 · 1 = 0. Off by three.

For the network to find out how far it missed, it has to express the error as a single number. A common choice is the square of the difference between the answer and the correct result. For the input 1 the answer is simply w, so the error is

f(w)=(w−3)2

Why the square and not just the difference? An answer that is three too small is just as bad as one that is three too large, and the square turns both into a positive 9. On top of that it punishes large errors more severely than small ones: an error of 1 gives 1, an error of 3 already gives 9. Such a function is called a loss function. A few values for a feel of it:

w 0 1 2 3 4 5
f(w) 9 4 1 0 1 4

Its graph is a parabola: the horizontal axis shows the value of the weight w, the vertical axis the error f(w). Learning therefore means finding its bottom, which here is at w = 3 at first glance. A large language model, however, has billions of weights: nobody can draw the graph of its error or try all the possibilities. The network only ever knows the error at the place where it happens to be standing.

Downhill in the fog: the derivative as a slope

Imagine standing on a hill in thick fog, wanting to get down to the valley. You cannot see a step ahead, but you can feel with your feet which way the ground slopes. You take a step downhill, stop, feel the slope again and carry on. You reach the valley without ever having seen it.

Gradient descent proceeds in the same way, and the slope under its feet is revealed by the derivative. If you do not know it from school, do not worry: the derivative at a point is the slope of the graph at that point, and it says how fast the error changes when we move the weight. And it can be estimated without any theory at all. We are standing at w = 0, where the error is 9. We move a tiny bit, say by 0.01, and measure the error again:

f(0.01)=(0.01−3)2=8.9401

The error dropped by 0.0599, almost six times more than the distance we moved:

8.9401−90.01=−5.99≈−6

The smaller the bit we move by, the closer to −6 we get; moving by 0.001 gives −5.999. The slope at w = 0 is therefore −6: if we increase the weight by a small amount, the error drops by roughly six times as much. It is written f′(0) = −6 and read “f prime of zero”. If you know tangents, you will recognise this slope as the slope of the tangent line. You can find more about this in the article derivative.

Graph of the parabola f(w) = (w − 3)² with the bottom at w = 3 marked by a green dot. At the point w = 0 there is an orange dot and a red tangent line falling to the right, labelled f′(0) = −6, and at the point w = 5 an orange dot and a blue tangent line rising to the right, labelled f′(5) = 4. Green arrows along the parabola point down to the bottom from both sides Graph of the parabola f(w) = (w − 3)² with the bottom at w = 3 marked by a green dot. At the point w = 0 there is an orange dot and a red tangent line falling to the right, labelled f′(0) = −6, and at the point w = 5 an orange dot and a blue tangent line rising to the right, labelled f′(5) = 4. Green arrows along the parabola point down to the bottom from both sides

From the slope we can read two things:

  • the sign tells which way is downhill: a negative slope means that the error decreases to the right, so we go right. A positive slope, for example f′(5) = 4, sends us left.
  • the magnitude reveals how steeply the slope falls. Far from the bottom the parabola is steep, near the bottom almost flat, and at the very bottom its slope is zero.

If you can differentiate, you can compute the slope at every point at once with a formula: f′(w) = 2 · (w − 3). If not, you can check it: for w = 0 we get 2 · (−3) = −6, just like our estimate, and for w = 5 we get 2 · 2 = 4, as in the picture.

The gradient descent formula

Now for the step itself. We get the new weight like this:

wnew=w−η⋅f′(w)

The Greek letter η (eta) is the learning rate, a positive number, usually small, which determines how far we move each time. The minus sign is in the formula because we go against the slope, downhill, not uphill. With a negative slope, minus times minus gives plus and the weight grows; with a positive slope it shrinks.

By hand with one weight

We set the learning rate to η=0.25 and set off from w = 0, where the slope is −6. We substitute:

wnew=0−0.25⋅(−6)

We multiply:

wnew=0+1.5=1.5

The network now answers 1.5 and the error has dropped from 9 to (1.5 − 3)2 = 2.25. At the new place we find the slope again, 2 · (1.5 − 3) = −3, and carry on. The first five steps look like this:

step w distance to the bottom error slope
0 0 3 9 −6
1 1.5 1.5 2.25 −3
2 2.25 0.75 0.5625 −1.5
3 2.625 0.375 0.140625 −0.75
4 2.8125 0.1875 0.035 −0.375
5 2.906 0.094 0.0088 −0.1875

Notice that the steps get shorter and shorter. The distance to the bottom (the column “distance to the bottom”) is halved each time, because the slope weakens along with it. The weight never gets to exactly 3, but after five steps the error is 0.0088, less than a hundredth, and that is enough for the network. Real networks stop learning when the error stops decreasing noticeably, or after a predetermined number of steps.

A parabola of the error with an orange ball jumping along it from the point w₀ = 0 to the point w₁ = 1.5 and on in ever shorter jumps towards the bottom at w = 3, marked by a green dot. Orange circles on the parabola show all the steps, dashed arcs the first three jumps, with which the ball approaches the green dot A parabola of the error with an orange ball jumping along it from the point w₀ = 0 to the point w₁ = 1.5 and on in ever shorter jumps towards the bottom at w = 3, marked by a green dot. Orange circles on the parabola show all the steps, dashed arcs the first three jumps, with which the ball approaches the green dot

The learning rate: neither too small nor too large

The size of the step matters a great deal. What if we choose η=0.05? From zero we get only to 0.3, then to 0.57, to 0.813, and after ten steps only to 1.95, where the error is still around 1.1. The direction is right, but the network only creeps towards the goal and wastes a lot of unnecessary computation.

And now, on purpose, a step that is too large, η=1.1. The first step leads from 0 to 0 − 1.1 · (−6) = 6.6. The network overshot the bottom and landed on the other side even higher, with an error of 12.96. And on:

step 0 1 2 3 4
w 0 6.6 −1.32 8.184 −3.22
error 9 12.96 18.66 26.87 38.70

The weight jumps from side to side and the error grows with every jump. The learning has started to oscillate wildly and, instead of going downhill, climbs up.

Two graphs of the parabola of the error side by side. On the left, with learning rate η = 0.05, ten densely bunched orange dots lead from the point w = 0, creeping towards the bottom at w = 3. On the right, with η = 1.1, red arrows lead from side to side of the parabola and each point lies higher than the previous one Two graphs of the parabola of the error side by side. On the left, with learning rate η = 0.05, ten densely bunched orange dots lead from the point w = 0, creeping towards the bottom at w = 3. On the right, with η = 1.1, red arrows lead from side to side of the parabola and each point lies higher than the previous one

There is no formula for the best learning rate; for large networks it is found by trying. Often one starts with a larger one and gradually reduces it, so that the network finally settles in the valley.

Billions of weights: the gradient

The error of a large network depends on all the weights at once. Instead of a parabola there is a landscape with hills and valleys, only not in two dimensions but in billions. Gradient descent in it reaches the bottom of whichever valley it happens to descend into, and that need not be the deepest one (such a bottom is called a local minimum). In practice this matters less for large networks, because the places where learning ends tend to be similarly good. In such a landscape the slope is measured separately in each direction: by how much the error changes when we move the first weight a little, by how much when we move the second, and so on. Together they form a vector called the gradient. It points in the direction in which the error grows most steeply, and gradient descent goes exactly the opposite way, hence its name.

For two weights the landscape can still be drawn, as contour lines on a walking map. Each grey ellipse joins places with the same error, and the green dot is the bottom of the valley:

A graph with two axes w₁ and w₂, grey concentric ellipses around a green dot at the point with coordinates 3 and 2. An orange path starts at the origin, the first arrows climb almost perpendicular to the ellipses, then it turns and in ever shorter steps heads horizontally to the green dot A graph with two axes w₁ and w₂, grey concentric ellipses around a green dot at the point with coordinates 3 and 2. An orange path starts at the origin, the first arrows climb almost perpendicular to the ellipses, then it turns and in ever shorter steps heads horizontally to the green dot

The orange path is gradient descent with the learning rate η=0.1. From each point it heads perpendicular to the contour line, where the slope falls most steeply. The formula stays the same, only instead of one number a whole vector of weights is moved, and instead of one slope the gradient is subtracted.

Backpropagation: how the slope gets through the layers

One snag remains. With a single weight, the slope was easy to compute. In a large network, though, a weight in the first layer affects the error only indirectly: it changes the output of its neuron, that changes the next layer, and so on up to the error. How do we find the slope for it?

A network with two weights in a row will do. The input x is multiplied by the weight w1, the result h by the weight w2, and from the output y the error is computed:

h=w1⋅x

y=w2⋅h

error=(y−3)2

We take x = 1, w1 = 1 and w2 = 2. Then h = 1, y = 2 and the error is (2 − 3)2 = 1.

A chain x, h, y and a red box with the word error, with arrows between them carrying the weights w₁, w₂ and the expression (y − 3)². In orange the values x = 1, h = 1, y = 2 and error 1. Below, red arrows lead from right to left: from the error to y with slope −2, from y to h times 2, from h to the input times 1. Under the nodes are the accumulated slopes −2 at y and −4 at h, and at the very bottom in a box the resulting slopes w₁: −4 and w₂: −2 A chain x, h, y and a red box with the word error, with arrows between them carrying the weights w₁, w₂ and the expression (y − 3)². In orange the values x = 1, h = 1, y = 2 and error 1. Below, red arrows lead from right to left: from the error to y with slope −2, from y to h times 2, from h to the input times 1. Under the nodes are the accumulated slopes −2 at y and −4 at h, and at the very bottom in a box the resulting slopes w₁: −4 and w₂: −2

We proceed backwards from the error. When y increases a little, the error changes with the slope 2 · (y − 3) = −2. That is the same formula as for the parabola, only with y in place of w. A small increase of h increases y twice as much, because y = 2 · h. Every change of h thus reaches the error doubled, and the error changes with the slope −2 · 2 = −4. And w1 passes into h one to one, because x = 1. The slope of the error with respect to w1, that is, how the error changes when we move only w1 and leave w2 standing, is therefore

−2⋅2⋅1=−4.

Along the way the slopes are simply multiplied: the change travels from link to link, and each one amplifies or weakens it. Mathematicians call this the chain rule, or the derivative of a composite function. For the second weight the same reasoning gives −2 · h = −2, so the gradient is (−4, −2). We take one step with it, η=0.1:

w1=1−0.1⋅(−4)=1.4

w2=2−0.1⋅(−2)=2.2

The network now answers 2.2 · 1.4 = 3.08 and the error has dropped from 1 to 0.082 = 0.0064. One step and almost done.

A large network is computed in exactly the same way, the chain is just longer and branching. The calculation runs backwards from the error, layer by layer, and that is why it is called backpropagation. The slopes accumulated at one layer serve all the weights of the previous layer, so nothing is computed twice. Backpropagation costs roughly twice as many operations (individual multiplications and additions) as computing the answer, so learning on one token (a piece of a word) comes to about three times as much: instead of two operations per parameter, that is per weight or bias, there are six.

How long a large model takes to learn

A language model learns to guess which token comes next in a text. The error is larger the smaller the probability it assigned to the token that actually followed (how it is computed is shown in the part on softmax). Everything else works as with our parabola.

GPT-3 from 2020 learned on 300 billion tokens. In one step it did not take one example but 3.2 million tokens at once, averaged the error and moved all 175 billion parameters. In all, that comes to roughly a hundred thousand steps. The learning rate was at most 0.00006, and along the way it was gradually reduced to a tenth. The bare formula was replaced by an improved version of gradient descent called Adam. Six operations per parameter and token give in total

6⋅175 billion⋅300 billion≈3.15⋅1023

operations (the authors of GPT-3 give 3.14 · 1023). By hand, at one operation per second, you would be calculating roughly seven hundred thousand times longer than the universe has existed. And the whole thing was still only our walk in the fog: find the slope, take a small step downhill and do it again.

Chapters: How ChatGPT and artificial intelligence work: the maths inside, Neural network: what it is and how it computes, Gradient descent: how a neural network learns, Softmax: how numbers become probabilities and what temperature is, Transformer and attention: how a model knows what a word refers to, AI hallucination: why artificial intelligence confidently writes falsehoods