Backpropagation
The chain rule, organized: every gradient in one backward sweep.
A network with a billion weights needs a billion partial derivatives at every training step. Computing them one at a time would take a billion forward passes; backpropagation gets all of them for the price of about two more. This lesson derives the algorithm on computational graphs and in matrix form, counts its cost in time and memory, shows how to test an implementation against finite differences, and explains why gradients in deep networks tend to vanish or explode.
What you’ll learn
- Compute gradients on a computational graph with the reverse sweep, including the rule that contributions arriving along different paths add up.
- Derive the backpropagation equations for an MLP, and , and implement them for a mini-batch.
- Count the time and memory of a backward pass, and explain why it costs about twice the forward pass.
- Check gradients with central differences, choosing the step size and tolerance soundly, and trace vanishing and exploding gradients to long products of Jacobians.
Computational graphs and the chain rule
Any computation of a loss can be written as a computational graph: a directed acyclic graph whose nodes are intermediate values , each computed from its parents by an elementary operation, ending with the loss . Define each node's adjoint . A node influences only through its children, so the multivariable chain rule gives
Visit the nodes in reverse topological order: when a node is reached, all its children are done, so its adjoint is complete. One forward sweep computes and stores the values; one backward sweep computes every adjoint. This is reverse-mode automatic differentiation, and backpropagation is its application to neural networks.
| Node | Forward value | Local derivatives | Adjoint (backward sweep, bottom row first) |
|---|---|---|---|
| input | |||
| input | |||
| , | |||
| , | |||
A weight is used in two places in a network (shared weights, as in a convolution applied at two positions). The backward sweep computes and . What is ?
Show the answer
D.
is a node with two children, and the chain rule sums over children: . Convolutional and recurrent networks rely on this: a shared filter or recurrent matrix accumulates gradient from every position or time step where it is used.
The layer-by-layer equations
Use the notation of From Perceptrons to Deep Networks: , for , logits , and a per-example loss . The quantity that flows backward is the error signal of each layer's pre-activations, , a vector the size of the layer.
Output layer. For softmax with cross-entropy (or sigmoid with log loss) the gradient with respect to the logits is prediction minus target; for an identity output with the squared loss it is (without the , twice that):
Recursion. affects the loss only through , which feeds every . Sum over the children :
Parameters. appears only in , with coefficient , so each weight's gradient is the error at its output times the activation at its input: an outer product.
Mini-batch. Stack the examples' error signals as rows of and activations as rows of . The recursion becomes a matrix product and the gradient of the average loss a sum of outer products:
import numpy as np
def forward_backward(params, X, Y):
"""X: (B, d) inputs, Y: (B, k) one-hot targets, params: [(W, b), ...]."""
Hs, Zs = [X], []
for W, b in params[:-1]: # forward pass: cache Z and H
Zs.append(Hs[-1] @ W.T + b)
Hs.append(np.maximum(0.0, Zs[-1])) # ReLU
W, b = params[-1]
logits = Hs[-1] @ W.T + b
logits -= logits.max(axis=1, keepdims=True)
logP = logits - np.log(np.exp(logits).sum(axis=1, keepdims=True))
B = X.shape[0]
loss = -np.sum(Y * logP) / B
D = (np.exp(logP) - Y) / B # output deltas: (p - y) / B
grads = []
for l in range(len(params) - 1, -1, -1): # backward pass
W, b = params[l]
grads.append((D.T @ Hs[l], D.sum(axis=0)))
if l > 0:
D = (D @ W) * (Zs[l - 1] > 0) # times ReLU'(z) of the layer below
return loss, grads[::-1]Forward and backward passes for the ReLU network of From Perceptrons to Deep Networks, with a numerically stable log-softmax. Each backward iteration is the matrix equations above: one product for the weight gradient, one to pass the error signal down.
What it costs
Time. For a dense layer and a mini-batch of examples, the forward product costs floating-point operations: a multiply and an add per weight per example. The backward pass needs two products of the same size: to send the error signal down, and for the weight gradient. Activations and their derivatives add only . So a backward pass takes about two forward passes' worth of arithmetic, and a whole gradient about three, however many parameters there are. This is the cheap-gradient principle, and it is not specific to networks: Baur & Strassen (1983) proved that all partial derivatives of a rational function cost at most a small constant times evaluating the function (Autodiff in Depth).
Memory. The backward pass needs every layer's cached or : about numbers, growing with depth and with batch size, and for large models often more than the weights themselves. Inference keeps only the current layer. Gradient checkpointing stores a few layers and recomputes the others during the backward pass, trading computation for memory.
A dense layer maps 1,000 units to 1,000 units for a mini-batch of 100 examples, and its forward product costs flops. How many flops does its backward pass cost, in units of ?
Show the answer
4 × 10⁸ flops
Two products, each flops: for the error signal and for the weight gradient, in total. Estimating the same gradient by finite differences would take one forward pass per parameter, over passes for this layer's weights alone.
Checking gradients
Backpropagation code fails silently: a wrong gradient often still lowers the loss, just badly. The standard test compares it with a finite difference. Use the central difference, along a coordinate or along a random unit direction (one check then covers every parameter at once):
Expand both evaluations around . The even-order terms cancel, so the truncation error is ; the one-sided difference keeps the curvature term and is only .
Each evaluation of carries a rounding error of about , where is the machine epsilon, and the difference quotient divides it by . The total error is smallest where the two terms balance:
In double precision this suggests around to and errors of order (times problem-dependent constants); in single precision the best achievable error is only about , too coarse to catch subtle bugs. Run gradient checks in float64, and do not shrink below the optimum: the error grows again.
import numpy as np
def grad_check(loss_fn, grad_fn, theta, h=1e-6, seed=0):
"""Relative error between the analytic and the numerical directional derivative.
theta is a flat float64 vector; grad_fn(theta) returns a flat gradient."""
v = np.random.default_rng(seed).normal(size=theta.shape)
v /= np.linalg.norm(v) # random unit direction
numeric = (loss_fn(theta + h * v) - loss_fn(theta - h * v)) / (2 * h)
analytic = grad_fn(theta) @ v
return abs(numeric - analytic) / max(abs(numeric), abs(analytic), 1e-12)In one run on a small ReLU network in double precision, this check gave relative errors of about at , at , and again at : the U shape the derivation predicts. (At large the step can also cross ReLU kinks, so the error there varies a lot from run to run.) A correct implementation typically scores far below ; a bug usually shows up as an error of order or worse.
Common false alarms and real traps:
- Kinks. ReLU, max-pooling and absolute values are not differentiable everywhere. If a perturbation moves some pre-activation across 0, the difference quotient mixes two linear pieces and the check fails for that point only. Check at points away from kinks, or temporarily swap in a smooth activation.
- Randomness. Dropout masks, data augmentation and random sampling must be frozen, or the two evaluations compute different functions.
- Missing terms. Weight decay and auxiliary losses must be in both the analytic and the numerical loss. Normalization layers must see the same mini-batch in both evaluations.
A gradient check on a ReLU network gives relative errors near for most coordinates you test, but for one particular first-layer weight. What is the most likely explanation?
- The backward pass is wrong for every weight
- is too small for double precision
- The learning rate is too large
- For some training example, that weight's unit has a pre-activation within about of 0, so the finite difference straddles the ReLU's kink
Show the answer
D. For some training example, that weight's unit has a pre-activation within about of 0, so the finite difference straddles the ReLU's kink
A single bad coordinate among many good ones points to a local non-smoothness, not a systematic bug. If a perturbation of size flips a unit between on and off, the numerical derivative averages two different slopes. Re-check at a slightly different or input, or confirm that some pre-activation is near zero.
Vanishing and exploding gradients
Unroll the recursion. With , the error signal that reaches layer is the output error multiplied by one transposed Jacobian factor per layer above it:
The sigmoid's slope never exceeds , and it is far smaller wherever the unit saturates, so in a deep sigmoid network with moderately sized weights the early layers receive tiny gradients and learn slowly, while the last layers do all the work. Explosions come from large weights, and they are most severe in recurrent networks, where the same matrix is applied at every time step: the gradient from steps back behaves roughly like the -th power of a per-step factor. Exploded gradients produce huge steps, loss spikes and overflow to NaN.
In a 10-layer sigmoid network whose weight matrices all have spectral norm 1, the bound above multiplies the output error by over the 10 layers. What is of the largest value this factor can take?
Show the answer
-6
Each layer contributes at most , so the bound is , about : even in the best case, the first layer's gradient is a millionth of the size it would have without the activation slopes. Saturated units make it smaller still. ReLU's slope of exactly 1 on active units is a major reason it replaced the sigmoid in hidden layers.
| Remedy | What it does to the product of Jacobians | Where |
|---|---|---|
| ReLU-family activations | slope exactly 1 on active units: no saturation | From Perceptrons to Deep Networks |
| Variance-preserving initialization (Glorot, He, orthogonal) | keeps each layer's factor near 1 at the start of training | Initialization & Signal Propagation |
| Normalization layers | re-standardize pre-activations, keeping units out of saturation | Normalization Layers |
| Residual connections | each Jacobian becomes , so an identity path carries the gradient | Initialization & Signal Propagation |
| Gradient clipping | rescales , capping exploded steps | Pascanu, Mikolov & Bengio (2013) |
| Gated recurrent cells (LSTM, GRU) | additive memory updates with learned gates instead of repeated matrix products | Initialization & Signal Propagation |
Key takeaways
- Reverse mode on a computational graph computes in reverse topological order; contributions along different paths add, which is how shared weights accumulate gradient.
- For an MLP: , , ; over a mini-batch these are matrix products.
- A backward pass costs about two forward passes, whatever the number of parameters, but it needs every cached activation: memory grows with depth times batch size.
- Check gradients with central differences in float64 with near along random directions; expect relative errors far below , and watch for kinks, frozen randomness and missing loss terms.
- The error signal is a product of Jacobians, so it vanishes or explodes geometrically with depth or time; activations, initialization, normalization, residual paths, clipping and gating keep the product near 1.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Layer has , and its input is . What is ?
- A matrix,
- A matrix,
- A vector of length 64, equal to
- The scalar
Show the answer
B. A matrix,
maps 128 inputs to 64 units, so it is , and so is its gradient. Entry is : the error at the weight's output times the activation at its input, an outer product.
Why does the backward pass through a dense layer cost about twice its forward pass?
- It needs two matrix products of the same size as the forward one: one to pass the error signal down, one for the weight gradient
- It runs the forward pass a second time
- Derivatives of activation functions are expensive
- It must invert each weight matrix
Show the answer
A. It needs two matrix products of the same size as the forward one: one to pass the error signal down, one for the weight gradient
and each cost flops, like the forward product. The elementwise is negligible. No inverse is ever needed: backpropagation only multiplies by transposes.
You double both the batch size and the depth of a network (same width). Roughly how does the memory needed for the cached activations change?
- It stays the same
- It doubles
- It grows about fourfold
- It grows exponentially
Show the answer
C. It grows about fourfold
Cached activations take about numbers: twice the batch times twice as many layers is four times the memory. This is why activation memory, not weights, often limits training, and why checkpointing exists.
In a central-difference gradient check you halve from to , still far above the rounding-error regime. How does the truncation error change?
- It halves
- It is unchanged
- It doubles
- It falls to about a quarter
Show the answer
D. It falls to about a quarter
The central difference's leading error term is , so halving divides it by 4. A one-sided difference has an error and would only halve.
In a recurrent network the error signal is multiplied at each time step by a Jacobian of norm about . Roughly how much of the gradient from an input 50 steps back survives?
- About times the original
- About
- All of it, because the weights are shared across time
- About
Show the answer
B. About
: the contribution of distant inputs vanishes geometrically, so gradient descent barely learns long-range dependencies. With a norm of the factor would be : an explosion. Gated cells and clipping address the two cases.
Go deeper
- Autodiff in Depth · Forward and reverse mode, cost, memory and checkpointing.
- Initialization & Signal Propagation · Keeping activations and gradients alive through depth.
- Training Dynamics & the Edge of Stability · Large learning rates, sharpness and catapults.
Further reading
- D. E. Rumelhart, G. E. Hinton & R. J. Williams, "Learning representations by back-propagating errors," Nature 323, 533–536 (1986).
- I. Goodfellow, Y. Bengio & A. Courville, Deep Learning (MIT Press, 2016), section 6.5.
- A. G. Baydin, B. A. Pearlmutter, A. A. Radul & J. M. Siskind, "Automatic differentiation in machine learning: a survey," Journal of Machine Learning Research 18(153), 1–43 (2018).
- Y. Bengio, P. Simard & P. Frasconi, "Learning long-term dependencies with gradient descent is difficult," IEEE Transactions on Neural Networks 5(2), 157–166 (1994).