All courses

Backpropagation as reverse-mode autodiff

Backpropagate gradients through a computational graph by hand using the local chain rule at each node. Explain why one backward pass costs about 2× the forward pass.

Builds on: Gradients and Jacobians, Weights, parameters and layers

▶ Watch this lesson Start the whole course

What the animation says

One number, billions of knobs

Training tweaks every weight to push one number down: the loss. To do that, it needs to know how the loss changes when each weight moves. One derivative per weight, billions of them. The naive way: nudge one weight, rerun the whole model, and see what the loss did. That is one forward pass per weight. A billion weights means a billion passes, every single step. Backpropagation gets all of those derivatives exactly, for roughly the cost of two more forward passes. Here is how.

Messages flow backwards

Write the forward pass as a graph of simple operations. Each node remembers its inputs. a is two, b is three. c is a times b: six. d is c plus a: eight. The loss is d squared: sixty-four. Now go backwards. Each node receives a message: how much the loss moves per unit of its output. It multiplies that by its local derivative and passes it on. The loss starts at one. d gets two times d: sixteen. The plus node passes sixteen straight to c. The times node sends b sixteen times a: thirty-two. But a feeds two nodes. What is its gradient?

Uses add: the local rule

Sixty-four. Through d, a gets sixteen. Through c, it gets sixteen times b: forty-eight. They add. Check: the loss equals a squared times b-plus-one squared. Its slope in a is sixty-four, and in b, thirty-two. So the rule is local. Each input's gradient gets plus-equals: the output's gradient times the local derivative. Start the loss at one and everything else at zero. Visit nodes in reverse order, so each gradient is complete before it is passed on. Here is a new graph. Tap the value whose gradient is a sum of two messages.

One product becomes two

Real networks are mostly matrix products. A layer computes Y equals X times W. Going backwards, the same local rule gives two products of the same size. X transpose times Y-bar is the weight gradient, used to update W. Y-bar times W transpose goes back to the previous layer. So the backward pass costs about two forwards, and a full training step about three. But those backward products need something from the forward pass. What must stay in memory?

Check it in code

The activations. The weight gradient needs X, so every layer's input stays in memory until backward. That's the price. Here it is in NumPy. One forward product, then the square's local rule: Y-bar is two Y. These two lines are the backward products: the weight gradient, and the message to the earlier layer. To check, nudge one weight by a millionth and rerun. The two printed numbers agree. Backprop is the chain rule applied locally, from the loss backwards. Uses add, and all gradients cost about two forward passes.

All the weight gradients at once?

Training adjusts every weight to lower one number, the **loss**. That needs $\partial\mathcal L/\partial w$ for billions of weights $w$. You could nudge each weight and rerun the forward pass, but that costs a billion forward passes per step. **Backpropagation** gets *all* of these derivatives exactly, for about the cost of two more forward passes. How does it do that?

Pass sensitivities backwards, node by node

Write the forward pass as a **computational graph**. Each node is one simple operation (add, multiply, matrix product) and remembers its inputs. Then walk the graph **backwards** from the loss. Each node receives "how much the loss changes per unit change of my output". It multiplies that by its own **local derivative** and hands the result to its inputs. If a value fed several nodes, the messages coming back to it are **added**.

The local rule

Write $\bar u=\partial\mathcal L/\partial u$ (same shape as $u$). Start with $\bar{\mathcal L}=1$ and every other $\bar u=0$. Visit nodes in reverse order of the forward pass, so each $\bar y$ is complete before it is passed on. For each node $y=f(u)$: $$\bar u \mathrel{+}= \bar y\,\frac{\partial y}{\partial u}$$ For vectors, this is the row vector $\bar y$ times the **Jacobian**. Every use of $u$ contributes to the sum. For a linear layer $Y=XW$: $$\bar X=\bar Y W^\top,\quad \bar W=X^\top\bar Y$$ This is **reverse mode**: one sweep gives one output's derivatives with respect to all inputs.

Backprop by hand

Take $a=2,\ b=3$. Forward: $c=ab=6$, $d=c+a=8$, $\mathcal L=d^2=64$. Backward: $\bar{\mathcal L}=1$, $\bar d=2d=16$, $\bar c=\bar d\cdot1=16$, $\bar b=\bar c\cdot a=32$. $a$ is used twice. Via $d$ it gets $16$; via $c$ it gets $\bar c\cdot b=48$. So $\bar a=16+48=64$. Check: $\mathcal L=a^2(b+1)^2$, so $\partial_a\mathcal L=2a(b+1)^2=64$ ✓ and $\partial_b\mathcal L=2a^2(b+1)=32$ ✓.

Why backward ≈ 2× forward

Almost all the work in a network is matrix products. The forward pass does one per layer: $XW$. The backward pass does **two of the same size**: - $\bar W=X^\top\bar Y$, the weight gradient, which is used to update the weights. - $\bar X=\bar Y W^\top$, which goes back to the previous layer. So backward ≈ 2× forward, and a full training step ≈ 3×. The price is memory. The forward pass's intermediate values (**activations**, such as each layer's input $X$) must be kept until the backward products use them.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(4, 3)); W = rng.normal(size=(3, 2))
Y = X @ W                 # forward: 1 matrix product
L = (Y**2).sum()          # scalar loss
Yb = 2 * Y                # dL/dY (local rule of the square)
Wb = X.T @ Yb             # backward product 1: weight gradient
Xb = Yb @ W.T             # backward product 2: sent to earlier layer
eps = 1e-6; W2 = W.copy(); W2[0, 0] += eps
print(Wb[0, 0], (((X @ W2)**2).sum() - L) / eps)  # should match

Remember

Backprop is the chain rule applied locally, from the loss backwards. Each node multiplies the incoming gradient by its local derivative, and gradients from multiple uses of a value add. Each forward matrix product becomes two in the backward pass, so the gradients for all weights cost about 2 forward passes.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.