◆ AI All-in-One

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
↗ Plan a path here

Read first

Neural NetworksThe Chain RuleGradient Descent

This leads to

Normalization Layers: BatchNorm and LayerNormOptimizers: SGD, Momentum and AdamVanishing and Exploding GradientsWeight InitializationBuild an Autograd Engine from ScratchPyTorch
The full path from zero — 15 concepts before this one
  1. What Is AI?
  2. Vectors
  3. Derivatives and Slopes
  4. Probability Basics
  5. How Machines Learn
  6. Partial Derivatives and Gradients
  7. Matrices and Matrix Multiplication
  8. The Chain Rule
  9. Supervised, Unsupervised and Reinforcement Learning
  10. Gradient Descent
  11. Supervised Learning
  12. Linear Regression
  13. The Perceptron
  14. Logistic Regression
  15. Neural Networks
  16. 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 ∂L∂v\frac{\partial L}{\partial v} for "how much the loss LL changes per unit change in the value vv". The symbol ∂\partial marks a partial derivative. The whole backward pass rests on one rule:

∂L∂input=∂L∂output×∂ output∂ input\frac{\partial L}{\partial \text{input}} = \frac{\partial L}{\partial \text{output}} \times \frac{\partial\, \text{output}}{\partial\, \text{input}}

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:

Any node: multiply by the local slope downstream = upstream × local slope Add: passes the gradient unchanged ŷ = (w₂·h) + b₂, so ∂L/∂b₂ = ∂L/∂ŷ Multiply: each input gets the other ∂L/∂w = g·h, ∂L/∂h = g·w Branch: gradients from each use add up x₁ feeds both hidden neurons σ z₁ = 0.25 h₁ = 0.5622 −0.8709 −0.2144 local slope h₁(1 − h₁) = 0.2461 −0.8709 × 0.2461 = −0.2144 + w₂·h = −0.0709 gets −1.7418 b₂ = 0.2 gets −1.7418 ŷ = 0.1291 g = −1.7418 × w = 0.5 gets −0.9792 h₁ = 0.5622 gets −0.8709 w·h₁ = 0.2811 g = −1.7418 −1.7418 × 0.5622 = −0.9792 · −1.7418 × 0.5 = −0.8709 x₁ z₁ z₂ 0.1 × −0.2144 = −0.0214 −0.3 × 0.2534 = −0.0760 sum: −0.0975
Fig. 1 The rules of the backward pass, with numbers from the worked example below. Any node multiplies the upstream gradient by its local slope. An addition passes the gradient unchanged to every input. A multiplication sends each input the gradient times the other input. A value used in several places sums the gradients from each use.
  • Addition c=a+bc = a + b has slope 1 with respect to each input, so it passes the upstream gradient unchanged to both.
  • Multiplication c=a×bc = a \times b has slope bb with respect to aa and slope aa with respect to bb. 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.

z=W1x+b1,h=σ(z),y^=w2⋅h+b2,L=(y^−y)2\mathbf{z} = \mathbf{W}_1 \mathbf{x} + \mathbf{b}_1, \qquad \mathbf{h} = \sigma(\mathbf{z}), \qquad \hat{y} = \mathbf{w}_2 \cdot \mathbf{h} + b_2, \qquad L = (\hat{y} - y)^2

The symbols: x\mathbf{x} is the input, W1\mathbf{W}_1 and b1\mathbf{b}_1 are the hidden layer's weights and biases, z\mathbf{z} the hidden weighted sums, σ\sigma the sigmoid, h\mathbf{h} the hidden activations, w2\mathbf{w}_2 and b2b_2 the output neuron's weights and bias, y^\hat{y} the prediction, yy the target and LL the loss.

The values we'll use:

x=(0.51.0),W1=(0.10.2−0.30.4),b1=(0.00.1),w2=(0.5−0.6),b2=0.2,y=1\mathbf{x} = \begin{pmatrix} 0.5 \\ 1.0 \end{pmatrix}, \quad \mathbf{W}_1 = \begin{pmatrix} 0.1 & 0.2 \\ -0.3 & 0.4 \end{pmatrix}, \quad \mathbf{b}_1 = \begin{pmatrix} 0.0 \\ 0.1 \end{pmatrix}, \quad \mathbf{w}_2 = \begin{pmatrix} 0.5 \\ -0.6 \end{pmatrix}, \quad b_2 = 0.2, \quad y = 1

