Backpropagation
One backward pass gives the gradient for millions of parameters. Local derivatives, the chain rule, and what the backward pass has to store.
Jump to a section
One loss, millions of parameters
Training needs the derivative of a single number, the loss, with respect to every parameter in the model. The naive way to get a derivative is to nudge a parameter and run the network again. A central difference costs two forward passes per parameter, so a 100-million-parameter model would need 200 million forward passes for one gradient step.
Backpropagation gets every one of those derivatives for roughly the price of two more forward passes. It is the chain rule, evaluated in the order that lets each intermediate result be reused: start at the loss and walk the computation graph backward once.
That order is the whole trick. Reverse-mode differentiation, of which backprop is the best-known case, costs one backward pass per scalar output. Forward-mode differentiation costs one pass per input. A training loss has one output and millions of inputs, so reverse mode wins by a factor the size of the model. Forward mode suits the opposite shape: few inputs and many outputs.
Local derivatives, multiplied backward
Take the smallest model that shows the mechanism: one weight , one input , a target and the loss at . The forward pass computes, and keeps, three values: the prediction , the error and the loss .
The backward pass starts from and visits the same operations in reverse. Each one multiplies the gradient it receives, the upstream gradient, by its own local derivative and hands the product on:
No operation needs to know anything about the rest of the graph. The squaring step knows its derivative is , and the multiply knows that . That locality is why a framework can differentiate any composition of operations it has backward rules for.
For vectors, the local derivative is a Jacobian. For a step with upstream gradient :
Frameworks never build that Jacobian. Each operation implements the product directly, as a vector-Jacobian product, which for most operations costs far less than materialising the matrix would.
One more rule covers graphs that branch. When a value feeds two later operations, its gradient is the sum of the gradients arriving along each path. Tied weights rely on this: an embedding matrix used at both the input and the output of a language model receives both contributions.
What a linear layer sends back
Most networks are linear layers with element-wise non-linearities between them. The diagram is a two-layer network: a linear layer, a ReLU, a second linear layer and the loss. Solid arrows are the forward pass; each dashed arrow carries a gradient computed from the one downstream of it times a local derivative.
Multiply the local derivatives
Each node shows its forward value and the gradient of L with respect to it. Backward: ∂L/∂r = 2r = −2, ∂r/∂(wx) = 1, ∂(wx)/∂w = x = 2, so ∂L/∂w = −4.
Exact inputs and equations appear with the figure.
Preparing the scientific figure…
The forward values and gradients are exact for one scalar example with x = 2, w = 1 and target y = 3.
Authored analytic exampleExperiment with related Studio inputs
For x = 2, w = 1, and target = 3: the prediction is 2, the residual is −1, and the loss is 1. Multiply the local derivatives to get dL/dw = −4.
A scalar worked example. Arrows show the forward computation; the gradient is evaluated by traversing that chain backward.
Read the related Studio connections
Input x -> Multiply by w : x = 2 Multiply by w -> Subtract target : prediction = 2 Subtract target -> Square : residual = -1 Square -> Loss : L = 1
For a linear layer with upstream gradient , the chain rule gives three results:
The weight gradient is the outer product of the upstream gradient with the layer's input, so the input has to survive from the forward pass. The input gradient is the upstream gradient for the layer before.
For an element-wise non-linearity the Jacobian is diagonal, and the product collapses to an element-wise one:
For ReLU, is 1 where and 0 elsewhere. The gradient passes through the active units and stops at the rest.
These rules also set the price of training. Over a batch, the forward pass of a linear layer is one matrix multiply. The backward pass needs two of the same size, one for and one for . That is the origin of the standard estimate of 6 FLOPs per parameter per training token, used by Kaplan et al. as : 2 for the forward multiply-add and 4 for the backward pass.
The derivative is not the update
Back to , where . Backpropagation's job ends with that number. Deciding what to do with it belongs to the optimizer.
With learning rate 0.1, gradient descent moves the weight to , and the loss falls to . With rate 0.3 the weight jumps to 2.2, the prediction overshoots to 4.4 and the loss rises to 1.96. Both updates used the correct gradient.
Keeping the two apart makes debugging tractable. Check the gradient on its own first, against a central finite difference:
With this gives , exact here because the loss is quadratic in . Run such checks in float64: in float32 a loss near 1 carries rounding error around , and dividing by turns that into an error near . If the gradient matches, look at the step size and the data before suspecting the differentiation.
In code
A manual backward pass for Linear → ReLU → MSE in NumPy, with every weight gradient checked against a central difference. Batch rows are examples, so the layer is x @ W and the transposes move: the weight gradient becomes .
1import numpy as np
2
3rng = np.random.default_rng(0)
4x = rng.normal(size=(8, 4)) # batch 8, in-dim 4
5y = rng.normal(size=(8, 2)) # targets, out-dim 2
6W = rng.normal(size=(4, 2)) * 0.1
7b = np.zeros(2)
8
9
10def forward(W, b):
11 z = x @ W + b
12 a = np.maximum(0, z) # ReLU
13 return z, a, np.mean((a - y) ** 2)
14
15
16# forward: keep z for the ReLU mask; x is needed for the weight gradient
17z, a, loss = forward(W, b)
18
19# backward: chain rule from the loss toward the inputs
20da = (2 / a.size) * (a - y) # dL/da from the mean squared error
21dz = da * (z > 0) # ReLU passes gradient where z > 0
22dW = x.T @ dz # dL/dW = xᵀ δ, same shape as W
23db = dz.sum(axis=0) # the bias gradient sums over the batch
24dx = dz @ W.T # dL/dx = δ Wᵀ, for an earlier layer
25assert dW.shape == W.shape and dx.shape == x.shape
26
27# central-difference check of every weight
28eps = 1e-6
29for i in range(W.shape[0]):
30 for j in range(W.shape[1]):
31 Wp, Wm = W.copy(), W.copy()
32 Wp[i, j] += eps
33 Wm[i, j] -= eps
34 numeric = (forward(Wp, b)[2] - forward(Wm, b)[2]) / (2 * eps)
35 assert abs(numeric - dW[i, j]) < 1e-6PyTorch's autograd does the same bookkeeping automatically. Each operation in the forward pass records the tensors its backward rule will need, and loss.backward() replays the recorded graph in reverse.
What the backward pass has to keep
Every backward rule above reads something the forward pass produced. The linear layer reads its input , ReLU reads which entries of were positive, and the squaring step read . Training therefore holds the activations of every layer from the moment they are computed until the backward pass has used them. That memory grows with batch size and depth; the weights do not grow with batch size at all.
Inference has no backward pass, so under torch.no_grad() each activation can be freed as soon as the next layer has consumed it.
Gradient checkpointing trades compute for that memory. It keeps only some activations and, during the backward pass, recomputes the others from the nearest saved one. Chen et al. showed that keeping one checkpoint every layers of an -layer network cuts activation memory to for roughly one extra forward pass. With the 2 + 4 FLOP split above, that extra forward pass makes each training step about a third more expensive.
Where gradients go wrong
Long products. The backward pass through a deep network multiplies one local Jacobian per layer, so factors below 1 shrink the gradient geometrically and factors above 1 grow it. The sigmoid's derivative never exceeds 0.25, so across ten sigmoid layers the activation derivatives alone contribute a factor of at most . ReLU's derivative is exactly 1 on active units, which removes that source of shrinkage.
Missing shortcuts. A residual block computing has Jacobian , so the gradient reaching always includes the upstream gradient unchanged. He et al. used this identity path to train a 152-layer network on ImageNet.
Exploding steps. When the product grows instead, one bad batch can produce a gradient large enough to wreck the weights. The usual guard is to clip the global gradient norm before the optimizer step.
Dead units. A ReLU whose input is negative for every example passes zero gradient to its incoming weights, so nothing will move them out of that state. A single oversized update can put a unit there for good.
Stale gradients. PyTorch adds each backward pass into .grad instead of overwriting it. That is what makes gradient accumulation over micro-batches work, and it is also why a missing optimizer.zero_grad() silently mixes every earlier step's gradient into the current one.
Sources and further reading
- Baydin et al., Automatic differentiation in machine learning: forward/reverse modes and computational graphs.
- Rumelhart, Hinton and Williams, Learning representations by back-propagating errors (1986): the paper that popularised backpropagation for multi-layer networks.
- Chen et al., Training Deep Nets with Sublinear Memory Cost (2016): gradient checkpointing and the square-root memory schedule.
- Kaplan et al., Scaling Laws for Neural Language Models (2020): the estimate of 6N training FLOPs per token.
- He et al., Deep Residual Learning for Image Recognition (2015): identity shortcuts and very deep networks.
Keep going
Ask your own question about Backpropagation, or start a guided session on it: six short pages, from the big picture to code you can run.