Backpropagation Explained: How Neural Networks Learn — With a Worked Example and Python Code
Backpropagation is how neural networks learn from errors. Follow the chain rule, a worked numeric example, the derivation, and NumPy and PyTorch code.
Definition: Backpropagation is the algorithm that calculates how much each weight in a neural network contributed to its error. It sends the error backward from the output, layer by layer, using the chain rule. Gradient descent then nudges every weight in the direction that reduces the error.
TL;DR: The 4 Steps
- Forward pass. Feed an input through the network, layer by layer, to get a prediction. Save every intermediate value.
- Loss. Compare the prediction with the target and compute a single number: the error.
- Backward pass. Starting at the output, use the chain rule to work out how much each weight and bias contributed to that error. This is backpropagation proper.
- Gradient-descent update. Move every weight a small step in the direction that lowers the loss. Then repeat.
How to read this article. If you just want the idea, read the first two sections. If you want the math, read the derivation section. If you want to code it, jump to the Python sections.
What Is Backpropagation? (in simple terms)
Imagine baking a cake from a recipe with twenty adjustable settings: oven temperature, sugar, salt, baking time, and so on. You taste it and it is far too salty. Which setting caused the problem, and by how much? Changing them all at random would be a poor strategy. You want to know that salt deserves most of the blame, baking time almost none, and which way each setting should move. That is a credit and blame assignment problem.
A neural network faces the same problem with thousands, millions, or billions of settings, called weights and biases. A loss function says how wrong the network was, but not which weights caused the error. Backpropagation answers that. For every weight it computes a number, the gradient, saying how the loss changes if that weight increases slightly. A large positive gradient means the weight is pushing the error up, so lower it. A large negative gradient means raising it would help. Near zero means it barely matters right now.
The name comes from backward propagation of errors. The error is measured at the output, then sent backward through the same connections the data traveled forward on. Each layer receives blame from the layer after it, works out its own share, and passes the rest back.
Two clarifications help. Backpropagation computes gradients; it does not change weights. An optimizer such as gradient descent does that. And what travels backward is not the raw prediction error but a derivative of the loss, defined precisely in the derivation section.
A preview from the worked example below: the output weight v₁ has a gradient of about −0.0603, while a first-layer weight has about −0.0154, roughly four times smaller. Blame is diluted as it travels back, which matters in the vanishing-gradient section. New to the building blocks? See what neural networks are and activation functions.
Why Do Neural Networks Need Backpropagation?
Consider the obvious alternative: you want every weight’s gradient, but you can only run the network forward.
The brute-force method is numerical differentiation. Nudge one weight by a tiny amount, rerun the forward pass, and see how the loss changes. That change divided by the nudge estimates the weight’s gradient. Then repeat for the next weight.
The cost is easy to count: one forward pass for the baseline, plus one per weight. A network with 1 million weights needs 1,000,001 forward passes for a single set of gradients, and training takes thousands to millions of steps. A 7-billion-weight language model would need 7,000,000,001 passes per step. That is not slow. It is impossible.
Backpropagation gets the same gradients from two passes: one forward and one backward. The backward pass costs a small constant multiple of the forward pass. Even if it costs three times as much, you pay the equivalent of four forward passes instead of 1,000,001, about 250,000 times less work for a 1-million-weight network.
It avoids repeated work by reusing intermediate results. The blame assigned to a layer is computed once, and every weight feeding that layer reuses it. This dynamic-programming idea is why deep learning is practical, and why finite differences survive only as a debugging tool, which we use in the NumPy section.
How Backpropagation Works: The 4 Steps
Training repeats a four-step cycle. Backpropagation is step 3, but it needs the other three to make sense.
- Forward pass. For each layer, compute the pre-activation z = W · (previous activation) + b, then the activation a = f(z), where f is a function such as sigmoid or ReLU. The last activation is the prediction ŷ. Cache every z and a as you go, because the backward pass needs them.
- Loss. Compute a scalar loss L measuring how far ŷ is from the target y: squared error for regression, cross-entropy for classification.
- Backward pass. At the output, compute how the loss changes with respect to the pre-activation. Call this δ (delta). Then step backward: each layer’s δ is built from the next layer’s δ, the connecting weights, and the local slope of the activation function. A weight’s gradient is its layer’s δ times the activations that fed it. This is the chain rule applied systematically.
- Gradient-descent update. Subtract a small multiple of each gradient: w ← w − η · ∂L/∂w, where η (eta) is the learning rate. Then return to step 1 with the next mini-batch.
Here is the cycle as pseudocode:
initialize weights W, biases b
repeat for many steps:
take a mini-batch (x, y)
a[0] = x
for l = 1..L: # 1. forward pass
z[l] = W[l] a[l-1] + b[l]
a[l] = f(z[l]) # cache z[l] and a[l]
loss = Loss(a[L], y) # 2. loss
delta[L] = dLoss/dz[L] # 3. backward pass
for l = L-1..1:
delta[l] = (W[l+1]^T delta[l+1]) * f'(z[l])
for l = 1..L:
dW[l] = delta[l] a[l-1]^T
db[l] = delta[l]
for l = 1..L: # 4. update
W[l] -= learning_rate * dW[l]
b[l] -= learning_rate * db[l]
Backpropagation and gradient descent: what is the difference?
Backpropagation computes the gradient. Gradient descent uses it. Other optimizers, such as momentum SGD or Adam, consume the same gradients in different ways. And you could compute gradients without backpropagation (slowly, by finite differences) and still feed them to gradient descent.
Picture a hiker in fog on a hilly landscape. Height is the loss, and position is the weights. Backpropagation is feeling the slope underfoot. Gradient descent is taking a step downhill. Too large a learning rate and the hiker overshoots the valley. Too small and getting anywhere takes forever.
Backpropagation Example: Worked Step by Step (with numbers)
This example is small enough to follow on paper. I checked every value in code, and the gradient for w₁₁ matches a finite-difference estimate to six decimal places.
The setup. A network with 2 inputs, 2 hidden neurons, and 1 output. All neurons use the sigmoid activation, σ(z) = 1 / (1 + e⁻ᶻ), whose derivative is σ′(z) = σ(z)(1 − σ(z)). The loss is squared error, L = ½(ŷ − y)². The learning rate is η = 0.5. Values are rounded to four decimal places for display.
| Item | Value |
|---|---|
| Inputs | x₁ = 1.0, x₂ = 0.5 |
| Target | y = 1.0 |
| Hidden neuron h₁ | weights w₁₁ = 0.3, w₁₂ = −0.2, bias b₁ = 0.1 |
| Hidden neuron h₂ | weights w₂₁ = 0.5, w₂₂ = 0.4, bias b₂ = −0.1 |
| Output neuron | weights v₁ = 0.6, v₂ = −0.4, bias c = 0.2 |
The example uses simple names (w, v, b, c); the derivation later uses layer notation.
Step 1: Forward pass
| Quantity | Calculation | Result |
|---|---|---|
| z for h₁ | 0.3 × 1.0 + (−0.2) × 0.5 + 0.1 | 0.3000 |
| a for h₁ = σ(0.3) | 1 / (1 + e⁻⁰·³) | 0.5744 |
| z for h₂ | 0.5 × 1.0 + 0.4 × 0.5 + (−0.1) | 0.6000 |
| a for h₂ = σ(0.6) | 1 / (1 + e⁻⁰·⁶) | 0.6457 |
| z for output | 0.6 × 0.5744 + (−0.4) × 0.6457 + 0.2 | 0.2864 |
| prediction ŷ = σ(0.2864) | 1 / (1 + e⁻⁰·²⁸⁶⁴) | 0.5711 |
Step 2: Loss
L = ½ × (0.5711 − 1.0)² = ½ × (−0.4289)² = ½ × 0.1840 = 0.0920
The prediction is too low, so the weights need to push the output up.
Step 3: Backward pass
Start at the output. The loss depends on ŷ, and ŷ depends on the output pre-activation z through the sigmoid. The chain rule gives:
δ_out = ∂L/∂z = (ŷ − y) × σ′(z) = (ŷ − y) × ŷ(1 − ŷ)
Then work backward to each hidden neuron, using the output weights to route blame, and each hidden neuron’s own sigmoid slope:
δ_hⱼ = (output weight vⱼ × δ_out) × aⱼ(1 − aⱼ)
| Quantity | Calculation | Result |
|---|---|---|
| δ_out | (0.5711 − 1.0) × 0.5711 × (1 − 0.5711) = (−0.4289) × 0.2449 | −0.1051 |
| Blame routed to h₁ | v₁ × δ_out = 0.6 × (−0.1051) | −0.0630 |
| Blame routed to h₂ | v₂ × δ_out = (−0.4) × (−0.1051) | 0.0420 |
| Sigmoid slope at h₁ | 0.5744 × (1 − 0.5744) | 0.2445 |
| Sigmoid slope at h₂ | 0.6457 × (1 − 0.6457) | 0.2288 |
| δ_h₁ | −0.0630 × 0.2445 | −0.0154 |
| δ_h₂ | 0.0420 × 0.2288 | 0.0096 |
Now every weight gradient is “the δ of the neuron it feeds, times the value it carries”:
| Parameter | Gradient formula | Gradient |
|---|---|---|
| v₁ | δ_out × a_h₁ = −0.1051 × 0.5744 | −0.0603 |
| v₂ | δ_out × a_h₂ = −0.1051 × 0.6457 | −0.0678 |
| c | δ_out | −0.1051 |
| w₁₁ | δ_h₁ × x₁ = −0.0154 × 1.0 | −0.0154 |
| w₁₂ | δ_h₁ × x₂ = −0.0154 × 0.5 | −0.0077 |
| b₁ | δ_h₁ | −0.0154 |
| w₂₁ | δ_h₂ × x₁ = 0.0096 × 1.0 | 0.0096 |
| w₂₂ | δ_h₂ × x₂ = 0.0096 × 0.5 | 0.0048 |
| b₂ | δ_h₂ | 0.0096 |
Step 4: Gradient-descent update
Each new weight is the old weight minus η × gradient, with η = 0.5:
| Parameter | Old | Gradient | New |
|---|---|---|---|
| w₁₁ | 0.3000 | −0.0154 | 0.3077 |
| w₁₂ | −0.2000 | −0.0077 | −0.1961 |
| b₁ | 0.1000 | −0.0154 | 0.1077 |
| w₂₁ | 0.5000 | 0.0096 | 0.4952 |
| w₂₂ | 0.4000 | 0.0048 | 0.3976 |
| b₂ | −0.1000 | 0.0096 | −0.1048 |
| v₁ | 0.6000 | −0.0603 | 0.6302 |
| v₂ | −0.4000 | −0.0678 | −0.3661 |
| c | 0.2000 | −0.1051 | 0.2525 |
Did it work?
Rerun the forward pass with the new weights. The prediction rises from 0.5711 to 0.5943, and the loss falls from 0.0920 to 0.0823, about 10.5% lower after a single update. Every parameter with a negative gradient increased, and every one with a positive gradient decreased.
A second mini-example: one neuron, ReLU, squared error
The ReLU activation is f(z) = max(0, z), with derivative 1 when z > 0 and 0 when z < 0. Take a single neuron with input x = 2, weight w = 0.5, bias b = −0.2, target y = 1.5, loss L = ½(a − y)², and η = 0.1.
| Step | Calculation | Result |
|---|---|---|
| Forward: z | 0.5 × 2 + (−0.2) | 0.8 |
| Forward: a = ReLU(0.8) | max(0, 0.8) | 0.8 |
| Loss | ½ × (0.8 − 1.5)² | 0.245 |
| δ = ∂L/∂z | (a − y) × f′(z) = (−0.7) × 1 | −0.7 |
| ∂L/∂w | δ × x = −0.7 × 2 | −1.4 |
| ∂L/∂b | δ | −0.7 |
| New w | 0.5 − 0.1 × (−1.4) | 0.64 |
| New b | −0.2 − 0.1 × (−0.7) | −0.13 |
| New z, new loss | 0.64 × 2 − 0.13 = 1.15; ½ × (1.15 − 1.5)² | 0.06125 |
The loss dropped from 0.245 to 0.06125 in one step. Had z been negative, f′(z) would be 0, so δ would be 0 and nothing would be learned from this example. A neuron stuck outputting zero for every input is called a “dead” ReLU.
The Chain Rule: The Only Math You Need First
Everything in backpropagation is one idea applied repeatedly: the chain rule. If y depends on u, and u depends on x, so that y = f(g(x)), then:
dy/dx = f′(g(x)) × g′(x)
Rates of change multiply along a chain. If a gear turns three times per crank turn, and the wheel turns twice per gear turn, the wheel turns 3 × 2 = 6 times per crank turn.
A neural network is a long chain of simple operations, so we organize the calculation as a computational graph: each node is one operation, and the chain rule says to multiply local derivatives along the path from the loss back to the quantity you care about. Take a tiny graph:
p = w * x q = p + b r = q * q
with w = 3, x = 2, b = -1: p = 6, q = 5, r = 25
Work backward from r. Each node multiplies the gradient arriving from the right by its own local derivative:
| Node | Local derivative | Gradient of r |
|---|---|---|
| r = q² | ∂r/∂q = 2q = 10 | ∂r/∂q = 10 |
| q = p + b | ∂q/∂p = 1, ∂q/∂b = 1 | ∂r/∂p = 10, ∂r/∂b = 10 |
| p = w × x | ∂p/∂w = x = 2, ∂p/∂x = w = 3 | ∂r/∂w = 10 × 2 = 20, ∂r/∂x = 10 × 3 = 30 |
Check by direct differentiation: r = (wx + b)², so ∂r/∂w = 2(wx + b)x = 2 × 5 × 2 = 20. It matches.
Two patterns recur. An addition node passes the incoming gradient to both inputs unchanged. A multiplication node gives each input the incoming gradient times the other input’s value. And if a value feeds several later operations, the gradients from each path are added, which is what lets the backward pass handle densely connected networks.
For a visual walkthrough, see 3Blue1Brown’s backpropagation calculus lesson and the Stanford CS231n notes on computational graphs.
Backpropagation Formula & Derivation
Notation. The network has layers l = 1, …, L, and the input is a⁽⁰⁾ = x.
- W⁽ˡ⁾ is layer l’s weight matrix, shape (neurons in l) × (neurons in l−1). b⁽ˡ⁾ is its bias vector.
- z⁽ˡ⁾ = W⁽ˡ⁾ a⁽ˡ⁻¹⁾ + b⁽ˡ⁾ is the pre-activation, the weighted sum before the non-linearity.
- a⁽ˡ⁾ = f(z⁽ˡ⁾) is the activation, with f applied element by element.
- L is the scalar loss, a function of a⁽ᴸ⁾ and the target y.
- δ⁽ˡ⁾ = ∂L/∂z⁽ˡ⁾ is the delta: how sensitive the loss is to each pre-activation in layer l. This is what travels backward.
Step 1: the output-layer delta
The loss depends on z⁽ᴸ⁾ through a⁽ᴸ⁾ = f(z⁽ᴸ⁾), so by the chain rule:
δ⁽ᴸ⁾ = ∂L/∂a⁽ᴸ⁾ ⊙ f′(z⁽ᴸ⁾)
The symbol ⊙ means element-wise multiplication. The first factor depends on your loss, the second on your activation.
Step 2: the delta recursion
A change in one pre-activation z⁽ˡ⁾ⱼ changes a⁽ˡ⁾ⱼ, which feeds every neuron k in layer l+1 through the weight W⁽ˡ⁺¹⁾ₖⱼ. The loss responds along many paths, so we add them:
δ⁽ˡ⁾ⱼ = Σₖ δ⁽ˡ⁺¹⁾ₖ · W⁽ˡ⁺¹⁾ₖⱼ · f′(z⁽ˡ⁾ⱼ)
For the whole layer, the sum over k becomes multiplication by the transpose:
δ⁽ˡ⁾ = (W⁽ˡ⁺¹⁾)ᵀ δ⁽ˡ⁺¹⁾ ⊙ f′(z⁽ˡ⁾)
Read it as three actions: take the blame from the layer ahead, route it backward through the same weights (the transpose), and scale it by the activation’s local slope. This is the engine of backpropagation. In the worked example, “0.6 × (−0.1051)” followed by “× 0.2445” was exactly this formula.
Step 3: weight and bias gradients
Since z⁽ˡ⁾ⱼ = Σₖ W⁽ˡ⁾ⱼₖ a⁽ˡ⁻¹⁾ₖ + b⁽ˡ⁾ⱼ, the weight W⁽ˡ⁾ⱼₖ affects the loss only through z⁽ˡ⁾ⱼ, with sensitivity a⁽ˡ⁻¹⁾ₖ:
∂L/∂W⁽ˡ⁾ = δ⁽ˡ⁾ (a⁽ˡ⁻¹⁾)ᵀ
∂L/∂b⁽ˡ⁾ = δ⁽ˡ⁾
In plain English, a weight’s gradient is the delta of the neuron it feeds times the activation it carries. In the worked example, w₁₁’s gradient was δ_h₁ × x₁.
Step 4: the vectorized (mini-batch) form
Stack m examples as columns, so A⁽ˡ⁾ has shape (n_l × m). For a loss averaged over the batch:
Z⁽ˡ⁾ = W⁽ˡ⁾ A⁽ˡ⁻¹⁾ + b⁽ˡ⁾ (b is added to every column)
Δ⁽ˡ⁾ = (W⁽ˡ⁺¹⁾)ᵀ Δ⁽ˡ⁺¹⁾ ⊙ f′(Z⁽ˡ⁾)
∂L/∂W⁽ˡ⁾ = (1/m) Δ⁽ˡ⁾ (A⁽ˡ⁻¹⁾)ᵀ
∂L/∂b⁽ˡ⁾ = (1/m) Σ over columns of Δ⁽ˡ⁾
The product Δ Aᵀ sums the per-example gradients automatically, so there is no loop over the batch. A quick shape check: Δ⁽ˡ⁾ is (n_l × m) and A⁽ˡ⁻¹⁾ᵀ is (m × n_{l−1}), giving (n_l × n_{l−1}), the shape of W⁽ˡ⁾.
Output-layer special cases
Only the output delta changes between models. Here y is the target and ŷ the prediction:
| Task | Output activation | Loss | δ⁽ᴸ⁾ |
|---|---|---|---|
| Regression | identity | ½‖ŷ − y‖² (MSE) | ŷ − y |
| Bounded regression | sigmoid | ½(ŷ − y)² | (ŷ − y) ⊙ ŷ ⊙ (1 − ŷ) |
| Binary classification | sigmoid | binary cross-entropy | ŷ − y |
| Multi-class classification | softmax | cross-entropy | ŷ − y |
Why do the cross-entropy cases simplify? For sigmoid plus binary cross-entropy, with a = σ(z) and L = −[y ln a + (1 − y) ln(1 − a)], we get ∂L/∂a = (a − y) / (a(1 − a)). Multiplying by σ′(z) = a(1 − a) cancels the denominator, leaving δ = a − y.
For softmax, ŷₖ = e^{zₖ} / Σⱼ e^{zⱼ} and L = −Σₖ yₖ ln ŷₖ. Using ∂ŷₖ/∂zᵢ = ŷₖ(𝟙[k = i] − ŷᵢ), we get ∂L/∂zᵢ = −yᵢ + ŷᵢ Σₖ yₖ. The targets sum to 1, so δ = ŷ − y.
The practical lesson is in row two. Squared error with a sigmoid output leaves a factor ŷ(1 − ŷ), which is nearly zero when the output saturates, so learning stalls even when the prediction is badly wrong. Cross-entropy cancels that factor, which is why it is the default for classification. Logistic regression is exactly the one-neuron sigmoid-plus-cross-entropy case.
Backpropagation vs Forward Propagation
These are two halves of one training step, not competing methods. Forward propagation makes a prediction. Backpropagation works out how to improve it.
| Aspect | Forward propagation | Backpropagation |
|---|---|---|
| Direction | Input to output (layer 1 to L) | Output to input (layer L to 1) |
| Purpose | Produce a prediction and a loss | Produce the gradient of the loss for every parameter |
| What is computed | z⁽ˡ⁾ = W⁽ˡ⁾a⁽ˡ⁻¹⁾ + b⁽ˡ⁾ and a⁽ˡ⁾ = f(z⁽ˡ⁾) | δ⁽ˡ⁾, then ∂L/∂W⁽ˡ⁾ and ∂L/∂b⁽ˡ⁾ |
| What is cached | Stores z⁽ˡ⁾ and a⁽ˡ⁾ for every layer | Does not need to store much extra. It consumes the forward cache, then discards it |
| Needs | Inputs and current weights | The forward cache, the weights, and the loss |
| Cost | One matrix multiply per layer | Roughly two matrix multiplies per layer (one for δ, one for the weight gradient), so a small constant multiple of the forward cost |
| Used at inference? | Yes | No. Only training needs gradients |
Two consequences follow. Training uses more memory than inference, because the forward pass must hold every layer’s activations until the backward pass consumes them. And backpropagation cannot start until the forward pass finishes, since δ at the output needs the final prediction.
Backpropagation in Python: NumPy From Scratch
This two-layer network (one hidden layer) learns XOR, a problem a single neuron cannot solve. It uses sigmoid in both layers and binary cross-entropy loss, so the output delta is simply a⁽²⁾ − y. Examples are columns, matching the vectorized formulas above. I ran this code, and the numbers below are its actual output.
import numpy as np
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def init_params(n_in, n_hidden, n_out, seed=0):
rng = np.random.default_rng(seed)
return {
"W1": rng.normal(0, 1.0, (n_hidden, n_in)),
"b1": np.zeros((n_hidden, 1)),
"W2": rng.normal(0, 1.0, (n_out, n_hidden)),
"b2": np.zeros((n_out, 1)),
}
def forward(X, p):
"""X has shape (n_in, m): one column per example."""
z1 = p["W1"] @ X + p["b1"]
a1 = sigmoid(z1)
z2 = p["W2"] @ a1 + p["b2"]
a2 = sigmoid(z2)
cache = {"X": X, "a1": a1, "a2": a2} # cache what backward needs
return a2, cache
def loss_fn(a2, Y):
eps = 1e-12
m = Y.shape[1]
return -np.sum(Y * np.log(a2 + eps) + (1 - Y) * np.log(1 - a2 + eps)) / m
def backward(Y, p, cache):
X, a1, a2 = cache["X"], cache["a1"], cache["a2"]
m = Y.shape[1]
d2 = a2 - Y # sigmoid + cross-entropy
grads = {
"W2": d2 @ a1.T / m,
"b2": d2.sum(axis=1, keepdims=True) / m,
}
d1 = (p["W2"].T @ d2) * a1 * (1 - a1) # delta recursion
grads["W1"] = d1 @ X.T / m
grads["b1"] = d1.sum(axis=1, keepdims=True) / m
return grads
def gradient_check(X, Y, p, eps=1e-5):
_, cache = forward(X, p)
grads = backward(Y, p, cache)
worst = 0.0
for name in p:
for idx in np.ndindex(p[name].shape):
old = p[name][idx]
p[name][idx] = old + eps
up = loss_fn(forward(X, p)[0], Y)
p[name][idx] = old - eps
down = loss_fn(forward(X, p)[0], Y)
p[name][idx] = old
num = (up - down) / (2 * eps)
ana = grads[name][idx]
rel = abs(num - ana) / max(1e-8, abs(num) + abs(ana))
worst = max(worst, rel)
return worst
X = np.array([[0, 0, 1, 1], [0, 1, 0, 1]], dtype=float) # XOR inputs
Y = np.array([[0, 1, 1, 0]], dtype=float)
params = init_params(2, 4, 1)
print("max relative error:", gradient_check(X, Y, params))
lr = 1.0
for step in range(5001):
a2, cache = forward(X, params)
grads = backward(Y, params, cache)
for k in params:
params[k] -= lr * grads[k]
if step % 1000 == 0:
print(step, round(loss_fn(a2, Y), 4))
print(np.round(forward(X, params)[0], 3))
Running it prints:
max relative error: 3.129072913748843e-09
0 0.9107
1000 0.0113
2000 0.0044
3000 0.0027
4000 0.0019
5000 0.0015
[[0.002 0.998 0.999 0.001]]
The last line is the output for the four XOR inputs: close to 0, 1, 1, 0, as it should be. Exact digits may vary slightly by platform.
How the code maps to the math. d2 = a2 - Y is the output delta. The line d1 = (W2.T @ d2) * a1 * (1 - a1) is the delta recursion, with a1 * (1 - a1) as σ′(z₁) written in terms of the cached activation. The gradients d2 @ a1.T / m and d1 @ X.T / m are δ(a)ᵀ averaged over the batch.
The gradient check. gradient_check perturbs each parameter by ±10⁻⁵ and compares the central-difference estimate (loss(w + ε) − loss(w − ε)) / 2ε with the analytic gradient. In float64, a relative error near 10⁻⁷ or smaller means the implementation is almost certainly right, and errors above about 10⁻³ point to a bug. Run it on a tiny network, then switch it off: it costs two forward passes per parameter, the very cost backpropagation avoids.
Common bugs
- Forgetting to zero gradients. Accumulated gradients from a previous step corrupt the next update. Here
backwardbuilds fresh arrays each call; in PyTorch you must calloptimizer.zero_grad().- Using the wrong derivative. f′ must be evaluated at the right quantity. σ′(z) = a(1 − a) uses the activation, but ReLU or tanh may need z. A missing or wrong f′ trains badly without any error message.
- Not caching activations. If you recompute or overwrite activations after the weights change, the gradients belong to a different network than the one that made the prediction.
- Shape and scaling slips. Mixing row-per-example and column-per-example layouts, or forgetting the 1/m. The gradient check catches both.
Backpropagation in PyTorch: loss.backward() Explained
If you have written loss.backward(), you have already run backpropagation. Here is the same network in PyTorch, which puts one example per row.
import torch
X = torch.tensor([[0., 0.], [0., 1.], [1., 0.], [1., 1.]]) # one row per example
Y = torch.tensor([[0.], [1.], [1.], [0.]])
torch.manual_seed(0)
model = torch.nn.Sequential(
torch.nn.Linear(2, 4), torch.nn.Sigmoid(),
torch.nn.Linear(4, 1), torch.nn.Sigmoid(),
)
loss_fn = torch.nn.BCELoss()
opt = torch.optim.SGD(model.parameters(), lr=1.0)
for step in range(5001):
opt.zero_grad() # clear old .grad values
loss = loss_fn(model(X), Y) # forward pass + loss
loss.backward() # backward pass: fills .grad on every parameter
opt.step() # gradient-descent update
if step % 1000 == 0:
print(step, round(loss.item(), 4))
print(model(X).detach().round(decimals=3).T)
With this seed, the loss falls to about 0.0165 after 1,000 steps and about 0.0016 after 5,000, and the predictions approach 0, 1, 1, 0. Exact values depend on your PyTorch version. The loop maps onto the four steps: model(X) and the loss are steps 1 and 2, loss.backward() is step 3, and opt.step() is step 4. After backward(), each parameter holds its gradient in .grad, for example model[0].weight.grad.
To confirm that autograd matches the formulas in this article, compare them directly:
torch.manual_seed(1)
m2 = torch.nn.Sequential(torch.nn.Linear(2, 4), torch.nn.Sigmoid(),
torch.nn.Linear(4, 1), torch.nn.Sigmoid())
torch.nn.BCELoss()(m2(X), Y).backward()
W1, b1, W2, b2 = [p.detach() for p in m2.parameters()]
a1 = torch.sigmoid(X @ W1.T + b1)
a2 = torch.sigmoid(a1 @ W2.T + b2)
d2 = a2 - Y # output delta
d1 = (d2 @ W2) * a1 * (1 - a1) # delta recursion
print(torch.allclose(d1.T @ X / 4, m2[0].weight.grad, atol=1e-6),
torch.allclose(d2.T @ a1 / 4, m2[2].weight.grad, atol=1e-6))
# True True
Autograd is backpropagation
PyTorch’s autograd engine is reverse-mode automatic differentiation, of which backpropagation is the neural-network special case. During the forward pass, PyTorch records each operation in a graph (visible through loss.grad_fn). loss.backward() walks that graph in reverse, applying the chain rule at each node and summing gradients where paths merge, as in the computational-graph example earlier.
Two details surprise newcomers. Gradients accumulate into .grad rather than overwrite it, which is why zero_grad() belongs at the top of the loop. And the graph is freed after backward(), so a second call on the same loss raises an error unless you pass retain_graph=True. Also, BCELoss after a Sigmoid mirrors the math above, but real projects prefer BCEWithLogitsLoss, which fuses the two in a numerically stable way.
When to write backpropagation by hand, and when not to
Use a framework for real work: it is faster, runs on GPUs, covers hundreds of layer types, and is far less error-prone than hand-derived gradients. Write it by hand to learn, to debug an odd gradient, to define a custom operation with its own backward rule, or because an interviewer asked. Writing the NumPy version once and checking it against autograd is the best way to stop treating loss.backward() as a black box.
Backpropagation in Deep Learning & AI Today
The algorithm in this article is the same one that trains today’s largest models. What has changed is the architecture around it and the engineering required to run it at scale.
Convolutional neural networks (CNNs). A convolutional layer reuses one small filter at every position of an image. Backpropagation handles this with the “add up the paths” rule: a shared filter weight’s gradient is the sum of its contributions from every position. Yann LeCun and colleagues applied backpropagation to a convolutional network reading handwritten ZIP-code digits in 1989.
Backpropagation through time (BPTT)
A recurrent neural network (RNN) applies the same weights at every time step. To train it, unroll the network across time, one copy of the layer per step with shared weights, and run ordinary backpropagation on the unrolled graph. That is backpropagation through time. A shared weight’s gradient is the sum of its contributions from every step, and error from step t flows back through all earlier steps, multiplying by a Jacobian at each one. Long sequences mean long chains of multiplication, so RNNs are prone to vanishing and exploding gradients (next section). Standard remedies are truncated BPTT, which backpropagates through only a fixed window of recent steps, and gated architectures such as LSTMs and GRUs.
Transformers and large language models. A transformer stacks attention and feed-forward layers with residual connections and normalization. Every operation, including softmax attention and layer normalization, is differentiable, so autograd backpropagates through all of it with no new algorithm. For a language model, the loss is typically cross-entropy on the next token, and the output delta is again ŷ − y. Optimizers such as AdamW consume the resulting gradients.
Scale. At billions of parameters, the challenge is engineering, not mathematics. The backward pass needs the forward activations, so memory becomes the bottleneck. Common responses are activation checkpointing (recompute some activations instead of storing them), mixed precision, gradient accumulation (sum gradients over several small batches before one update), and splitting work across many accelerators. Backpropagation also trains image classifiers, diffusion image generators, speech recognizers, and reinforcement-learning networks such as the deep Q-network.
Vanishing and Exploding Gradients (and How to Fix Them)
The delta recursion multiplies by a weight matrix and an activation slope at every layer, so going back k layers means roughly k multiplications. Repeated multiplication is unstable: factors just below 1 shrink toward zero, and factors just above 1 explode.
Vanishing gradients. The sigmoid’s slope never exceeds 0.25, and is far smaller when the neuron saturates. Ignoring the weights, ten sigmoid layers scale the gradient by at most 0.25¹⁰ ≈ 9.5 × 10⁻⁷, and twenty layers by 0.25²⁰ ≈ 9.1 × 10⁻¹³. Early layers then receive almost no learning signal. This is the backpropagation vanishing gradient problem: the last layers train, the first barely move.
Exploding gradients. If the typical per-layer factor is 1.5, fifty layers (or fifty time steps in an RNN) give 1.5⁵⁰ ≈ 6.4 × 10⁸. Weights jump wildly and the loss turns into NaN. Logging per-layer gradient norms exposes both problems.
The fixes, roughly in the order you would reach for them:
- ReLU-family activations. ReLU’s slope is exactly 1 for positive inputs. The cost is the dead-ReLU effect shown earlier, which Leaky ReLU softens.
- Sensible initialization. Xavier (Glorot) sets weight variance to about 2 / (fan_in + fan_out), and He uses 2 / fan_in for ReLU networks. Both keep the signal’s scale roughly constant across layers.
- Residual connections. A block computing x + F(x) has derivative 1 + F′(x), so the “1” always carries signal back. This is a main reason networks with hundreds of layers can train.
- Normalization. Batch or layer normalization keeps activations in a well-behaved range.
- Gradient clipping. Rescale the gradient when its global norm exceeds a threshold. It is one line in PyTorch:
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
opt.step()
- Gated architectures (LSTM, GRU) let gradients flow across many time steps in sequence models.
Limitations & Alternatives to Backpropagation
Backpropagation has real limits.
- It needs differentiable operations. Hard decisions such as argmax or sampling have zero or undefined gradients. Workarounds like the straight-through estimator are approximations.
- It needs a loss signal. Not necessarily human labels: language models use self-supervised targets such as the next word. But some scalar objective must exist.
- It finds a good solution, not a guaranteed best one. Loss surfaces are non-convex.
- It is memory-hungry and sequential. Activations must be stored, and each layer waits on the layer after it.
- It is biologically implausible in its standard form. The backward pass reuses the forward weights transposed, which real neurons are not known to do (the weight transport problem).
Researchers have proposed alternatives. None has replaced backpropagation for large-scale training, but each is a useful lens:
- Direct Feedback Alignment (DFA). The output error goes straight to every hidden layer through fixed random feedback matrices, removing the weight-transport requirement. It typically trails backpropagation on harder tasks.
- Forward-Forward. Proposed by Geoffrey Hinton in 2022, it uses two forward passes, one on real (“positive”) data and one on fabricated (“negative”) data. Each layer learns locally to respond strongly to the first and weakly to the second.
- Hebbian learning. A local rule often summarized as “neurons that fire together wire together.” It needs no global error signal, but is hard to make solve complex supervised tasks alone.
- Gradient-free methods. Evolution strategies try perturbations, essentially the finite-difference idea from earlier, with the same scaling problem.
History: Who Invented Backpropagation?
The popular story, “Geoffrey Hinton invented backpropagation,” is a myth. The idea was developed in stages by several people in several fields.
| Year | Who | What |
|---|---|---|
| Early 1960s | Control theorists (e.g., Kelley, Bryson) | Gradient recursions for optimizing multi-stage control systems, a close relative of the backward pass |
| 1970 | Seppo Linnainmaa | Master’s thesis at the University of Helsinki describing the reverse mode of automatic differentiation, the general algorithm behind backpropagation |
| 1974 | Paul Werbos | Harvard PhD thesis proposing backpropagation as a way to train neural-network-like systems |
| 1982 | Paul Werbos | Published a paper applying the method to neural networks |
| 1985 | David Parker; Yann LeCun | Independently rediscovered and described similar learning procedures |
| 1986 | David Rumelhart, Geoffrey Hinton, Ronald Williams | Nature paper “Learning representations by back-propagating errors” (vol. 323, pp. 533-536), showing that hidden layers trained this way learn useful internal representations |
| 1989 | LeCun and colleagues | Applied backpropagation in a convolutional network for handwritten ZIP-code digits |
The 1986 paper convincingly showed the neural-network community that backpropagation lets hidden units discover useful features, which is why it is the most-cited milestone. The accurate summary: Linnainmaa supplied the general algorithm, Werbos pointed it at neural networks, and Rumelhart, Hinton, and Williams made it widely understood and used. The original paper is at DOI 10.1038/323533a0.
Frequently Asked Questions
What is backpropagation in simple terms?
Backpropagation is how a neural network works out which weights caused a wrong prediction, and by how much. The error travels backward from the output, giving each weight a share of the blame. The weights are then nudged slightly to reduce that error.
Does AI use backpropagation?
Most modern AI does. Image classifiers, speech recognizers, and large language models are trained with backpropagation plus an optimizer such as Adam. Not all AI does: rule-based systems, decision trees, and search algorithms do not train this way. If a model has weights and a differentiable loss, backpropagation is almost certainly how it learned.
Is backpropagation hard to understand?
The idea is easy; the notation is hard. The idea is: measure the error, then multiply local slopes backward to find each weight’s contribution. The difficulty is indices, transposes, and superscripts. Work through one tiny network by hand, like the 2-2-1 example above (nine parameters), and the formulas usually click.
What is backpropagation really doing?
It is computing a gradient: one number per weight saying how the loss changes if that weight increases slightly. It does this efficiently by applying the chain rule from the output backward and reusing shared results. It does not learn by itself. It supplies directions, and an optimizer takes the steps.
Why use backpropagation?
Because it is far cheaper than the alternative. Finite differences need one forward pass per weight, so a 1-million-weight network needs 1,000,001 passes per update. Backpropagation gets every gradient from one forward and one backward pass, and it is exact up to rounding, whereas finite differences are approximate.
Do CNNs use backpropagation?
Yes. Convolutional networks are trained with backpropagation like fully connected ones. The only twist is weight sharing: one filter is applied at many positions, so its gradient sums the contributions from every position. Yann LeCun’s team used this in 1989 for ZIP-code digit recognition, and modern image models still do.
Why is it called backpropagation?
Because the error signal propagates backward. A forward pass moves data from input to output to make a prediction. The error is then measured at the output and passed back through the layers, last to first. The full phrase is “backward propagation of errors,” often hyphenated as “back-propagation.”
Is AI just a neural network?
No. Neural networks are one family of AI techniques, an especially successful one in the last decade. AI also includes search algorithms, rule-based systems, decision trees, support vector machines, probabilistic models, and reinforcement learning. Chatbots and image generators are built on neural networks, which is why the two get conflated.
Is learning rate 0.001 good?
It is a sensible default for the Adam optimizer, whose PyTorch default is 1e-3. For plain SGD, 0.001 is often too small (typical starts are 0.01 to 0.1), so training crawls. No rate suits every task. Try 0.0001, 0.001, and 0.01 and watch the loss curve.
Does our brain use backpropagation?
Nobody knows. Textbook backpropagation sends errors backward through the same connections in reverse, which real neurons are not known to do. Researchers study approximations, such as feedback alignment and predictive coding, that could learn similarly with biologically plausible wiring. The question is still open.
What problem does backpropagation solve?
The credit assignment problem: in a network with many layers and weights, which weights should change to reduce the error, and in which direction? Backpropagation answers this for all weights at once, at a cost comparable to just two passes through the network, rather than one test run per weight.
Are there alternatives to backpropagation?
Yes, but none has replaced it for large-scale training. Examples include Direct Feedback Alignment (fixed random feedback), Forward-Forward (two forward passes using positive and negative data), Hebbian learning (local rules), and gradient-free methods like evolution strategies. These are mostly research topics. They tend to be less accurate or less scalable on hard tasks.
Can you explain backpropagation in a simple way?
Picture a game of telephone played in reverse. The network guesses, learns how far off it was, and passes that message backward. Each layer says, “here is how much I contributed,” and hands a message to the layer before it. Each weight then shifts slightly in the direction that would have reduced the mistake.
Who found backpropagation?
No single person. Seppo Linnainmaa described the general reverse-mode method in 1970. Paul Werbos proposed it for neural networks in 1974 and published on it in 1982. Rumelhart, Hinton, and Williams popularized it in their 1986 Nature paper. Hinton did not invent it alone.
What is the math behind backpropagation?
Calculus and linear algebra. The chain rule gives δ⁽ˡ⁾ = (W⁽ˡ⁺¹⁾)ᵀ δ⁽ˡ⁺¹⁾ ⊙ f′(z⁽ˡ⁾), which carries blame backward, and the weight gradient is ∂L/∂W⁽ˡ⁾ = δ⁽ˡ⁾(a⁽ˡ⁻¹⁾)ᵀ. At the output of a softmax-plus-cross-entropy model, δ = ŷ − y. The full derivation is in the formula section above.
Key Takeaways + Next Steps
Key takeaways
- Backpropagation computes the gradient of the loss for every weight and bias, using the chain rule from the output backward. It does not update weights itself.
- It costs about two passes instead of one forward pass per weight: for 1 million weights, 1,000,001 passes versus a small constant multiple of two.
- The core formulas are δ⁽ˡ⁾ = (W⁽ˡ⁺¹⁾)ᵀ δ⁽ˡ⁺¹⁾ ⊙ f′(z⁽ˡ⁾), ∂L/∂W⁽ˡ⁾ = δ⁽ˡ⁾(a⁽ˡ⁻¹⁾)ᵀ, and ∂L/∂b⁽ˡ⁾ = δ⁽ˡ⁾. With softmax plus cross-entropy, the output delta is ŷ − y.
- Vanishing and exploding gradients come from repeated multiplication. ReLU, initialization, residuals, normalization, and clipping are the standard fixes.
- PyTorch’s
loss.backward()is reverse-mode autodiff, which is backpropagation. Verify hand-written versions with a gradient check.
Next steps
- Re-derive the 2-2-1 example with different weights, then confirm in code.
- Run the NumPy code, delete the
* (1 - a1)factor, and watch the gradient check fail. - Read on: what neural networks are, activation functions, the multilayer perceptron, and the AI roadmap for beginners.
Further reading
