Backpropagation & Automatic Differentiation
Computational graphs, reverse mode and why a gradient costs only a few forward passes.
Backpropagation is not a neural-network trick. It is one instance of reverse-mode automatic differentiation, an algorithm that differentiates any program built from differentiable pieces and returns the exact gradient for a small constant multiple of the program's own cost. Here you derive it for a whole layer at once, count what it costs in time and memory, and see how PyTorch automates it.
What you’ll learn
- Express a network as a composition of primitives with local Jacobians, and explain why reverse mode computes the gradient with vector–Jacobian products only.
- Write backpropagation through a multilayer perceptron as matrix equations, first for a single example and then for a whole mini-batch.
- Count the cost of a gradient (backward about twice the forward FLOPs) and its activation memory, and explain how gradient checkpointing trades recomputation for memory.
- Compare forward mode (Jacobian–vector products) with reverse mode, and use PyTorch's autograd and a gradient check correctly.
Programs, Jacobians and the order of multiplication
A network is a computational graph of primitives: matrix products, additions, elementwise activations, a loss. Write the whole computation as a composition , where maps the value to and has the local Jacobian . The chain rule says the derivative of the composition is the product of the local Jacobians:
Multiplying from the right, first, builds full Jacobians of intermediate values with respect to all inputs: matrix–matrix products, hopeless when is the number of weights. Multiplying from the left starts with the row , and every later product is a row vector times a matrix. That is reverse mode, and backpropagation is reverse mode applied to a network.
Graphs are rarely simple chains. When a value is used by several primitives, its adjoint is the sum of the VJPs coming back from each use, , which is the multivariable chain rule. A reverse sweep therefore visits the nodes in reverse topological order, accumulating adjoints, so each primitive's VJP runs exactly once.
Backpropagation for a layer, in matrix form
Apply this to a multilayer perceptron with and for , with and the loss computed from . The quantity to propagate is the error signal , written as a column vector.
Unit of layer feeds every unit of layer , with . Sum over those paths:
The activation acts elementwise, so its Jacobian is diagonal, , and its VJP is an elementwise product:
Weight enters only , with . So each weight's gradient is the error at its output unit times the activation at its input unit, an outer product:
For a mini-batch, stack the examples as rows: , and has row equal to for the batch-mean loss. The per-example outer products sum into one matrix product:
BACKPROP-MLP(X, Y) // rows of X: B examples; Y: one-hot labels
H⁽⁰⁾ ← X
for ℓ = 1 … L: // forward pass, keeping Z⁽ℓ⁾ and H⁽ℓ⁾
Z⁽ℓ⁾ ← H⁽ℓ⁻¹⁾ W⁽ℓ⁾ᵀ + 1 b⁽ℓ⁾ᵀ
H⁽ℓ⁾ ← φ(Z⁽ℓ⁾) // no activation at the output layer
Δ ← (softmax(Z⁽ᴸ⁾) − Y) / B // ∂ℒ/∂Z⁽ᴸ⁾ for the mean cross-entropy
for ℓ = L … 1: // backward pass
∂W⁽ℓ⁾ ← Δᵀ H⁽ℓ⁻¹⁾ ; ∂b⁽ℓ⁾ ← Δᵀ 1
if ℓ > 1: Δ ← (Δ W⁽ℓ⁾) ⊙ φ′(Z⁽ℓ⁻¹⁾)
return all ∂W⁽ℓ⁾, ∂b⁽ℓ⁾The starting signal is the gradient of softmax followed by cross-entropy, derived in Deriving Backward Passes. Everything else is the derivation above, one layer at a time.
Layer has and the batch has examples. What is the shape of ?
- , the shape of
Show the answer
C. , the shape of
is (one error per example and output unit) and is , so is . A gradient always has the shape of the thing it differentiates, a quick test for transposition bugs.
What a gradient costs: time and memory
Time. Count FLOPs for one dense layer with inputs, outputs and a batch of , taking a multiply–add as 2 FLOPs. The forward product costs . The backward pass needs two products of the same size: to pass the error down, and for the weight gradient. So the backward pass costs about twice the forward pass, and a training step about three times, or FLOPs per weight per example. This is where the estimate for training a model with parameters on tokens comes from (Kaplan et al., 2020). Elementwise work (activations, their derivatives, biases) adds only per layer.
Beyond networks, the cheap gradient principle (Baur & Strassen, 1983, for arithmetic circuits; Griewank & Walther, 2008, for programs) guarantees that reverse mode returns the full gradient of a scalar function for a small constant multiple of the function's own operation count, independent of the number of inputs. The constant depends on the cost model; memory is the part that is not cheap.
Memory. The derivation needs and for every layer, and they are produced in the forward pass but consumed in reverse order. So all of them are stored at once: activation memory grows like depth × batch × width (× sequence length for transformers), while the weights grow like depth × width². For large batches and long sequences the activations, not the weights, fill the accelerator. Inference needs none of this, because each layer's input can be discarded once the next layer has it.
Gradient checkpointing trades compute for memory. Keep the activations only at every -th layer (the checkpoints) and discard the rest. During the backward pass, rerun the forward pass of one segment at a time from its checkpoint to regenerate its activations. Peak memory is about checkpoints plus one live segment of layers, minimized at , for one extra forward pass in total. Chen, Xu, Zhang and Guestrin (2016) brought this scheme to deep networks and noted that applying it recursively cuts memory to at extra forward computation. Checkpointing is older in automatic differentiation, where optimal ("binomial") schedules are known (Griewank & Walther, 2008).
A 100-layer network is checkpointed every layers, so peak memory is about layers' worth of activations. With the best , how many layers' worth is that (against 100 without checkpointing)?
Show the answer
20 layers
is smallest at , giving : five times less memory, paid for with one extra forward pass, which raises the step's cost from about three forward passes to about four.
import torch
from torch.utils.checkpoint import checkpoint
class Deep(torch.nn.Module):
def __init__(self, width=1024, depth=48):
super().__init__()
self.blocks = torch.nn.ModuleList(
torch.nn.Sequential(torch.nn.Linear(width, width), torch.nn.GELU())
for _ in range(depth))
def forward(self, x):
for block in self.blocks:
# keep only the block's input; recompute its insides during backward
x = checkpoint(block, x, use_reentrant=False)
return xCheckpointing every block, as here, stores one tensor per block instead of all the internals. PyTorch's documentation asks for use_reentrant to be passed explicitly and recommends False.
Forward mode versus reverse mode
Forward mode carries a tangent alongside every value, applying each primitive's JVP as the program runs. One forward-mode pass costs a small multiple of one evaluation and yields : the derivative of every output along one input direction. One reverse-mode pass yields : the derivative of one output combination with respect to every input. The shape of the function decides which is cheaper:
| For | Forward mode (JVP) | Reverse mode (VJP) |
|---|---|---|
| One pass gives | : one column combination | : one row combination |
| Full Jacobian | passes | passes |
| Gradient of a loss () | passes: one per weight | 1 pass |
| Extra memory | none beyond the current values | every intermediate needed by a VJP, until the sweep reaches it |
| Typical use | few inputs, many outputs; sensitivities; the outer pass of Hessian–vector products | training: millions of inputs, one loss |
import torch
from torch.func import jvp, vjp
A = torch.randn(1000, 3)
f = lambda x: torch.tanh(A @ x) # f: R^3 -> R^1000
x = torch.randn(3)
y, Jv = jvp(f, (x,), (torch.ones(3),)) # forward mode: J v, one pass
y, pullback = vjp(f, x) # reverse mode: returns a function
uJ, = pullback(torch.ones(1000)) # u^T J, one pass
J = torch.stack([jvp(f, (x,), (e,))[1] for e in torch.eye(3)], dim=1) # 3 passesWith 3 inputs and 1,000 outputs, the full Jacobian takes 3 forward-mode passes but 1,000 reverse-mode ones. Training is the opposite shape.
A simulator maps 4 physical parameters to a 10,000-pixel image. You need the full Jacobian of the image with respect to the parameters. Which mode, and how many passes?
- Reverse mode, 1 pass, as for any gradient
- Forward mode, 4 passes
- Reverse mode, 4 passes
- Forward mode, 10,000 passes
Show the answer
B. Forward mode, 4 passes
Forward mode gives one column per pass, so 4 passes cover all 4 parameters. Reverse mode gives one row per pass and would need 10,000. The rule: forward mode when inputs are few, reverse mode when outputs are few.
Autograd in PyTorch, and checking it
PyTorch builds the graph as your code runs (define-by-run): every operation on a tensor with requires_grad=True records a node holding its VJP and whatever it saved for it. Ordinary Python control flow just works: the graph records whichever operations actually ran, so a loop or a data-dependent branch can differ from one batch to the next. loss.backward() runs the reverse sweep from a scalar and adds each leaf's gradient into its .grad, then frees the graph. Four habits follow:
- Zero (or set to
None) the gradients before each backward pass, since.gradaccumulates. Accumulation is a feature: summing gradients over several small batches simulates one big batch. - Wrap evaluation and parameter updates in
torch.no_grad(), so nothing is recorded and no activations are kept. - Use
.detach()to get the same values cut off from the graph, for logging or for a stop-gradient. - Use
torch.autograd.grad(out, inputs)to get gradients as return values instead of in.grad; withcreate_graph=Truethe result is itself differentiable, which gives higher derivatives.
import torch
import torch.nn.functional as F
torch.manual_seed(0)
X, y = torch.randn(64, 10), torch.randint(0, 3, (64,)) # a batch: inputs, labels
W1 = (0.3 * torch.randn(32, 10)).requires_grad_() # leaf tensors to train
W2 = (0.2 * torch.randn(3, 32)).requires_grad_()
for step in range(100):
H = torch.tanh(X @ W1.T) # the graph is recorded as this runs
loss = F.cross_entropy(H @ W2.T, y) # mean over the batch
loss.backward() # reverse sweep: fills W1.grad, W2.grad
with torch.no_grad(): # the update itself is not recorded
for W in (W1, W2):
W -= 0.5 * W.grad
W.grad = None # else the next backward() adds to it
features = H.detach() # same values, no graph attachedIn real code torch.nn.Linear and torch.optim.SGD do this bookkeeping, and optimizer.zero_grad() resets the gradients.
A hand-written backward pass is easy to get subtly wrong, so test it. A gradient check compares it with central differences, , whose truncation error is while rounding error grows like . Use double precision, a step around , a few random coordinates and the relative error. In double precision a correct gradient typically agrees to many digits, while a bug usually shows up as a disagreement in the first or second digit; kinks such as ReLU's at can cause rare false alarms.
def max_rel_error(f, x, h=1e-6, k=5):
"""Autograd vs central differences on k random coordinates, in float64."""
x = x.detach().double().requires_grad_()
g = torch.autograd.grad(f(x), x)[0].reshape(-1)
worst = 0.0
for i in torch.randint(0, x.numel(), (k,)).tolist():
e = torch.zeros(x.numel(), dtype=x.dtype)
e[i] = h
e = e.reshape(x.shape)
with torch.no_grad():
fd = (f(x + e) - f(x - e)).item() / (2 * h)
worst = max(worst, abs(fd - g[i].item()) / max(abs(fd), abs(g[i].item()), 1e-12))
return worst
# built in: checks every entry of the Jacobian; its defaults assume float64 inputs
torch.autograd.gradcheck(torch.tanh, (torch.randn(4, dtype=torch.double, requires_grad=True),))f must return a scalar. torch.autograd.gradcheck raises an error on a mismatch; its documentation warns that it will likely fail on single-precision inputs.
Key takeaways
- Backpropagation is reverse-mode automatic differentiation: the chain rule evaluated from the loss backward as a sequence of vector–Jacobian products, with adjoints summed where a value is used more than once.
- For an MLP, and ; over a batch these become the matrix products and .
- The backward pass costs about twice the forward FLOPs (6 FLOPs per weight per example in total), and it needs every stored activation, so memory grows with depth × batch; checkpointing every layers cuts it to for one extra forward pass.
- Forward mode (JVPs) costs one pass per input and reverse mode (VJPs) one pass per output: reverse for training, forward for few-input sensitivities and Hessian–vector products.
- PyTorch records the graph as code runs and accumulates into
.grad; useno_grad,detachand gradient checks in double precision.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
With and , which is the error signal ?
- , with no activation term
Show the answer
C.
The VJP of multiplies by , and the VJP of the elementwise activation multiplies by at the layer's own pre-activation .
About how many FLOPs does one training step (forward plus backward) spend per weight of a dense layer, per example?
Show the answer
A.
Forward: one multiply–add per weight per example, FLOPs. Backward: two products of the same size, and , another . Total , hence .
Why do deep learning libraries train with reverse mode rather than forward mode?
- Forward mode gives only approximate derivatives
- Reverse mode needs less memory
- Forward mode cannot handle nonlinear activations
- The loss is one number depending on millions of weights, and reverse mode gets all of their derivatives in one pass instead of one pass per weight
Show the answer
D. The loss is one number depending on millions of weights, and reverse mode gets all of their derivatives in one pass instead of one pass per weight
For reverse mode costs one sweep for the whole gradient; forward mode costs sweeps. Reverse mode pays for it in memory, since it must store intermediates.
A training loop calls loss.backward() and steps the optimizer, but never zeroes the gradients. What happens?
- Nothing:
backward()overwrites.gradeach time - Each
.gradholds the sum of all gradients so far, so the steps keep growing and point in a stale direction - PyTorch raises an error on the second call
- The gradients are averaged over steps, which acts like momentum
Show the answer
B. Each .grad holds the sum of all gradients so far, so the steps keep growing and point in a stale direction
backward() adds into .grad. Without zeroing, step uses the sum of gradients. Deliberate accumulation over a few micro-batches, followed by one step and a reset, is how large batches are simulated.
Go deeper
- Deriving Backward Passes · Vector–Jacobian products for matmul, softmax, normalization and convolution.
- Implicit Differentiation & Equilibrium Models · Differentiating through fixed points and optimization layers without unrolling.
- Influence Functions & Data Attribution · Tracing a prediction back to the training examples that caused it.
Further reading
- I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, §6.5 "Back-Propagation and Other Differentiation Algorithms" (MIT Press, 2016).
- 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) (2018).
- A. Griewank & A. Walther, Evaluating Derivatives: Principles and Techniques of Algorithmic Differentiation (2nd ed., SIAM, 2008).
- T. Chen, B. Xu, C. Zhang & C. Guestrin, "Training deep nets with sublinear memory cost," arXiv:1604.06174 (2016).