That's 9 parameters in total: 4 in W1\mathbf{W}_1, 2 in b1\mathbf{b}_1, 2 in w2\mathbf{w}_2 and 1 in b2b_2.

x₁ 0.5 x₂ 1.0 z₁ 0.25 ∂L/∂z₁ = −0.2144 z₂ 0.35 ∂L/∂z₂ = 0.2534 h₁ = σ(z₁) 0.5622 ∂L/∂h₁ = −0.8709 h₂ = σ(z₂) 0.5866 ∂L/∂h₂ = 1.0451 ŷ 0.1291 ∂L/∂ŷ = −1.7418 L = (ŷ − y)² 0.7584 ∂L/∂L = 1 W₁ = [0.1 0.2; −0.3 0.4] b₁ = (0, 0.1) w₂ = (0.5, −0.6) b₂ = 0.2 · target y = 1 forward pass: compute values (black) backward pass: compute ∂L/∂(each value) (red) weight gradients: ∂L/∂W₁ = [−0.1072 −0.2144; 0.1267 0.2534] · ∂L/∂w₂ = (−0.9792, −1.0217) · ∂L/∂b₂ = −1.7418
Fig. 2 The tiny network as a computation graph. Forward values are written inside each box. The backward pass fills in the red gradients from right to left, starting from ∂L/∂L = 1 at the loss.

Forward pass, every number

Step 1. Hidden weighted sums. Each row of W1\mathbf{W}_1 times x\mathbf{x}, plus a bias:

z1=0.1×0.5+0.2×1.0+0.0=0.05+0.20=0.25z_1 = 0.1 \times 0.5 + 0.2 \times 1.0 + 0.0 = 0.05 + 0.20 = 0.25
z2=−0.3×0.5+0.4×1.0+0.1=−0.15+0.40+0.10=0.35z_2 = -0.3 \times 0.5 + 0.4 \times 1.0 + 0.1 = -0.15 + 0.40 + 0.10 = 0.35

Step 2. Hidden activations. Apply σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}):

h1=σ(0.25)=11+e−0.25=11+0.7788=0.5622h_1 = \sigma(0.25) = \frac{1}{1 + e^{-0.25}} = \frac{1}{1 + 0.7788} = 0.5622
h2=σ(0.35)=11+e−0.35=11+0.7047=0.5866h_2 = \sigma(0.35) = \frac{1}{1 + e^{-0.35}} = \frac{1}{1 + 0.7047} = 0.5866

Step 3. Output.

y^=0.5×0.5622+(−0.6)×0.5866+0.2=0.2811−0.3520+0.2=0.1291\hat{y} = 0.5 \times 0.5622 + (-0.6) \times 0.5866 + 0.2 = 0.2811 - 0.3520 + 0.2 = 0.1291

Step 4. Loss. The target is 1, so the network is far too low:

L=(0.1291−1)2=(−0.8709)2=0.7584L = (0.1291 - 1)^2 = (-0.8709)^2 = 0.7584

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. L=(y^−y)2L = (\hat{y} - y)^2, so the local slope is 2(y^−y)2(\hat{y} - y):

∂L∂y^=2×(0.1291−1)=2×(−0.8709)=−1.7418\frac{\partial L}{\partial \hat{y}} = 2 \times (0.1291 - 1) = 2 \times (-0.8709) = -1.7418

The sign makes sense. The gradient is negative, which means increasing y^\hat{y} would decrease the loss. The prediction is too low.

Step 6. Output weights and bias. y^=w2,1h1+w2,2h2+b2\hat{y} = w_{2,1} h_1 + w_{2,2} h_2 + b_2. 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:

∂L∂w2,1=−1.7418×h1=−1.7418×0.5622=−0.9792\frac{\partial L}{\partial w_{2,1}} = -1.7418 \times h_1 = -1.7418 \times 0.5622 = -0.9792
∂L∂w2,2=−1.7418×h2=−1.7418×0.5866=−1.0217\frac{\partial L}{\partial w_{2,2}} = -1.7418 \times h_2 = -1.7418 \times 0.5866 = -1.0217
∂L∂b2=−1.7418\frac{\partial L}{\partial b_2} = -1.7418

