Backpropagation: how a neural network learns
A neural network learns by fixing its weights a little each time it is wrong. But if there are millions of weights, which one should move, which way, and by how much? Backpropagation works that out in one go. Step through the picture below, one box at a time.
Short answer. Backpropagation is a way to work out, all at once, how much the error (the loss) changes when you nudge each weight a little. That number is the gradient. First you run the math from front to back once (the forward pass). Then you start at the loss and go from back to front, multiplying and handing a gradient to each box on the way (the chain rule). Finally you move each weight a little in the opposite direction of its gradient.
Circles are values. Boxes are calculations. The green number (= …) above a circle is its value. The orange number below (grad …) is its gradient. A thick blue border marks a weight we can change. A dashed border marks given data. Solid green arrows (→) show the path values took forward. Dashed orange arrows (←) show the path gradients came back on. The box tagged "now ▾" is the one this step computes, and the bottom of the picture shows its math with real numbers (backward: gradient = gradient from behind × this box's derivative). Numbers are rounded to three digits.
| Box | Goes to | Own slope | × Gradient from behind | = Gradient handed on |
|---|
Change a starting number with its slider or box and everything is worked out again on the spot. "Update weights" works only after the backward pass is done, and each press adds a point to the loss chart. Press an example button again to get its starting numbers back. This graph is a small model, cut down so you can follow it by hand. A real neural network chains millions of the same boxes, and feeds in many data points at once instead of one.
Definitions
The text below uses the computation of one neuron, z = w·x + b, a = σ(z), L = (a − y)². These are the textbook definitions. L is the loss, and θ₁, …, θₚ are the parameters (the weights and biases).
- computational graph
- A computation drawn as a directed acyclic graph. The nodes are values or operations, and an edge shows that a value goes into an operation as input.
- partial derivative, gradient
- The partial derivative ∂L/∂w is the limit of the rate at which L changes when only w changes and every other variable stays fixed. It is what this page calls the gradient of w. The vector of the partial derivatives for all parameters is the gradient ∇L.
- chain rule
- The rule for the derivative of a composite function. When w sets z, z sets a, and a sets L, ∂L/∂w is the product of the derivatives of each step (first formula). When x reaches L through several values u₁, …, uₖ, add the products along each branch (second formula).
- forward pass
- The step that follows the computational graph from the inputs toward the loss, computing and storing the value of every node. The stored values are used in backpropagation to compute the local gradients.
- backpropagation
- The algorithm that, after the forward pass, starts from ∂L/∂L = 1 and walks the computational graph back from the loss toward the inputs, using the chain rule to get the partial derivative for every parameter. At each node it multiplies the upstream gradient coming from behind by the node's local gradient and passes the result toward the inputs. If a value was used in several places, it adds the gradients it gets.
- vanishing gradient
- In a deep network, the gradient of the early layers becomes a product of many local gradients smaller than 1 in size, so it gets close to 0 and the early weights barely change. The opposite case, where the product grows large, is the exploding gradient.
1. Why we need it: you cannot nudge the weights one by one
Training means making the loss smaller. The loss is a single number that says how far the network's answer is from the right answer. To make it smaller, you need to know this for each weight: if I raise it a little, does the loss go up or down, and how fast? That is the weight's gradient. If the gradient is negative, raise the weight. If it is positive, lower it.
The simplest way is to nudge the weights one at a time. Raise w by 0.0001, run the whole calculation again, and see how much the loss changed. With three weights, you run it three more times. But with a million weights, you would have to run it more than a million extra times just to take one step.
| Method | Work for one step with n weights |
|---|---|
| Nudge one at a time (numerical differentiation) | n extra forward passes. 2n if you nudge both ways |
| Backpropagation | One forward pass + one backward pass. The backward pass is a few multiplications per box, so it costs at most a few forward passes |
With backpropagation, the work does not grow n times when n grows. That is what makes it possible to train big neural networks.
2. Reading the computational graph
A neural network's calculation is many small calculations joined together. The basic example in the lab, "One neuron," looks like this. It has the same shape as one neuron in a neural network.
z = w·x + b multiply the input x by the weight w, then add the bias b
a = σ(z) sigmoid: squeezes any number into the range 0 to 1
L = (a − y)² loss: how far the answer a is from the right answer y
x: the input, given data.y: the right answer, given data.w: the weight the input is multiplied by, a value we will change.b: the bias, a value we will change.z: the input times the weight, plus the bias.σ: the sigmoid, which squeezes any number into the range 0 to 1.a: the answer,σ(z).L: the loss, how far the answer a is from the right answer y.
The sigmoid is σ(z) = 1 ÷ (1 + e^(−z)). When z is 0 it gives 0.5. When z is large it gets close to 1, and when z is very negative it gets close to 0.
In the picture, a circle is a value, a box is a calculation, and an arrow means "this value goes into that calculation." x and y are given data (dashed border). w and b are the weights we will change (blue border). At the start we only know x, w, b and y.
Try this. ① Press "Next step" three times and the green numbers fill in from the left: z = 0, a = 0.5, L = 0.25. ② Press four more times and the orange numbers fill in from the right, ending with ∂L/∂w = −0.5 and ∂L/∂b = −0.25. ③ Press "Update weights" and the loss drops from 0.25 to 0.0496. After five presses in total it is down to 0.0111, and the small chart below draws a falling line.
3. The chain rule: gradients link up by multiplying
A slope (a derivative) answers: "if I change the input a little, how many times as much does the output change?" (Derivatives). For example, the slope of a = σ(z) at z = 0 is 0.25. Raise z by 0.01 and a goes up by about 0.0025.
When calculations are chained, these rates multiply. If z moves a at 0.25 times the rate, and a moves L at −1 times the rate, then z moves L at 0.25 × (−1) = −0.25 times the rate. That is the chain rule.
∂L/∂z = ∂L/∂a × ∂a/∂z
Read ∂L/∂z as "how fast L changes when you change only z a little." The ∂ sign means "keep everything else fixed and change just this one." So the gradient of w is the product of every rate along the path from w to L.
∂L/∂w = ∂L/∂a × ∂a/∂z × ∂z/∂w = 2(a − y) × a(1 − a) × x
Why this is a product is built up step by step right after this section, in How the formula is built, by nudging w a little.
Backpropagation works out this product starting from the right. It starts at the far right (∂L/∂L = 1), and each time it passes a box it multiplies by that box's own slope. You get ∂L/∂a, then ∂L/∂z, and then w and b both get theirs from z. w and b share the front part of the product (∂L/∂z). Working out shared parts only once is why backpropagation is fast.
How the formula is built: the chain rule product
Here is why the formula from section 3, ∂L/∂w = ∂L/∂a × ∂a/∂z × ∂z/∂w, is a product. Nudge w a tiny bit. The nudge moves z, the change in z moves a, and the change in a moves L. Measure how many times bigger or smaller the nudge gets in each box, chain those numbers, and you have the formula. The numbers are the lab's basic example (x = 2, w = 0.5, b = −1, y = 1, so z = 0, a = 0.5, L = 0.25). Read Δw as "the change in w" (Δ is the Greek letter delta).
Press "Next" to go one step at a time. A piece is added to the formula at the top (the orange background marks the new piece), the bars grow by how much each value changed, and the reason appears next to the picture. Bar lengths use Δw = 0.001 as one unit (the ruler at the bottom), so even tiny changes show up. The blue bar is w, and the green bars are z, a and L. A bar to the right means the value went up, to the left means it went down. The orange text is each box's rate. The numbers in this picture are fixed to the basic example.
- The z box:
∂z/∂w = x. Raise w by Δw = 0.001. Inz = w·x + b, x and b stay the same, so z changes by(w + Δw)·x + b − (w·x + b) = x·Δw, which is 2 × 0.001 = 0.002. Nothing is left over: it is exactly x times. That rate is ∂z/∂w. - The a box:
∂a/∂z = a(1 − a). When z goes from 0 to 0.002, a = σ(z) goes from 0.5 to 0.5005, a change of 0.0005. That is 0.25 times 0.002. The sigmoid is curved, so its rate is different at every spot. Its rate (slope) at this spot isa(1 − a) = 0.5 × 0.5 = 0.25. We do not prove here why the sigmoid's slope is a(1 − a). Because of the curve the change is not exactly 0.25 times, but it gets closer to 0.25 times as Δz gets smaller. - The L box:
∂L/∂a = 2(a − y). When a changes by Δa, L changes by(a + Δa − y)² − (a − y)² = 2(a − y)·Δa + Δa². When Δa is small, Δa² is much smaller still (0.0005² = 0.00000025), so drop it. The rate is2(a − y) = 2 × (0.5 − 1) = −1, and ΔL ≈ −1 × 0.0005 = −0.0005. The rate is negative, so when a goes up, L goes down. - Chain them:
∂L/∂w = ∂L/∂a × ∂a/∂z × ∂z/∂w. Put the three in one after another:ΔL ≈ 2(a − y) × Δa ≈ 2(a − y) × a(1 − a) × Δz = 2(a − y) × a(1 − a) × x × Δw. Divide both sides by Δw, and "how much L changes when w changes by 1" comes out as the product of the three rates: (−1) × 0.25 × 2 = −0.5. Each box scales the nudge before it enters the next box, so the rates multiply. They do not add. As Δw shrinks toward 0, the ≈ becomes =. That is the chain rule. We do not give a full proof here. - Check by nudging:
≈ ΔL ÷ Δw. Measure it the way section 1 describes (nudge one weight). Set w to 0.501 and redo the whole calculation: z = 0.002, a = 0.5005, L = 0.24950025. So ΔL = −0.00049975, and dividing by Δw = 0.001 gives −0.49975. That is 0.00025 off from the product −0.5. Almost all of the gap is the Δa² dropped in step 3, divided by Δw (0.00000025 ÷ 0.001). With Δw = 0.0001 you get −0.499975, and the gap is 10 times smaller (0.000025). - Done:
∂L/∂w = 2(a − y) × a(1 − a) × x. In the basic example that is −0.5, the same as the hand calculation in section 5 and the lab's backward pass. If you nudge b instead of w, z moves by exactly Δb (∂z/∂b = 1), so only the last rate changes, to 1:∂L/∂b = 2(a − y) × a(1 − a) × 1 = −0.25.
4. The recipe: one forward pass, one backward pass
- Forward pass. Go left to right, work out each box's value, and keep it. The backward pass needs it again (the σ box needs a, the multiplying box needs x).
- Start. Set the gradient of the loss to 1. L changes exactly as fast as L.
- Backward pass. Go right to left. At each box, work out
gradient handed on = own slope × gradient from behindand hand it to that box's inputs. - Add. If one value went into several boxes, add up all the gradients it gets (section 6).
- Update. For each weight,
w ← w − step size × ∂L/∂w. This part is the job of gradient descent.
Each kind of box has a fixed own slope. These are all the boxes in the lab.
| Box | Calculation | Own slope |
|---|---|---|
| Multiply and add | z = w·x + b | ∂z/∂w = x, ∂z/∂b = 1, ∂z/∂x = w |
| Sigmoid σ | a = σ(z) | a(1 − a). At most 0.25 (when a = 0.5) |
| ReLU | h = relu(z) = max(0, z) | 1 if z is above 0, otherwise 0 |
| Squared error | L = (a − y)² | ∂L/∂a = 2(a − y) |
| Multiply | u·v | The other value. v for u, u for v |
| Add | w + 1 | 1. Hands the gradient on unchanged |
5. Follow along by hand
These are the lab's starting numbers: x = 2, w = 0.5, b = −1, y = 1, step size 1. Each row matches what the lab shows when you press "Next step."
| Step | Math | Result |
|---|---|---|
| Forward 1 | z = 0.5 × 2 + (−1) | 0 |
| Forward 2 | a = σ(0) | 0.5 |
| Forward 3 | L = (0.5 − 1)² | 0.25 |
| Backward start | ∂L/∂L | 1 |
| Backward 1: loss box | ∂L/∂a = 2(a − y) × 1 = 2 × (0.5 − 1) × 1 | −1 |
| Backward 2: σ box | ∂L/∂z = a(1 − a) × ∂L/∂a = 0.25 × (−1) | −0.25 |
| Backward 3: multiply-and-add box | ∂L/∂w = x × ∂L/∂z = 2 × (−0.25)∂L/∂b = 1 × ∂L/∂z | −0.5 −0.25 |
| Update | w ← 0.5 − 1 × (−0.5)b ← −1 − 1 × (−0.25) | 1 −0.75 |
| Forward again | z = 1 × 2 + (−0.75) = 1.25, a = σ(1.25) ≈ 0.7773, L = (0.7773 − 1)² | about 0.0496 |
The loss dropped from 0.25 to about 0.0496. A negative ∂L/∂w (−0.5) means "raising w lowers the loss," so w went up. We did not work out gradients for x and y. They are data, and we never change data.
6. When branches join, add
If one value is used in two places, nudging it changes the loss along both paths at once. So you add the gradients that come back along the two paths.
The lab's "Two branches" example is L = (w·x)·(w + 1). w goes into two places: u = w·x and v = w + 1. This is not a neural network loss. It is a tiny formula made only to show the adding rule. With x = 3 and w = 1: u = 3, v = 2, L = 6.
| Path | Math | What w gets |
|---|---|---|
| v side (+ 1 box) | ∂L/∂v = u = 3, ∂v/∂w = 1 | 1 × 3 = 3 |
| u side (× box) | ∂L/∂u = v = 2, ∂u/∂w = x = 3 | 3 × 2 = 6 |
| Total | 3 + 6 = 9 |
Check: L = 3w² + 3w, so the slope is 6w + 3, which is 9 at w = 1. This happens all the time in neural networks. One neuron's output feeds many neurons in the next layer, and one weight is shared by many data points.
Try this. ① Pick "Two branches" and press "Next step" to the end. First 3 appears under w (from the + 1 box). In the last step 6 is added, giving 9. ② Change w to 2: L = 18, and the gradient of w is 6 + 9 = 15. ③ In this formula L can go below 0. Press "Update weights" again and again, and w heads to −0.5 while L heads to −0.75.
7. With many layers, gradients vanish or explode
The "Two layers" example is h = relu(w₁·x + b₁), a = w₂·h + b₂, L = (a − y)². The gradient of the front layer is a product that passes through every layer behind it.
∂L/∂w₁ = 2(a − y) × w₂ × (z₁ > 0 ? 1 : 0) × x
With the starting numbers (x = 2, w₁ = 0.5, b₁ = 0.5, w₂ = 1, b₂ = −1, y = 1.5) this is (−2) × 1 × 1 × 2 = −4.
With ten or a hundred layers, this product gets very long. If most of the numbers in it are below 1, the product shrinks toward 0. This is the vanishing gradient problem. The weights in the front layers barely change, so they do not learn. The sigmoid's own slope is at most 0.25, so after ten sigmoids, even ignoring everything else, you get 0.25¹⁰ ≈ 0.00000095. If most of the numbers are above 1, the product gets huge. This is the exploding gradient problem. Multiply 2 by itself 50 times and you get more than a quadrillion (10¹⁵). The steps get so big that the weights jump somewhere useless.
| Common fix | What it does |
|---|---|
| ReLU | Its own slope is 1 on the positive side, so multiplying by it does not shrink anything. On the negative side it is 0, so that path is cut |
| Residual connection | output = input + calculation(input). An add box hands the gradient on unchanged, so there is a shortcut that skips the multiplying |
| Normalization | Keeps the values in each layer at an even size, so the numbers being multiplied do not get too big or too small (batch normalization, layer normalization) |
| Gradient clipping | If the gradient gets bigger than a set size, shrink it to that size. This stops explosions |
Try this. ① In "One neuron," set y to 0 and w to 3, then press "Run to the end." a = 0.993 is far from the right answer 0, so the loss is 0.987, yet ∂L/∂w is only 0.0264. Compared with the start (loss 0.25, gradient −0.5), the error is about 4 times bigger but the gradient is about 19 times smaller. That is because the σ box's own slope is only 0.00665. ② In "Two layers," set b₁ to −2 and press "Run to the end." z₁ = −1, so ReLU outputs 0 and its own slope is 0. The gradients of w₁ and b₁ become 0, and since h = 0, so does the gradient of w₂. Press "Update weights" and only b₂ changes (loss 6.25 → 5.06).
8. Things to know
| Property | In plain words |
|---|---|
| Gradients link up by multiplying (the chain rule) | The gradient of a value near the front is the product of the own slopes of every box on the way |
| When branches join, add | If a value is used in several places, its gradient is the sum of what comes back along each path |
| One pass forward and one pass back give every gradient | Even with many weights, the work per step is at most a few forward passes |
| The forward pass values must be kept | Own slopes need them. That is why training uses more memory than just getting answers |
| Backpropagation only finds gradients | How far to move is set by the step size. Changing the weights is the job of gradient descent |
9. Automatic differentiation: you do not write it yourself
In practice, nobody writes backpropagation by hand. Tools like PyTorch record the computational graph during the forward pass. When you call loss.backward(), they work out the gradients from back to front, just like the lab, and put each weight's gradient in its .grad. This is called automatic differentiation (reverse mode). Below is the hand example from section 5, as code.
import torch
x, y = torch.tensor(2.0), torch.tensor(1.0) # data
w = torch.tensor(0.5, requires_grad=True) # weights to change
b = torch.tensor(-1.0, requires_grad=True)
loss = (torch.sigmoid(w * x + b) - y) ** 2 # forward pass, the graph is recorded
loss.backward() # backward pass
print(w.grad, b.grad) # -0.5 and -0.25, same as section 5
with torch.no_grad(): # update the weights (step size 1)
w -= 1.0 * w.grad
b -= 1.0 * b.grad
w.grad.zero_() # gradients add up, so clear them before the next step
b.grad.zero_()
Real code calls optimizer.step() and optimizer.zero_grad() instead of the last five lines. It also bundles many data points (for example 32), averages their loss, and takes one step using the gradient of that average. Such a bundle is called a mini-batch.
How to walk downhill with these gradients (step size, momentum, Adam) is the next topic, gradient descent.
Where it is used
- Training neural networks. Photo classification, translation, speech recognition, large language models: nearly every place that trains a neural network gets its gradients from backpropagation.
- Seeing what the input did to the answer. Take the gradient with respect to the input (the pixels of a photo) instead of the weights. It shows which pixels change the answer most when nudged. People use this to look at which part of a photo a model relied on.
- Outside neural networks. The same method works for any calculation you can differentiate. Fitting the numbers in a physics simulation to measurements is one example. In engineering and weather science, the same idea is called the adjoint method.
Frequently asked questions
How is backpropagation different from gradient descent?
Backpropagation finds the gradient for each weight. Gradient descent uses those gradients to change the weights. Training repeats the two, one after the other.
Why start from the back?
Because there is one loss and many weights. Start at the loss and go backward once, and every weight gets its gradient. Start from the front and you have to make a separate trip for each weight.
How is it different from numerical differentiation?
Numerical differentiation nudges the weights one at a time and measures how much the loss changes. You have to rerun the calculation once per weight, and the answer is only approximate. Backpropagation gives exact values in one go. Numerical differentiation is used to check that backpropagation code is correct.
What happens when a gradient is 0?
That weight does not change on that step. When the path goes through a ReLU that outputs 0, or a sigmoid stuck near 0 or 1, the gradient from behind gets multiplied by 0 or something close to 0, so the weights in front of it barely learn.
Why call zero_grad() in PyTorch?
backward() does not overwrite .grad. It adds the new gradient to what is already there. So if you do not clear it every step, gradients from earlier steps keep piling up.
Words
| Words used here | Textbook names |
|---|---|
| how wrong the answer is | loss, cost, objective function |
| weight, bias | weight, bias. Together they are the parameters |
| the picture of circles, boxes and arrows | computational graph |
| working out values front to back | forward pass, forward propagation |
| handing gradients back to front | backpropagation, backward pass |
| the gradient ∂L/∂w | partial derivative. All of them together make the gradient (vector) |
| a box's own slope | local gradient |
| gradient from behind | upstream gradient |
| linking rates by multiplying | chain rule |
| step size | learning rate |
| nudging weights one at a time | numerical differentiation, finite differences |
| gradients shrinking away / blowing up | vanishing gradient / exploding gradient |
| sigmoid σ | sigmoid, logistic function |
| ReLU | rectified linear unit |
| shortcut connection | residual connection, skip connection |
| shrinking a gradient that is too big | gradient clipping |
| backpropagation done for you by the computer | automatic differentiation, reverse mode |
| a bundle of data points | mini-batch |
Sources
- Rumelhart, Hinton, Williams (1986). Learning representations by back-propagating errors. Nature 323, 533–536. The paper that made backpropagation widely known.
- Bengio, Simard, Frasconi (1994). Learning long-term dependencies with gradient descent is difficult. IEEE Transactions on Neural Networks 5(2). Vanishing gradients.
- Pascanu, Mikolov, Bengio (2012). On the difficulty of training Recurrent Neural Networks. Exploding gradients and gradient clipping.
- Glorot, Bordes, Bengio (2011). Deep Sparse Rectifier Neural Networks. ReLU.
- He, Zhang, Ren, Sun (2015). Deep Residual Learning for Image Recognition. Residual connections.
- Ioffe, Szegedy (2015). Batch Normalization. Ba, Kiros, Hinton (2016). Layer Normalization.
- Baydin, Pearlmutter, Radul, Siskind. Automatic differentiation in machine learning: a survey.
- PyTorch docs: torch.autograd, A Gentle Introduction to torch.autograd.