Level 3 In-Depth AI · Deep Learning
Backpropagation
The algorithm that computes how much every weight in a network contributed to the error, all in one backward sweep. Worked here number by number on a tiny network, then checked against PyTorch.
- Level
- ●●●●● Intermediate
- Reading
- 17 min
- To learn it well
- 1.5 hours to read, an afternoon to practise
- Builds on
- 15 concepts →
- Quiz
- 5 questions ↓
The full path from zero — 15 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- The Chain Rule
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Backpropagation
Read them roughly in this order. See it on the concept map →
Why it matters
Gradient descent trains a model by nudging every parameter a little in the direction that reduces the loss. To do that it needs the gradient: for every single weight, how much the loss would change if that weight changed slightly. A modern language model has billions of weights. Computing each of their gradients separately would take billions of passes through the network for every training step. Training would never finish.
Backpropagation computes all of those gradients in one backward sweep through the network, at a cost of only about twice a normal forward pass. It is the reason deep learning is possible at all. Every time you see loss.backward() in PyTorch, backpropagation is running. It trained the image classifiers, the speech recognisers and the GPT models, and nothing better has replaced it.
The idea is just the chain rule from calculus, applied carefully and in the right order. This chapter works through it number by number on a tiny network, so you can see every step, and then checks the result against PyTorch.
The intuition
Imagine a factory line that makes a product in stages. At the end, a quality inspector measures how far off the final product is. The manager wants to know how much each worker along the line contributed to the error, so each can adjust.
The efficient way is to pass blame backwards. The inspector tells the last worker, "the product was this far off, in this direction". The last worker knows how their own output affects the final product, so they can work out their share, and also tell the worker before them how their output affected things. Each worker only needs two pieces of information: the blame message that arrives from the next stage, and how their own step responds to its input. They multiply the two and pass the result back.
That is backpropagation. The network's forward pass is the assembly line. The loss is the inspector. The backward pass sends an "error signal" from the loss back through each layer. At each step it is multiplied by a local gradient, the slope of that one small operation. No step ever needs to see the whole network.
Key idea Backpropagation applies the chain rule backwards through the network. Each operation multiplies the gradient arriving from above by its own local slope and passes the result down. One backward pass gives the gradient of the loss with respect to every parameter.
How it works
Networks as computation graphs
Any network calculation can be drawn as a computation graph: boxes for simple operations (add, multiply, sigmoid, square) and arrows showing which results feed into which. The forward pass computes the values from left to right. The backward pass computes the gradients from right to left.
Write for "how much the loss changes per unit change in the value ". The symbol marks a partial derivative. The whole backward pass rests on one rule:
In words: the gradient flowing out of a node towards its input equals the gradient arriving at its output (the upstream gradient) times the node's own slope (the local gradient). That's the chain rule. Three special cases come up constantly:
- Addition has slope 1 with respect to each input, so it passes the upstream gradient unchanged to both.
- Multiplication has slope with respect to and slope with respect to . So each input gets the upstream gradient times the other input.
- Branching. When a value feeds into several places, its gradient is the sum of the gradients coming back from each place. A small change in it affects the loss through every path.
The tiny network
Here is the network we'll work through. It has two inputs, two hidden neurons with sigmoid activations, and one output neuron with no activation, since it predicts a number. The loss is the squared error.
The symbols: is the input, and are the hidden layer's weights and biases, the hidden weighted sums, the sigmoid, the hidden activations, and the output neuron's weights and bias, the prediction, the target and the loss.
The values we'll use:
That's 9 parameters in total: 4 in , 2 in , 2 in and 1 in .
Forward pass, every number
Step 1. Hidden weighted sums. Each row of times , plus a bias:
Step 2. Hidden activations. Apply :
Step 3. Output.
Step 4. Loss. The target is 1, so the network is far too low:
Keep every intermediate value. The backward pass needs them.
Backward pass, every number
We start at the end. The gradient of the loss with respect to itself is 1. Then we walk backwards, one node at a time, applying the rule downstream = upstream × local slope.
Step 5. Through the loss. , so the local slope is :
The sign makes sense. The gradient is negative, which means increasing would decrease the loss. The prediction is too low.
Step 6. Output weights and bias. . By the multiply rule, each weight's gradient is the upstream gradient times the input it multiplies. By the add rule, the bias gets the upstream gradient unchanged:
Step 7. Back into the hidden activations. Same multiply rule, but now we want the gradient for the other input, , so we multiply by the weight:
Look at the signs. Raising would lower the loss, because it connects to the output with a positive weight. Raising would raise the loss, because its weight is negative.
Step 8. Through the sigmoids. The sigmoid's slope is , which we can compute from the stored activations:
Multiply by the upstream gradients:
Notice the sigmoid cut each gradient to about a quarter. Its slope is never more than 0.25. Stack many sigmoid layers and the gradient shrinks at each one. That is the vanishing gradient problem in miniature.
Step 9. Hidden weights and biases. . Each weight's gradient is times the input it multiplies. Each bias gets unchanged:
That's all 9 gradients. Collected:
| Parameter | Value | Gradient |
|---|---|---|
| 0.1, 0.2 | −0.1072, −0.2144 | |
| −0.3, 0.4 | 0.1267, 0.2534 | |
| 0.0, 0.1 | −0.2144, 0.2534 | |
| 0.5, −0.6 | −0.9792, −1.0217 | |
| 0.2 | −1.7418 |
If you needed the gradient with respect to the inputs, say for Adversarial Examples, one more step gives it. Since feeds both hidden neurons, the branch rule sums two contributions: .
One gradient-descent step
Now use the gradients. With learning rate , every parameter moves by times its gradient. For example goes from to , and goes from to . Run the forward pass again with all nine updated parameters and the loss falls from 0.7584 to 0.3223. One step, and the error has more than halved.
The general recipe
The same steps, written for whole layers at once, work for any size of network. Use ("delta") for the gradient of the loss with respect to a layer's weighted sums , often called the layer's error signal. For a layer whose input is , followed by an activation :
- Gradient for the weights: (each weight gets its row's times its column's input).
- Gradient for the biases: .
- Gradient passed to the layer below: .
- Through the activation below: , where means multiply element by element.
Steps 1 and 3 are just the multiply rule written for matrices, and step 4 is the "multiply by the local slope" rule. In batch form, with examples as the rows of , step 1 becomes dW = X.T @ dZ. That's exactly the line you saw in the XOR code in Neural Networks.
Why it is efficient
There is a naive way to get gradients: nudge one weight by a tiny amount , run the network again, and see how much the loss changes. For our 9 parameters that's 18 extra forward passes (nudging each one up and down). For a model with a billion parameters it is two billion forward passes per training step.
Backpropagation gets every gradient for roughly the cost of two more forward passes. The trick is reuse. The gradient was computed once and then shared by every parameter below it. In a deep network, each layer's is computed once and reused by all the weights in that layer and all the layers below. This style of computing derivatives, sweeping backwards from one output to all inputs, is called reverse-mode differentiation. It suits neural networks perfectly, because they have millions of inputs (the parameters) and one output (the loss).
The price is memory. The backward pass needs the values from the forward pass, such as and for the sigmoid slopes, so every intermediate activation must be stored until the backward pass reaches it. For large models, these stored activations often take more memory than the weights. A trick called activation checkpointing saves memory by storing only some activations and recomputing the rest during the backward pass.
Automatic differentiation
Nobody writes backward passes by hand for real networks. Libraries such as PyTorch, JAX and TensorFlow do automatic differentiation: as your code runs the forward pass, the library records each operation in a computation graph. Each operation type knows its own local derivative. When you call loss.backward(), the library walks the recorded graph in reverse, applying exactly the rules above. The Build an Autograd Engine from Scratch chapter builds a small version of this in about 100 lines.
In code
The full worked example in NumPy, forward and backward by hand:
import numpy as np
sigmoid = lambda z: 1 / (1 + np.exp(-z))
# The tiny network and one training example
x = np.array([0.5, 1.0]) # input
y = 1.0 # target
W1 = np.array([[0.1, 0.2], [-0.3, 0.4]]) # hidden layer: 2 neurons x 2 inputs
b1 = np.array([0.0, 0.1])
w2 = np.array([0.5, -0.6]) # output neuron: 2 weights
b2 = 0.2
# ---- forward pass
z1 = W1 @ x + b1 # hidden weighted sums
h = sigmoid(z1) # hidden activations
yhat = w2 @ h + b2 # output (no activation: regression)
L = (yhat - y) ** 2 # squared error
# ---- backward pass: chain rule, from the loss back to every parameter
dyhat = 2 * (yhat - y) # dL/dyhat
dw2 = dyhat * h # dL/dw2
db2 = dyhat # dL/db2
dh = dyhat * w2 # dL/dh
dz1 = dh * h * (1 - h) # dL/dz1 (sigmoid slope is h(1-h))
dW1 = np.outer(dz1, x) # dL/dW1
db1 = dz1 # dL/db1
np.set_printoptions(precision=4, suppress=True)
print("z1", z1, " h", h, " yhat", round(yhat, 4), " L", round(L, 4))
print("dyhat", round(dyhat, 4), " dw2", dw2, " db2", round(db2, 4))
print("dh", dh, " dz1", dz1)
print("dW1", dW1.ravel(), " db1", db1)
# z1 [0.25 0.35] h [0.5622 0.5866] yhat 0.1291 L 0.7584
# dyhat -1.7418 dw2 [-0.9792 -1.0217] db2 -1.7418
# dh [-0.8709 1.0451] dz1 [-0.2144 0.2534]
# dW1 [-0.1072 -0.2144 0.1267 0.2534] db1 [-0.2144 0.2534]
The same network in PyTorch, where L.backward() does the whole backward pass. The numbers match to four decimal places:
import torch
x = torch.tensor([0.5, 1.0])
y = torch.tensor(1.0)
W1 = torch.tensor([[0.1, 0.2], [-0.3, 0.4]], requires_grad=True)
b1 = torch.tensor([0.0, 0.1], requires_grad=True)
w2 = torch.tensor([0.5, -0.6], requires_grad=True)
b2 = torch.tensor(0.2, requires_grad=True)
h = torch.sigmoid(W1 @ x + b1)
yhat = w2 @ h + b2
L = (yhat - y) ** 2
L.backward() # autograd does the whole backward pass
torch.set_printoptions(precision=4)
print("L", L.item())
print("dW1", W1.grad.flatten(), " db1", b1.grad)
print("dw2", w2.grad, " db2", b2.grad)
# one gradient-descent step with learning rate 0.1, then re-run the forward pass
with torch.no_grad():
for p in [W1, b1, w2, b2]:
p -= 0.1 * p.grad
print("loss after one step", ((w2 @ torch.sigmoid(W1 @ x + b1) + b2 - y) ** 2).item())
# L 0.7584359049797058
# dW1 tensor([-0.1072, -0.2144, 0.1267, 0.2534]) db1 tensor([-0.2144, 0.2534])
# dw2 tensor([-0.9792, -1.0217]) db2 tensor(-1.7418)
# loss after one step 0.32231730222702026
Gradient checking confirms a hand-written backward pass by comparing it with the slow nudge-and-measure method. It is the standard way to test new layers:
import numpy as np
sigmoid = lambda z: 1 / (1 + np.exp(-z))
x = np.array([0.5, 1.0]); y = 1.0
params = {"W1": np.array([[0.1, 0.2], [-0.3, 0.4]]), "b1": np.array([0.0, 0.1]),
"w2": np.array([0.5, -0.6]), "b2": np.array(0.2)}
def loss(p):
h = sigmoid(p["W1"] @ x + p["b1"])
return (p["w2"] @ h + p["b2"] - y) ** 2
# numerical gradient: nudge each parameter up and down by a tiny eps
eps = 1e-5
for name, p in params.items():
grad = np.zeros_like(p)
for i in np.ndindex(p.shape):
old = p[i]
p[i] = old + eps; up = loss(params)
p[i] = old - eps; down = loss(params)
p[i] = old
grad[i] = (up - down) / (2 * eps)
print(name, np.round(grad.ravel(), 4))
# W1 [-0.1072 -0.2144 0.1267 0.2534]
# b1 [-0.2144 0.2534]
# w2 [-0.9792 -1.0217]
# b2 [-1.7418]
All three methods agree.
Common pitfalls
- Forgetting to zero gradients. PyTorch adds new gradients to
.gradon everybackward()call, so that gradients from several branches or batches can accumulate. If you don't calloptimizer.zero_grad()each step, you're descending along the sum of all past gradients. - Modifying tensors in place that autograd still needs. Operations like
h += 1orrelu_(...)can overwrite a value the backward pass stored. PyTorch usually raises an error about "a variable needed for gradient computation has been modified by an inplace operation". - Breaking the graph. Converting to NumPy, calling
.item(), or using.detach()in the middle of a computation cuts the graph. Gradients simply stop flowing through that path, often with no error. - Running out of memory. Memory grows with batch size and depth because every activation is stored for the backward pass. During evaluation, wrap code in
torch.no_grad()so nothing is stored. - Trusting a hand-written backward pass without a gradient check. Sign errors and missing transposes are easy to make and give gradients that are almost right, which train badly rather than not at all.
Watch out When gradients look wrong, check their size layer by layer. Gradients that shrink towards zero in early layers signal Vanishing and Exploding Gradients. Gradients that grow huge or become
nansignal exploding gradients. Both are properties of the network, not bugs in backpropagation, and have their own fixes.
Where it leads
- Vanishing and Exploding Gradients: what happens when the chain of local slopes multiplies to almost zero, or to something huge.
- Optimizers: SGD, Momentum and Adam: what to do with the gradients once you have them. Momentum and Adam improve on the plain update.
- Weight Initialization and Normalization Layers: BatchNorm and LayerNorm: keeping the signals in the forward and backward passes at a healthy size.
- Build an Autograd Engine from Scratch: build your own automatic differentiation engine.
- Recurrent networks use the same algorithm on a graph unrolled through time, called backpropagation through time.
A bit of history
The mathematics of propagating derivatives backwards appeared several times before it reached neural networks. Control engineers such as Henry Kelley (1960) and Arthur Bryson (1961) used related ideas to optimise rocket trajectories. In 1970, the Finnish student Seppo Linnainmaa described reverse-mode automatic differentiation in his master's thesis, the general algorithm behind modern autograd. Paul Werbos proposed using it to train neural networks in his 1974 PhD thesis.
The idea became widely known in 1986, when David Rumelhart, Geoffrey Hinton and Ronald Williams published "Learning representations by back-propagating errors" in Nature. They showed that the hidden units of networks trained this way learned meaningful internal features, which convinced many researchers that multi-layer networks were practical. Automatic differentiation libraries such as Theano (late 2000s), and later TensorFlow (2015) and PyTorch (2017), made backpropagation a single function call. In 2018, Hinton shared the Turing Award with Yoshua Bengio and Yann LeCun for their work on deep learning.
Try it
- Redo the forward and backward pass by hand with target instead of 1. Which gradients change sign? Check your answers by editing the NumPy code.
- Replace the hidden sigmoid with ReLU. What is the local slope at and ? Recompute and . Are they larger or smaller than with sigmoid?
- Harder: write the backward pass for a batch of examples, with
Xof shape (N, 2), and check it against PyTorch for N = 4 random inputs.Hint for 2: ReLU's slope is 1 for any positive input, so the gradient passes through the hidden layer unchanged.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Neural Networks (video series)
Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.
Neural Networks: Zero to Hero
A video series that builds backprop, language models and finally GPT from an empty file. Many people consider it the best way to really understand LLMs.
micrograd
A tiny autograd engine in about 100 lines. Reading it is the best way to demystify backprop.
Calculus on Computational Graphs: Backpropagation
A short, beautifully drawn essay showing how the chain rule on a graph of operations becomes backpropagation.
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
Yes you should understand backprop
A short essay on why practitioners must understand the backward pass, with concrete failure cases: saturated sigmoids, dead ReLUs and exploding gradients in RNNs.
Learning representations by back-propagating errors
The paper that popularised backpropagation for training multi-layer networks.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/backpropagation.md