Step 7. Back into the hidden activations. Same multiply rule, but now we want the gradient for the other input, hh, so we multiply by the weight:

∂L∂h1=−1.7418×w2,1=−1.7418×0.5=−0.8709\frac{\partial L}{\partial h_1} = -1.7418 \times w_{2,1} = -1.7418 \times 0.5 = -0.8709
∂L∂h2=−1.7418×w2,2=−1.7418×(−0.6)=1.0451\frac{\partial L}{\partial h_2} = -1.7418 \times w_{2,2} = -1.7418 \times (-0.6) = 1.0451

Look at the signs. Raising h1h_1 would lower the loss, because it connects to the output with a positive weight. Raising h2h_2 would raise the loss, because its weight is negative.

Step 8. Through the sigmoids. The sigmoid's slope is σ′(z)=σ(z)(1−σ(z))=h(1−h)\sigma'(z) = \sigma(z)(1 - \sigma(z)) = h(1 - h), which we can compute from the stored activations:

h1(1−h1)=0.5622×0.4378=0.2461,h2(1−h2)=0.5866×0.4134=0.2425h_1(1 - h_1) = 0.5622 \times 0.4378 = 0.2461, \qquad h_2(1 - h_2) = 0.5866 \times 0.4134 = 0.2425

Multiply by the upstream gradients:

∂L∂z1=−0.8709×0.2461=−0.2144,∂L∂z2=1.0451×0.2425=0.2534\frac{\partial L}{\partial z_1} = -0.8709 \times 0.2461 = -0.2144, \qquad \frac{\partial L}{\partial z_2} = 1.0451 \times 0.2425 = 0.2534

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. zi=Wi,1x1+Wi,2x2+b1,iz_i = W_{i,1} x_1 + W_{i,2} x_2 + b_{1,i}. Each weight's gradient is ∂L∂zi\frac{\partial L}{\partial z_i} times the input it multiplies. Each bias gets ∂L∂zi\frac{\partial L}{\partial z_i} unchanged:

∂L∂W1,1=−0.2144×0.5=−0.1072,∂L∂W1,2=−0.2144×1.0=−0.2144\frac{\partial L}{\partial W_{1,1}} = -0.2144 \times 0.5 = -0.1072, \qquad \frac{\partial L}{\partial W_{1,2}} = -0.2144 \times 1.0 = -0.2144
∂L∂W2,1=0.2534×0.5=0.1267,∂L∂W2,2=0.2534×1.0=0.2534\frac{\partial L}{\partial W_{2,1}} = 0.2534 \times 0.5 = 0.1267, \qquad \frac{\partial L}{\partial W_{2,2}} = 0.2534 \times 1.0 = 0.2534
∂L∂b1,1=−0.2144,∂L∂b1,2=0.2534\frac{\partial L}{\partial b_{1,1}} = -0.2144, \qquad \frac{\partial L}{\partial b_{1,2}} = 0.2534

That's all 9 gradients. Collected:

Parameter Value Gradient ∂L/∂(⋅)\partial L / \partial(\cdot)
W1,1,W1,2W_{1,1}, W_{1,2} 0.1, 0.2 −0.1072, −0.2144
W2,1,W2,2W_{2,1}, W_{2,2} −0.3, 0.4 0.1267, 0.2534
b1,1,b1,2b_{1,1}, b_{1,2} 0.0, 0.1 −0.2144, 0.2534
w2,1,w2,2w_{2,1}, w_{2,2} 0.5, −0.6 −0.9792, −1.0217
b2b_2 0.2 −1.7418

If you needed the gradient with respect to the inputs, say for Adversarial Examples, one more step gives it. Since x1x_1 feeds both hidden neurons, the branch rule sums two contributions: ∂L∂x1=0.1×(−0.2144)+(−0.3)×0.2534=−0.0214−0.0760=−0.0975\frac{\partial L}{\partial x_1} = 0.1 \times (-0.2144) + (-0.3) \times 0.2534 = -0.0214 - 0.0760 = -0.0975.

