Key takeaways
- Any neural network can be broken into a computational graph: each node is a simple operation with an easy local derivative, called a gate.
- Backpropagation is just the chain rule applied over and over: downstream gradient = upstream gradient × local gradient.
- Gate patterns: add passes the gradient on unchanged, multiply swaps in the other input's value, max gives it all to the largest. When a variable is used in several places (a fork), its gradients add up.
- Start from a scalar loss with a seed of 1, walk the graph once in reverse topological order, and you get the gradient of every parameter at about the cost of a forward pass.
- For one layer Z=XW+b: ∂W∂L=X⊤G, ∂X∂L=GW⊤, and the gradient of b is summed over the batch (with G=∂L/∂Z). Three tools round it out: automatic differentiation, gradient checking and activation checkpointing.
Billions of partial derivatives: how?
Last episode gave us the recipe for training: work out the gradient of the loss with respect to every parameter, then nudge each parameter a small step the opposite way.
The catch is that a big model has billions of parameters, so we need billions of partial derivatives. The naive way is to test them one at a time: nudge one parameter a tiny bit (say, add 0.001), recompute the loss, and see how much it changed. But every parameter you test means running the whole model again. 7 billion parameters means 7 billion full runs. Nobody can wait that long.
Backpropagation has a far more elegant answer: run forward once, then walk backward once from the loss, and out come the gradients for every parameter in one go. And that backward walk costs about the same as the forward pass.
Breaking a computation into a graph
Start tiny: f=(x+y)⋅z. Split it into two steps:
q=x+y,f=q⋅z
Drawn out, each circle is a simple operation (a gate) and the arrows show which way data flows. That's a computational graph. Plug in x=−2, y=5, z=−4 and follow the arrows: q=−2+5=3, then f=3×(−4)=−12. This trip is the forward pass.
Any neural network, however big, can be broken into a graph of simple gates like this. How finely you chop it is your call. There's just one rule: every gate's local derivative has to be easy to compute.
Walking back from the end
Now we want to know: if x, y and z each move a tiny bit, how does f change? That is, what's the gradient of f with respect to each input?
- Start: the derivative of f with respect to itself is 1, ∂f∂f=1.
- Multiply gate f=q⋅z: ∂z∂f=q=3 and ∂q∂f=z=−4.
- Add gate q=x+y: ∂x∂q=1 and ∂y∂q=1. That's the add gate's local gradient.
- The chain rule connects them:
∂x∂f=∂q∂f⋅∂x∂q=(−4)×1=−4
The same goes for y: −4.
Intuition: Let's check. Change x from −2 to −1.99 and f goes from −12 to −12.04, a change of exactly −4×0.01. A derivative is a sensitivity: move x by h and f moves by about −4h.
So the gradient starts at the very end and flows backward along the arrows to every input. That's backpropagation.
Upstream × local = downstream
Zoom in on a single gate with input x and output q.
- During backprop, a number arrives from later in the graph: the gradient of the loss with respect to q, ∂q∂L. Everything after this gate, however complicated, is already baked into it. This is the upstream gradient.
- The gate itself knows just one thing: ∂x∂q, how much the output moves when the input moves a little. This is the local gradient.
- Multiply them and you get the gradient of the loss with respect to x. It keeps getting passed back, and it's called the downstream gradient.
downstream∂x∂L=upstream∂q∂L×local∂x∂q
That's really just the chain rule, said a different way. The add gate from before works exactly like this: upstream −4, local 1, downstream −4.
The beautiful part: no gate needs to know what the whole graph looks like. It just catches the number coming from upstream, multiplies by its own local gradient, and passes the result on.
Intuition: Think of backprop as gates passing messages down the line. The sign of the gradient tells each gate whether pushing its output up would make the loss go up (gradient >0) or down (gradient <0). The size tells it how strong that effect is.
Add, multiply, max: three gate patterns
A slightly bigger example:
f=2⋅(xy+max(z,w)),x=3, y=−4, z=2, w=−1
Forward: xy=−12, max(z,w)=2, their sum is −10, times 2 gives f=−20.
Backward, starting from 1:
- Times-2 gate: local gradient 2, so the add gate receives 1×2=2.
- Add gate: its local gradient for each input is 1, so it hands the upstream 2, untouched, to both inputs. An add gate is a distributor.
- Max gate: only the larger input, z, actually affected the output. So z gets the whole 2 and w gets 0. A max gate is a router: only one path gets through.
- Multiply gate xy: the derivative with respect to x is y, and with respect to y it's x. So x gets 2×(−4)=−8 and y gets 2×3=6. It's as if the two inputs swapped values.
Check against the formula: ∂x∂f=2y=−8. Spot on.
| Gate |
What it does going back |
| add + |
passes upstream to every input unchanged |
| multiply × |
scales by the other input's value |
| max |
all to the largest input, 0 to the rest |
Watch out: ReLU is just ReLU(z)=max(0,z), so it follows the max-gate rule: when z>0 the gradient passes straight through, and when z<0 it's blocked and becomes 0.
Forks: gradients add up
One more situation: the same variable used in more than one place. The simplest case is f=x⋅x with x=3.
Going forward, both wires carry 3 and the product is 9. Going backward, the multiply gate swaps in the other value: the top wire gets the bottom wire's 3, and vice versa. So what's the gradient of x? Add the gradients from both paths: 3+3=6. Check: dxdx2=2x=6. Exactly right.
The reason is simple: nudge x and the change travels to f along both paths at once, so the two effects add. In general, if y is used by both a and b:
∂y∂f=∂a∂f∂y∂a+∂b∂f∂y∂b
Forks are everywhere in neural networks. One input feeds into every neuron of the next layer. And a residual connection in a Transformer, where x both goes through a sublayer and skips around it to be added back, is a fork too.
Worked example: a sigmoid neuron
Now a real neuron: two inputs x0,x1, two weights w0,w1, and a bias w2. Take the weighted sum and pass it through a sigmoid:
f(w,x)=1+e−(w0x0+w1x1+w2)1
Use w=(2,−3,−3) and x=(−1,−2). To keep things easy, break the sigmoid into four of the simplest gates: multiply by −1, exponentiate, add 1, take the reciprocal.
| Gate |
Forward |
Backward (to its input) |
| weighted sum |
1 |
0.20 |
| ×(−1) |
−1 |
0.20 |
| exp |
0.37 |
−0.20 |
| +1 |
1.37 |
−0.53 |
| 1/x |
0.73 |
−0.53 |
The backward pass, starting from 1 at the output:
- Reciprocal gate: local gradient −x21=−1.3721≈−0.53.
- Plus-1 gate: passes it straight through, still −0.53.
- Exp gate: its local gradient is just its own output, 0.37 (because dxdex=ex), so we get −0.20.
- Times −1 gate: flips the sign, giving +0.20 (more precisely 0.197).
- Add gate: hands that unchanged to all three inputs, so the bias has ∂w2∂f=0.20.
- The two multiply gates: swap in the other value. ∂w0∂f=x0×0.197≈−0.20 and ∂x0∂f=w0×0.197≈0.39; likewise ∂w1∂f≈−0.39 and ∂x1∂f≈−0.59.
Those last four gates together are just the sigmoid, and we've seen its derivative before:
σ′=σ(1−σ)=0.73×0.27≈0.20
Exactly what we got step by step.
Intuition: Which operations you bundle into one gate is purely a matter of convenience. As long as the local gradient is easy, a gate can be as small as one addition or as big as an entire sigmoid.
The algorithm: reverse topological order
Let's turn this into an algorithm. Picture a graph where x is used by both a and b (a fork), a and b feed into c, and c gives L.
- Forward: compute the nodes in an order where each one comes after its inputs. That's a topological order. Store every value along the way, because the backward pass needs them.
- Seed: set the gradient of the loss with respect to itself to 1, ∂L∂L=1.
- Backward: visit every node in exactly the reverse order (reverse topological order). Multiply upstream by local to get the gradient for each of its inputs, and add it on.
Why strictly backward? Look at x: its gradient isn't complete until both paths, through a and through b, have come back and been added. Reverse topological order guarantees that when we reach a node, everything that uses it is already done.
Every edge is walked once forward and once backward. So, done correctly, backprop has the same big-O cost as the forward pass; in practice the backward pass is about twice the forward. Compare the naive approach: 7 billion parameters means 7 billion forward passes, while backprop needs one forward plus one backward, roughly the cost of three forward passes.
Why start from a single number?
Backprop always starts from one number: the loss L. That's because we want one number per parameter, ∂θ∂L ("if θ moves a little, how much does L change?"), and that question only makes sense when L is a single number, a scalar.
A language model, for instance, has a loss at every position in a sentence, ℓ1,…,ℓN. Left uncombined, a single parameter would get several gradients, some saying "go up", others "go down". So we combine them first, usually by taking the mean. A mean is just an add gate followed by multiplying by N1, so going back each loss gets a gradient of N1 (one quarter each, for four losses). Because differentiation is linear:
L=N1i=1∑Nℓi⟹∂θ∂L=N1i=1∑N∂θ∂ℓi
The gradient of the mean loss is exactly the mean of the individual gradients. If four positions give θ the gradients +0.8,−0.3,+0.5,−0.6 (illustrative numbers), the combined gradient is 41(0.8−0.3+0.5−0.6)=0.1.
In PyTorch you first reduce the loss with .mean() (or .sum()), then call .backward(). The first thing backward does is seed ∂L/∂L=1:
loss = losses.mean() # one number
loss.backward() # seed: dL/dL = 1
Backpropagation through one layer
Now apply these rules to one layer, z=xW+b, where x has 3 numbers, z has 2, and W has 3 rows and 2 columns:
zj=i∑xiWij+bj,W=103−121
Each connection is a multiply gate, and where they meet is an add gate. Take x=(1,2,−1) and suppose the upstream gradient ∂z∂L=(2,−1) has arrived.
Weights. W21 connects x2 to z1. It's a multiply gate, so it swaps in the other value: ∂W21∂L=x2⋅∂z1∂L=2×2=4. Every weight works the same way:
∂Wij∂L=xi⋅∂zj∂L⟹∂W∂L=x⊤∂z∂L=24−2−1−21
A column (x⊤) times a row (the gradient) gives 3 rows by 2 columns, exactly the size of W.
Inputs. x1 connects to both z1 and z2. That's a fork, so the gradients add: ∂x1∂L=1⋅2+(−1)⋅(−1)=3. Doing all three at once:
∂x∂L=∂z∂LW⊤=(3, −2, 5)
Bias. It enters z through an add gate, so it's copied straight over: ∂b∂L=∂z∂L=(2,−1).
A whole batch
Real training feeds in a batch of m samples at once. Stack them into a matrix X∈Rm×3 (one sample per row) and the layer becomes Z=XW+b, with Z of shape m×2, W of shape 3×2, and b of shape 1×2 broadcast onto every row. Writing G=∂Z∂L (shape m×2), the three gradients are:
∂W∂L=X⊤G,∂X∂L=GW⊤,∂bj∂L=i=1∑m∂zij∂L
Intuition: A check that saves a lot of head-scratching: a gradient always has the same shape as the tensor it belongs to. W is 3×2, and the only way to build a 3×2 from these pieces is X⊤(3×m)⋅G(m×2).
Why is the gradient of W summed over samples? Because every sample uses the same W, so it's a fork again: each sample contributes its own share. Say sample 1 is the example above and sample 2 has x=(0,1,1) and ∂z∂L=(1,1):
∂W∂L=sample 124−2−1−21+sample 2011011=25−1−1−12
Watch out: A rule worth remembering for life: first derive things cleanly for a single example, then ask whether the tensor is shared across the batch. Shared (like W and b): sum the gradient over the batch dimension. Not shared (like X): each sample keeps its own gradient, and they're stacked along the batch dimension.
Element-wise activations
If an activation follows, H=f(Z), it acts element-wise: output i depends only on input i, so its Jacobian is the diagonal matrix diag(f′(z)). Going back, each element just gets multiplied by its own derivative:
∂Z∂L=∂H∂L⊙f′(Z)
Here ⊙ means multiplying matching entries. Take ReLU: wherever Z>0 the derivative is 1 and the gradient passes through; everywhere else it's 0 and the gradient is blocked. That's the max gate again:
Z=(1.5−2−0.30.7):(0.4−0.20.90.5)⊙(1001)=(0.4000.5)
Math vs PyTorch
In math we write XW with W of shape nin×nout. But PyTorch's nn.Linear stores the weight as nout×nin (output by input) and computes X @ W.T. The transpose is essentially free: it only changes the order memory is read in (the stride) and copies nothing. The design keeps W's gradient the same shape as the stored W.
Gradients that move on, gradients that stay
Draw backprop through a multi-layer network and you'll see two kinds of gradient:
loss
│ dL/dy2 (activation grad)
▼
Layer 2 ──→ dL/dW2 (param grad, stored)
│ dL/dy1 (activation grad)
▼
Layer 1 ──→ dL/dW1 (param grad, stored)
│ dL/dx (activation grad — usually discarded)
▼
input
- Gradients with respect to activations, like ∂y2∂L and ∂y1∂L, are the upstream gradients. They keep getting passed down, layer by layer.
- Gradients with respect to parameters, like ∂W2∂L and ∂W1∂L, stop where they are. Parameters are leaf nodes of the graph: nothing comes before them. Their gradients are stored and handed to the optimizer for the update.
- The gradient that finally reaches the input x is usually thrown away, since input data never gets updated.
Automatic differentiation
By now the whole process looks completely mechanical. Each gate needs to know just two things: how to compute its output, and given the upstream gradient, how to compute its inputs' gradients. The multiply gate, for example:
class Mul:
def forward(self, x, y):
self.x, self.y = x, y # remember inputs
return x * y
def backward(self, g): # g: upstream grad
return g * self.y, g * self.x
Frameworks like PyTorch have these two functions written for every operation (Add, Mul, Exp, MatMul, ReLU, Softmax, and so on); the local gradients are written by the programmer. You only write the forward computation. The framework records the graph as it runs, and when you call backward() it walks back through it for you. This is automatic differentiation: the gradient computation is inferred automatically from the forward expression.
Here's a scary-looking function:
f(x,y)=σ(x)+(x+y)2x+σ(y)
Writing out ∂f/∂x explicitly would be a monster, and it's completely unnecessary. Break the forward pass into simple intermediate variables, one per line, and every local gradient is obvious:
sy = sigmoid(y)
num = x + sy
sx = sigmoid(x)
xpy = x + y
xpy2 = xpy ** 2
den = sx + xpy2
iden = 1 / den
f = num * iden
The backward pass runs those steps in reverse, one local rule per line:
dnum = iden # f = num * iden
diden = num
dden = -1 / den**2 * diden # iden = 1 / den
dsx = dden # den = sx + xpy2
dxpy2 = dden
dxpy = 2 * xpy * dxpy2 # xpy2 = xpy ** 2
dx = dxpy # xpy = x + y
dy = dxpy
dx += sx * (1 - sx) * dsx # sx = sigmoid(x)
dx += dnum # num = x + sy
dsy = dnum
dy += sy * (1 - sy) * dsy # sy = sigmoid(y)
Watch out: x is used three times in the forward pass (in num, sx and xpy). That's a fork, so dx gets accumulated three times (note the +=). y is used twice, so dy accumulates twice.
Gradient checking
Hand-written backprop is easy to get wrong. How do you know it's right? Bring back the naive method: numerical differentiation. Nudge the parameter a small step h left and right, and compute f at each:
f′(x)≈2hf(x+h)−f(x−h)
That's the slope of the secant line between the two points. The smaller h gets, the closer the secant hugs the tangent (the true derivative). Taking a point on each side, a central difference, has an error that shrinks like h2, much more accurate than nudging in one direction only.
Test it on our first example, f=(x+y)z, at x=−2 with h=0.001. The two sides give f(x+h)=−12.004 and f(x−h)=−11.996:
0.002−12.004−(−11.996)=−4
Exactly what backprop gave us.
Watch out: It costs two forward passes per parameter, far too slow for training. Gradient checking is for debugging only: spot-check a few parameters to confirm your backprop is correct.
Trading compute for memory: activation checkpointing
One last engineering problem. Backprop needs intermediate results from the forward pass: a multiply gate needs the other input's value, a sigmoid gate needs its own output. So by default the framework stores every layer's activations. A network with N layers stores N layers' worth, and once the model gets deep, you run out of GPU memory.
Activation (or gradient) checkpointing keeps activations at only a few layers, the checkpoints. When the backward pass needs a segment, it starts from the nearest checkpoint, recomputes that segment with a partial forward pass, uses it, and drops it.
Split N layers into K segments. Memory now holds K checkpoints plus the one segment being recomputed, about N/K layers:
memory∼K+KN
Too few segments and each is long; too many and there are lots of checkpoints. It's cheapest when the two terms match, at K=N:
memory∼N+NN=2N
A 100-layer network, for example, stores about 20 layers' worth instead of 100. Memory drops from O(N) to O(N). The price: backward compute goes from O(N) to O(N+N(K−1)/K), about O(2N) at K=N, or roughly one extra forward pass. That's trading compute for memory.
Recap
Any computation breaks down into a graph of simple gates. Backprop starts from a scalar loss with a seed of 1, walks the graph in reverse topological order applying "downstream = upstream × local", and gets every parameter's gradient in one go, at a cost in the same ballpark as the forward pass. Remember the patterns: add passes the gradient on, multiply swaps in the other value, max gives it all to the largest, and forks add up. For one layer, ∂W∂L=X⊤G, ∂X∂L=GW⊤, and the bias gradient is summed over the batch: shared tensors sum, unshared ones stack. In practice, automatic differentiation does the walking for us, gradient checking catches mistakes, and activation checkpointing trades compute for memory. Next up: now that we have gradients, how big a step should we take?