Introduction
A neural network is a function. You give it numbers (the pixels of an image, the words of a sentence turned into vectors, the measurements of a flower) and it gives back numbers: a prediction . The hat means predicted: the network’s answer, which we compare with the true answer .
What makes it a learning machine is that this function has knobs: thousands, sometimes billions of numbers, the weights and the biases, that decide what the function computes. We write them all in one big vector , and the network as .
Training the network means finding values of the knobs for which its predictions are close to the true answers, on examples where we know them. We measure “close” with a single number, the loss: the bigger it is, the worse the network. Training is then a minimization problem:
For a model with two knobs, like a straight line , there is a formula that gives the best directly. For a network with millions of knobs there is none. Instead, we improve the knobs a little at a time:
Each arrow answers the same question: in which direction should I turn each knob, and by how much, to lower the loss? This page builds the answer in four steps:
- The derivative tells how much a function’s output changes when you turn one knob.
- The chain rule computes that derivative for a function made of layers, which is what a network is: this is backpropagation.
- Gradient descent uses the derivative to walk downhill, one step at a time, and the learning rate sets the size of the steps.
- The gradient does the same for many knobs at once.
At the end, you will train a small model by hand, with pen and paper, and watch a real network train in your browser. All you need is to remember what a function is; section 0 recalls, quickly, the two other objects we need, vectors and matrices, and uses them to write what a network computes: the forward pass.
0. Vectors, matrices and the forward pass
0.1 Data are vectors
A vector is a list of numbers. In machine learning, every data point is one: an iris flower is the vector of its four measurements (sepal length and width, petal length and width), ; a word, for a language model, is a vector of a few hundred numbers, its embedding.
Vectors add entry by entry, and multiply by a number entry by entry. The operation that matters most is the dot product, which multiplies two vectors entry by entry and sums the results:
The length, or norm, of a vector is , and dividing the dot product by the two lengths gives the cosine similarity, the cosine of the angle between the two vectors:
It is when the vectors point the same way, when they are unrelated, when they are opposite. This is how search engines and language models compare documents or words: two vectors that point the same way mean similar things.
0.2 A layer is a matrix
A matrix of size is a table of numbers with rows and columns. Multiplied by a vector of , it gives a vector of : each entry of the result is the dot product of one row of the matrix with the vector.
The sizes must fit: an matrix times an vector gives an vector, and the two inner sizes, , must be equal.
This product is exactly what a layer of a network computes. A layer with inputs and neurons multiplies its input by a weight matrix of size , adds a bias vector , then applies an activation to each entry:
and are the knobs of the layer: with 2 inputs and 3 neurons, is and has 3 entries, so 9 knobs. A network stacks several such layers, the output of one being the input of the next.
0.3 The forward pass
Running a network on an input means computing its layers one after the other, from the input to the output: this is the forward pass. With one hidden layer and one output, it is two lines:
The hidden layer turns the input into a vector , one entry per neuron; the output layer takes a weighted sum of these entries, with no activation. The knobs of the network are .
For example, with 2 inputs, 2 hidden neurons and the activation , which keeps the positive numbers and replaces the negative ones by :
The second neuron receives a negative number and outputs : for this input, it plays no part in the prediction.
With a single input , the sizes shrink: is a column of weights , a row of weights , and a single number . The network becomes a function from to ,
and a function from to can be drawn. Do the forward pass for every and you get a curve: the shape the network draws. With ReLU, each neuron adds one bend to it, and its knobs decide where the bend is and how steep. More neurons, more bends: with enough of them, a network can draw almost any shape.
Add neurons and try to fit the orange points by hand, turning one knob at a time. Then click Let backprop fit it: the knobs that fit exist, and the rest of this page is about how to find them: the derivative, then the backward pass.
1. The derivative: what happens when you turn one knob
1.1 A rate of change
Drive 120 km in 2 hours and your average speed is 60 km/h: the change of distance divided by the change of time. Your speedometer shows something else, the speed now: the same ratio, measured over a moment so short that the speed has no time to change.
The derivative is that speedometer, for any function. Between and , the function changes by , so its average rate of change is
Make smaller and smaller. If this ratio settles on a finite value, is differentiable at , and that value is its derivative:
It is also written : a tiny change of , , divided by the tiny change of , , that caused it. On the graph of , it is the slope of the tangent at .
For , with :
So , at every point: the derivative is itself a function, .
1.2 In practice: a table and a few rules
Nobody computes limits by hand every time. We use a table for the usual functions, and rules to combine them.
| (a constant) | |
| Rule | |
|---|---|
| sum | |
| constant factor | |
| product |
The sign of says which way the function goes at : up if it is positive, down if it is negative. Its size says how fast. Keep this in mind: it is all a computer needs to find which way is down.
Optional How does a computer compute a derivative?: finite differences or automatic differentiation
Give a computer a function, say y = 3 * x**2 + x. It can estimate in two ways.
Numerically, with finite differences: compute with a small , like . It is simple, but only approximate, and it needs one extra evaluation of the function per knob: far too many for a network.
Exactly, with automatic differentiation: the computer records every operation it makes (, , powers, …) and applies the table and the rules above to each one. This is what PyTorch does when you call loss.backward(), and the next section explains how it chains the steps.
Exercise 1.2 Basic derivatives
Differentiate:
- (product rule)
Hint
Differentiate each term separately (sum rule), keeping the constant factors in front: .
Hint
For question 4, set and , then .
Checkpoint what you should get
At , the four derivatives are , , and .
Solution
- , for
2. The chain rule: derivatives through the layers
2.1 A network is a chain of functions
Each layer of a network is a function: it takes the output of the previous layer and computes its own. The network is the composition of its layers,
with applied first. To train it, we need the derivative of such a composed function, and the table of section 1 has no line for it. The chain rule fills the gap. For two functions:
In words: the derivative of the inside, times the derivative of the outside evaluated at the inside.
For example, is three layers: , then , then . One factor per layer, each evaluated at the input of its layer:
2.2 With n layers: forward, then backward
Name the intermediate values of a chain of layers: , , …, . The chain rule gives
The order of the computation follows: first go forward and compute every (the forward pass of section 0.3), since each factor needs the input of its layer; then go backward, from the output to the input, multiplying the factors as you go. Every layer reuses the product computed by the layer after it: nothing is computed twice.
2.3 Backpropagation
Now the knobs. The loss compares the prediction with the true answer, for example , and depends on every weight. To know which way to turn one weight , keep all the others fixed and look at how the loss changes:
The round instead of says that we differentiate with respect to one variable, the others being fixed: a partial derivative, more in section 4. Its sign says in which direction the loss changes when goes up; its size says by how much.
Try it on a network with a single knob: with , , and . Turning the knob by hand from to moves from to and the loss from to : a rate of change of . The chain rule gives the same number, exactly and without trying:
The derivative is positive: turning up makes the loss worse, so we should turn it down, in the direction opposite to the derivative.
Backpropagation is this computation done for every weight of a network at once: the chain rule applied recursively, from the loss back to each parameter. One forward pass computes the prediction and the loss; one backward pass gives the derivative of the loss with respect to every weight.
Step backward one node at a time and read the orange numbers: each one is the number on its right times the derivative of one operation. Then click Gradient step: every weight moves against its derivative, and the loss goes down.
Exercise 2.3a Backprop in 2 layers
A tiny network with one neuron per layer and no activation:
with , (the true answer), and .
- Forward: compute , and the loss.
- Backward: compute , then and .
- Compute .
- To reduce the loss, should you turn up or down? And ?
Hint
with , so .
Hint
Question 3 reuses from question 2: this reuse is what makes backpropagation cheap.
Checkpoint what you should get
The loss is , and the two derivatives with respect to the weights are and .
Solution
- , , .
- , , .
- .
- Both derivatives are positive: turning a weight up increases the loss. Turn both down.
The prediction is too big compared with , so both weights should shrink. But the loss is three times more sensitive to than to : a step against the derivative moves three times more.
Exercise 2.3b Activation layers
Between the weighted sums, a network applies an activation, a simple function of one number. The two classics:
- Compute and .
- What is for negative? For positive?
- Let . With the chain rule, compute and .
- Compute . Check that , then compute .
Hint
ReLU is on the left of and on its right: two straight lines, so two constant slopes.
Hint
For question 4, write with , and use .
Checkpoint what you should get
and ; and .
Solution
- , .
- for negative, for positive.
- : , .
- . With :
When the input of a ReLU is negative, its derivative is : the backward pass stops there, and the weights before it do not move. This is the “dead neuron” you can see in the Space above.
At exactly, ReLU has no derivative: the slope jumps from to . What do you think libraries like PyTorch do there?
3. Walking downhill: gradient descent
3.1 Where is the minimum?
At the bottom of a valley, the ground is flat: at a minimum of a smooth function, the tangent is horizontal and . So the solutions of are the candidates. Only candidates, though: , and all have , and the first one has no extremum at , it only pauses before going up again.
A minimum can also be local (the lowest point around it) or global (the lowest point everywhere). A curve with two valleys has two local minima, and only the deeper one is global.
Optional Sorting the candidates: sign tables and the second derivative
With the expression of , there are two classic ways to tell a minimum from a maximum.
The sign table of . If goes from negative to positive at the candidate, goes down then up: a minimum. From positive to negative: a maximum. No change of sign: no extremum, as for whose derivative is never negative.
The second derivative, , the derivative of . It says whether the curve bends up, , convex, when , or down, , concave, when . At a candidate :
- and : a local minimum;
- and : a local maximum;
- and : we don’t know.
For , is positive everywhere: the minimum at is global. Convexity around a point gives a local extremum; convexity everywhere gives the global one.
All of this needs the expression of , and equations we can solve. The loss of a network has millions of variables, and no one can solve for it. We need a method that only looks at the function where we are.
3.2 One step at a time
Stand on a hillside in the fog. You can’t see the valley, but you can feel the slope under your feet, so you take a step downhill, feel the slope again, take another step. The derivative is that slope: if , the function goes up to the right, so the way down is to the left; if , it is to the right. In both cases, move against the sign of the derivative:
This is gradient descent. The number is the learning rate, or step size: it sets how far each step goes. And since is large where the slope is steep and small near the bottom, the steps shrink by themselves as we get closer: the tangent gives the direction and the magnitude of the step.
The learning rate is the one choice gradient descent leaves to you, and it matters. Play with it on the simplest valley, :
A too large jumps over the minimum, and can even diverge. A too small converges, but needs a large number of steps. For a network, each step costs a forward and a backward pass over the data, so the number of steps is the cost of training: choosing is a real trade-off, and much of practical deep learning is about it.
Gradient descent gets to a local minimum: the bottom of the valley it starts in, not necessarily the deepest one. The animation at the top of this page shows it: the point stops in the first valley it meets.
Exercise 3.2 Extrema by hand, then one step downhill
Let .
- Compute and find the candidate extrema.
- Compute . Use it to say which candidate is a minimum and which is a maximum.
- Are they global extrema? Look at when and .
- Start at and do two steps of gradient descent with . Which candidate are you heading to?
Hint
factors as .
Hint
For question 4, apply twice, with .
Checkpoint what you should get
Candidates and ; and .
Solution
- : candidates and .
- : , a maximum, ; , a minimum, .
- No: when and when . They are local extrema only.
- , then and : heading to the local minimum at .
The second step is ten times smaller than the first, with the same : the slope flattens near the minimum, and the steps shrink with it. From , the same steps would run towards , since there is no valley on that side.
4. Many knobs at once: the gradient
4.1 Functions of several variables
A loss depends on all the knobs of the network, so we need functions of several variables. A function from to takes numbers and returns :
- , from to ;
- , from to ;
- , from to : each output, and , is a function of all the inputs.
The names of the variables don’t matter: , and are the same kind of function, and , with in bold, means that the input is a vector. From now on we focus on functions from to : many numbers in, a single number out, like a loss.
4.2 Partial derivatives
The partial derivative is the derivative of with respect to , the other variables being fixed: turn the knob only, and watch . In practice, treat every other variable as a constant and differentiate as usual, term by term:
and in the same way and . Read as how much changes when changes.
The chain rule works with partial derivatives too. With and :
4.3 The gradient
Put all the partial derivatives in one vector, and you get the gradient:
One entry per variable, so a vector of size . The gradient is itself a function, from to : at each point , it gives the vector , which points in the direction where increases the fastest. For the bowl , points away from the bottom, uphill, everywhere.
Gradient descent in several variables is the same rule as in section 3, with vectors. Each step goes against the gradient:
On the bowl , every step points straight at the centre, and the steps converge to , the minimum.
Exercise 4.3 Partial derivatives and one step in 2D
- Let . Compute , , then .
- Let . Compute .
- Start at and do one step of gradient descent on with .
- Compute before and after the step. Where is the minimum of ?
Hint
For , is a constant: is ” times ”, whose derivative is .
Hint
A step in 2D is two steps in 1D done at the same time, one per coordinate: , and the same for .
Checkpoint what you should get
; after the step, and went from to .
Solution
- ( fixed), ( fixed), .
- .
- , so .
- and : the step lowered . The minimum is at , where .
The step went from to : straight towards the centre, halving the distance. On this bowl, halves the distance at every step.
5. Training a network
5.1 The training loop
Everything is in place. Put all the weights and all the biases of the network in one vector, , and train it by gradient descent on the loss:
where the gradient, one partial derivative per knob, is computed by backpropagation: the chain rule on all the layers. One step of training is always the same three moves:
- Forward: compute the predictions and the loss.
- Backward: compute , the derivative of the loss with respect to every parameter.
- Step: move every parameter against its derivative, .
Repeat until the loss stops going down.
5.2 Watch a network train
The Space below is a network with one hidden layer, learning a function from examples. Each step of gradient descent moves every weight and every bias by : watch the curve fit the points, and the loss go down.
5.3 Train one by hand
Training a network by hand is long, but training the smallest model is not. Take two examples, and , and the model : a straight line, with two knobs, and . The loss is the sum of the squared errors on the two examples:
Exercise 5.3 Linear regression by gradient descent
- Compute .
- Compute ( fixed) and ( fixed). Evaluate them at .
- Do one step of gradient descent from with , and compute the new loss.
- Which line goes through both points? What are , and for this line?
Hint
The first term, , does not contain : its partial derivative with respect to is .
Hint
Chain rule on the second term: .
Checkpoint what you should get
, , and after one step the loss is .
Solution
- .
- and . At : and .
- , . Then , down from .
- The line : , and , the global minimum. Each step of gradient descent gets closer to it.
Both derivatives were negative, so both knobs went up: the line was too low everywhere. And moved more than , because it changes the predictions on both examples, while only changes the second one.
For a straight line, we did not need gradient descent: least squares gives the best with a formula, , a closed-form solution. That is exactly what a network does not have, and why the whole of section 3 was needed.
6. Recap
- The forward pass computes the prediction layer by layer, : matrices, then an activation. With enough neurons, a network can draw almost any shape.
- The derivative is the slope of the tangent: how much a function changes when its input changes. Its sign says which way is up.
- The chain rule differentiates a chain of functions, one factor per layer. Applied from the loss back to every weight, it is backpropagation: one forward pass, one backward pass.
- Gradient descent walks downhill, , to a local minimum. The learning rate must be neither too large (oscillations, divergence) nor too small (too many steps).
- A partial derivative turns one knob with the others fixed; the gradient collects them in a vector that points uphill.
- Training a network is gradient descent on the loss, with backpropagation to compute the gradient: .