1.7Backpropagation & the chain rule
How a network figures out which of its millions of knobs to blame for a mistake, in a single backward sweep that costs about as much as the forward pass.
The problem: a billion knobs and one number
Gradient descent told us what to do with a gradientGradientThe vector of partial derivatives of the loss with respect to each parameter. It points in the direction of steepest increase.: step against it. It quietly skipped the hard part, which is getting the gradient. For a network like the ones in the previous lesson, the lossLoss functionA number measuring how wrong a model's predictions are. Training tries to make it small. is one number that depends on every weight through layer after layer of sums and squashes. We need for every weight .
The naive approach is to wiggle each weight in turn: nudge it by a tiny amount , rerun the whole network, and see how much the loss moved. That’s a finite difference, and it works. But it needs one extra forward pass per parameter. GPT-3 had 175 billion parameters, so one gradient this way would take 175 billion forward passes, for a single training step out of hundreds of thousands. Not happening.
BackpropagationBackpropagationAn algorithm that computes the gradient of the loss with respect to every parameter by applying the chain rule backward through the network. gets all of those derivatives exactly (not approximately) from one forward pass and one backward pass. It is not a new kind of calculus; it’s the ordinary chain ruleChain ruleThe calculus rule for derivatives of composed functions: d/dx f(g(x)) = f′(g(x))·g′(x). from school, applied in a clever order with careful bookkeeping. That bookkeeping is so mechanical that every modern framework does it for you automatically. But knowing what happens inside loss.backward() explains a great deal: why training needs so much memory, why some networks refuse to learn, and why certain architectural tricks exist at all.
A bakery’s assembly line has stations: one mixes the dough, one adds sugar, one bakes, one glazes. A customer complains: “too sweet, by this much.” The manager doesn’t re-run the whole factory once per station to find out who’s responsible. Instead the complaint is passed backward. The glazing station says, “my glaze accounts for 30% of the sweetness you taste, so pass 30% of the complaint upstream for whatever came in to me.” The baking station says the oven barely changes sweetness, and passes the message along almost unchanged. And so on.
Each station only needs to know its own sensitivity (how much its output changes when its input changes); that’s the local gradient. The complaint arriving at each station, already scaled by everyone downstream, is the upstream gradient. Multiply the two and pass it on: that’s the chain rule. When the message reaches the sugar dispenser, its knob (a parameter) knows exactly how much to turn, and every other knob found out in the same single backward trip.
Networks as computational graphs
To make the bookkeeping explicit, write the computation as a computational graphComputational graphA computation written as a graph of elementary operations (add, multiply, sigmoid…) with arrows showing which values feed into which. Backpropagation walks it backward.: every elementary operation (multiply, add, sigmoid, square) is a node, and arrows show which values feed into which. Here’s one sigmoid neuronNeuronThe basic unit of a neural network: a weighted sum of inputs plus a bias, passed through an activation function. scored with squared error against a target :
Four tiny steps. The forward pass walks them left to right, computing and remembering each intermediate value. The backward pass walks them right to left, computing for every node, using only two ingredients at each step:
- the upstream gradient , already computed, and
- the node’s local gradient , which depends only on that one operation.
Their product is the gradient for the node’s input. Step through it yourself.
Blue = forward pass (values flow left to right). Orange = backward pass (gradients flow right to left). Each orange edge is labeled with its local gradient; each node’s ∂L/∂· is the incoming gradient times that local gradient. Edit any input and the numbers update instantly.
Things to try:
- Watch the sigmoid step (step 8). The gradient shrinks from about −0.76 to −0.18, because the sigmoid’s local gradient is at most 0.25. Keep that in mind for the vanishing-gradient section below.
- Set and . Now is large, the sigmoid is saturated (), and the loss is close to its maximum of 1. Yet every gradient upstream of the sigmoid is tiny, because is nearly zero out there. The neuron is badly wrong and barely able to learn: it’s stuck.
- Compare the two × outputs. uses the value of ; uses the value of . A multiply node “swaps” its inputs when sending gradients back.
- Check the finite-difference line at step 10. Backprop’s exact answer matches the slow wiggle-one-knob estimate.
- Apply the update a few times. Each round, and move against their gradients and the loss drops: this is gradient descent, with backprop supplying the direction.
The chain rule, gear by gear
The chain rule says: if depends on , and depends on , then the sensitivity of to is the product of the two sensitivities,
Think of gears. If gear A turns 3 times for each turn of gear B, and B turns 2 times for each turn of C, then A turns times per turn of C. A deep network is a long gear train from each weight to the loss, and backprop multiplies the ratios starting from the loss end.
Because every node only needs its own local rule, a handful of patterns cover most of what happens in real networks:
- Add (): local gradient 1 for each input. An adder distributes the upstream gradient unchanged to all its inputs.
- Multiply (): the gradient for is the upstream gradient times , and vice versa. A multiplier swaps.
- Sigmoid: local gradient , conveniently computed from the forward output alone.
- ReLU: local gradient 1 if the input was positive, else 0. A ReLU is a gate: it passes gradient through only for neurons that were active.
- Matrix multiply (): the gradient for is the upstream gradient times (an outer product), and the gradient for is times the upstream gradient. Same “swap” pattern as a scalar multiply, in matrix clothing.
One more rule matters a lot: when a value is used in several places, its gradients add up. If a weight feeds two different paths to the loss, its total gradient is the sum of the gradients along each path. (This is the multivariable chain rule.) In code this is why gradients are accumulated with +=, and why PyTorch makes you call zero_grad() before each step.
Why backward is so efficient
There are two ways to apply the chain rule through a graph. Forward mode pushes derivatives forward alongside the values: pick one input, and track how every node changes as that input wiggles. One pass gives the derivative of everything with respect to one input. With a billion parameters you’d need a billion passes.
Reverse mode goes the other way: start from one output (the loss) and pull derivatives backward. One pass gives the derivative of that output with respect to every input at once. Training has a single scalar loss and enormously many parameters, which is exactly the situation reverse mode is built for. Backpropagation is reverse-mode automatic differentiationAutomatic differentiation (autodiff)Computing exact derivatives of a program by applying the chain rule to each elementary operation. Reverse mode, which gives the gradient of one output with respect to all inputs in one backward pass, is what backpropagation uses. applied to neural networks.
The cost is modest. Each node’s backward step does about as much arithmetic as its forward step, and often a bit more (for a matrix multiply, the backward pass needs two matrix multiplies, one for the weights and one for the inputs, so roughly twice the forward cost). A common rule of thumb is that a training step costs about three forward passes in total: one forward and about two for backward.
The price is memory. To compute local gradients, the backward pass needs the values from the forward pass ( for the multiply, for the sigmoid). So all intermediate activations are stored until the backward pass consumes them. For large models this activation memory can dominate GPU memory, which is why tricks such as activation checkpointing (throw some activations away and recompute them during backward) exist.
Vanishing and exploding gradients
Look again at the chain rule: the gradient reaching an early layer is a product of many local gradients, one per layer it passes through on the way back. Products of many numbers are fragile.
If those factors are typically smaller than 1, the product shrinks exponentially with depth. The sigmoid’s local gradient is at most 0.25, so after 10 sigmoid layers the gradient is scaled by at most . The early layers receive almost no signal and barely learn. This is the vanishing gradientVanishing gradientsWhen gradients shrink exponentially as they flow backward through many layers (a product of many factors below 1), so early layers barely learn. The opposite failure is exploding gradients. problem, and it held back deep networks for years. If the factors are larger than 1 (large weights, say), the product grows exponentially instead: exploding gradients, which show up as sudden loss spikes or NaNs.
Modern architectures are full of fixes, and now you can see why each one works:
- ReLU-family activations have local gradient exactly 1 when active, so they don’t shrink the signal the way saturated sigmoids do.
- Careful initialization (Xavier/Glorot, He) picks starting weight scales so that signals neither shrink nor grow on average from layer to layer.
- Residual connectionsResidual connectionAdding a layer's input to its output (x + f(x)). This creates a 'residual stream' and makes very deep networks trainable. compute instead of . The ”+ x” path has local gradient 1, giving gradients an express lane straight back through dozens of layers.
- Normalization layers such as LayerNormLayer normalizationRescales each token's vector to zero mean and unit variance, with learned scale and shift. RMSNorm is a simpler variant. keep activations in a healthy range.
- Gradient clipping caps the gradient’s overall size, a seatbelt against explosions that’s standard in LLM training.
MATH CORNER · optionalThe chain rule in general, and the demo's numbers by hand
For a scalar loss and a node whose output feeds nodes , the multivariable chain rule sums over all paths:
Process the nodes in reverse topological order (every consumer before its producers) and each is ready when you need it. For vector-valued layers the local derivative is a Jacobian matrix , and the backward step is a vector–Jacobian product . For a linear layer , that gives and .
Worked example (the demo’s defaults): , , , , learning rate .
| node | forward value | local gradient | |
|---|---|---|---|
| 0.1425 | (seed) | 1 | |
| 0.6225 | −0.7551 | ||
| 0.5 | |||
| 1.0 | −0.1774 | ||
| −0.5 | −0.1774 | ||
| 0.5 | |||
| 2 | −0.0887 |
The update: and . The new output is , and the loss falls from 0.1425 to about 0.0785. Both gradients were negative, so both parameters went up, pushing toward the target of 1.
Check one entry with a finite difference: with , . Backprop’s answer is exact; the finite difference merely agrees with it, at the cost of two extra forward passes for this single parameter.
In code
Here is a complete reverse-mode autodiff engine for scalars, in the spirit of Andrej Karpathy’s micrograd. Each Value remembers its parents and its local gradients; backward() visits nodes in reverse order and applies the chain rule:
import math
class Value:
def __init__(self, data, parents=(), local_grads=()):
self.data, self.grad = data, 0.0
self.parents, self.local_grads = parents, local_grads
def __add__(self, o): return Value(self.data + o.data, (self, o), (1.0, 1.0))
def __sub__(self, o): return Value(self.data - o.data, (self, o), (1.0, -1.0))
def __mul__(self, o): return Value(self.data * o.data, (self, o), (o.data, self.data))
def sigmoid(self):
s = 1 / (1 + math.exp(-self.data))
return Value(s, (self,), (s * (1 - s),))
def backward(self):
order, seen = [], set()
def visit(v): # topological order: inputs before outputs
if v not in seen:
seen.add(v)
for p in v.parents: visit(p)
order.append(v)
visit(self)
self.grad = 1.0 # the seed: dL/dL = 1
for v in reversed(order): # walk the graph backward
for p, local in zip(v.parents, v.local_grads):
p.grad += v.grad * local # chain rule; += sums over all paths
x, w, b, y = Value(2.0), Value(0.5), Value(-0.5), Value(1.0)
a = (w * x + b).sigmoid()
L = (a - y) * (a - y) # a is used twice: its gradients add up
L.backward()
print(round(L.data, 4), round(w.grad, 4), round(b.grad, 4)) # 0.1425 -0.3549 -0.1774
PyTorch does exactly this, for tensors, on GPUs, with hundreds of hand-written local-gradient rules: build the graph during the forward pass, then call loss.backward().
- “Backpropagation is the learning algorithm.” Backprop only computes gradients. The learning, changing the weights, is done by an optimizer such as SGD or Adam that uses those gradients. The two are often lumped together, but they’re separate steps.
- “Backprop approximates the gradient numerically.” No: it computes exact derivatives (up to floating-point rounding) by the chain rule. The finite-difference method is the approximate one, and it’s used only to check backprop implementations.
- “The backward pass must be far more expensive than the forward pass.” It costs about the same order: roughly twice the forward pass. The real extra cost is memory, because forward activations must be kept for the backward pass.
- “Vanishing gradients mean the loss has reached its minimum.” A tiny gradient in early layers usually means the signal got crushed on the way back (saturated sigmoids, poor initialization), not that those layers are already good.
- “Each weight’s gradient only depends on its own layer.” It depends on everything downstream: every later layer’s weights and activations shape the upstream gradient that reaches it.
Check your understanding
Q1.A node computes u = w·x. During the backward pass it receives upstream gradient ∂L/∂u = −0.2, and the forward values were w = 3, x = 4. What is ∂L/∂w?
Q2.Why is reverse mode (backpropagation) the right choice for training neural networks, rather than forward mode?
Q3.A weight feeds into two different branches that both affect the loss. How does backprop compute its gradient?
Q4.A 12-layer network with sigmoid activations trains its last layers well but its first layers barely change. What's the most likely cause?
Q5.Why does training a large model need much more GPU memory than just running it?
Further reading
- blogCalculus on Computational Graphs: Backpropagation — Chris Olah's clear explanation of forward vs reverse mode, with pictures.
- courseCS231n: Backpropagation, Intuitions — Stanford's notes on local gradients and the add/multiply/max patterns.
- codemicrograd — Andrej Karpathy's tiny autograd engine; pair it with his video building it from scratch.
- videoBackpropagation calculus — 3Blue1Brown on the chain rule inside a network.
- paperLearning representations by back-propagating errors — Rumelhart, Hinton & Williams (1986), the paper that popularized backprop.
- paperAutomatic differentiation in machine learning: a survey — Baydin et al., a thorough tour of forward and reverse mode.