One gradient-descent step

Now use the gradients. With learning rate η=0.1\eta = 0.1, every parameter moves by −0.1-0.1 times its gradient. For example w2,1w_{2,1} goes from 0.50.5 to 0.5−0.1×(−0.9792)=0.59790.5 - 0.1 \times (-0.9792) = 0.5979, and W2,1W_{2,1} goes from −0.3-0.3 to −0.3−0.1×0.1267=−0.3127-0.3 - 0.1 \times 0.1267 = -0.3127. 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 δ\boldsymbol{\delta} ("delta") for the gradient of the loss with respect to a layer's weighted sums z\mathbf{z}, often called the layer's error signal. For a layer z=Wa+b\mathbf{z} = \mathbf{W}\mathbf{a} + \mathbf{b} whose input is a\mathbf{a}, followed by an activation ff:

  1. Gradient for the weights: ∂L∂W=δ a⊤\frac{\partial L}{\partial \mathbf{W}} = \boldsymbol{\delta}\, \mathbf{a}^\top (each weight gets its row's δ\delta times its column's input).
  2. Gradient for the biases: ∂L∂b=δ\frac{\partial L}{\partial \mathbf{b}} = \boldsymbol{\delta}.
  3. Gradient passed to the layer below: ∂L∂a=W⊤δ\frac{\partial L}{\partial \mathbf{a}} = \mathbf{W}^\top \boldsymbol{\delta}.
  4. Through the activation below: δbelow=∂L∂a⊙f′(zbelow)\boldsymbol{\delta}_{\text{below}} = \frac{\partial L}{\partial \mathbf{a}} \odot f'(\mathbf{z}_{\text{below}}), where ⊙\odot 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 X\mathbf{X}, 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 ϵ\epsilon, 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 ∂L∂y^=−1.7418\frac{\partial L}{\partial \hat{y}} = -1.7418 was computed once and then shared by every parameter below it. In a deep network, each layer's δ\boldsymbol{\delta} 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 h1h_1 and h2h_2 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 .grad on every backward() call, so that gradients from several branches or batches can accumulate. If you don't call optimizer.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 += 1 or relu_(...) 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 nan signal exploding gradients. Both are properties of the network, not bugs in backpropagation, and have their own fixes.

Where it leads

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

  1. Redo the forward and backward pass by hand with target y=0y = 0 instead of 1. Which gradients change sign? Check your answers by editing the NumPy code.
  2. Replace the hidden sigmoid with ReLU. What is the local slope at z1=0.25z_1 = 0.25 and z2=0.35z_2 = 0.35? Recompute ∂L∂z1\frac{\partial L}{\partial z_1} and ∂L∂z2\frac{\partial L}{\partial z_2}. Are they larger or smaller than with sigmoid?
  3. Harder: write the backward pass for a batch of examples, with X of 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In a computation graph, c = a × b with a = 3 and b = −2. The upstream gradient ∂L/∂c is 0.5. What gradient flows back to a?

  2. A value x feeds into two different neurons. During the backward pass, those two paths send back gradients of 0.3 and −0.1. What is ∂L/∂x?

  3. Why is backpropagation so much cheaper than nudging each weight and re-running the network?

  4. Your PyTorch training loop never calls optimizer.zero_grad(). What goes wrong?

  5. You wrote a backward pass for a new layer by hand. Training runs but the model learns badly. What should you do first?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

Neural Networks (video series)

3Blue1Brown · Beginner · Free

Gorgeous animated explanations of neural nets, gradient descent, backprop, Transformers and attention.

Video

Neural Networks: Zero to Hero

Andrej Karpathy · Intermediate · Free

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.

Tool

micrograd

Andrej Karpathy · Intermediate · Free

A tiny autograd engine in about 100 lines. Reading it is the best way to demystify backprop.

Article

Yes you should understand backprop

Andrej Karpathy · 2016 · Intermediate · Free

A short essay on why practitioners must understand the backward pass, with concrete failure cases: saturated sigmoids, dead ReLUs and exploding gradients in RNNs.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/backpropagation.md