Backpropagation
How one backward sweep gives the gradient with respect to every weight of a network: the computational graph, the chain rule in matrix form with shapes, the forward and backward pass of a two-layer network with cross-entropy, the cost of reverse mode, autograd in PyTorch and checking gradients by finite differences.
The bill for a gradient
The topic From linear models to networks built a network as a stack of layers, and with . It left one question open, and it comes with a bill. The small digit classifier from that topic already has 17,226 parameters, and gradient descent (see the topic Gradient descent) needs the derivative of the loss with respect to every one of them, at every step.
The baseline is the definition of the derivative. Nudge one parameter both ways, rerun the network and divide:
This costs two forward passes per parameter, and the answer is only approximate. A network with millions of weights would need millions of passes for a single step.
The calculus is already in place. The topic Gradients, Jacobians and Hessians showed that the chain rule is a product of Jacobians, and that multiplying them from the loss backwards gives the gradient of a small network with respect to its input in one sweep. The topic Matrix calculus found the gradient of a linear layer with respect to its weight matrix. Here these pieces become backpropagation: the gradient with respect to every weight of a network, for a whole batch, with a classification loss, for the price of about three forward passes. Then we let PyTorch do it and learn to check a gradient written by hand.
The key idea fits in one sentence. All partial derivatives of share the factors that lie between a parameter and the loss, so if we compute from the loss backwards, each shared factor is computed once and reused for everything below it.
The computational graph
Any computation of is a chain of elementary operations. Draw it as a directed acyclic graph, the computational graph: the nodes are intermediate values, and an edge from to means that is computed from . The forward pass evaluates the nodes in order.
For every node write
the adjoint of . It has the shape of , as every gradient does in the topic Matrix calculus. The backward pass starts from and visits the nodes in reverse order. If feeds several nodes , its influence on goes through all of them, and the multivariate chain rule adds up the contributions:
A sigmoid unit with the squared error shows the whole procedure: , , at , , , .
| node | forward | adjoint | backward |
|---|---|---|---|
| , | , |
Each step of the backward column multiplies by one local derivative. The local derivative uses the value from the forward pass. This is why the forward pass keeps its values: the backward pass will need them.
Three rules for layers
With vectors the rule is the same, and it reads as a transposed Jacobian. If with , and the Jacobian , then
The backward pass multiplies vectors by transposed Jacobians and never forms the Jacobians as matrices. Three operations cover an MLP.
A linear layer with . The topic Matrix calculus derived its weight gradient; the input gradient is the transposed Jacobian :
The weight gradient is an outer product: the adjoint arriving from above times the input stored during the forward pass.
An elementwise activation . Its Jacobian is , so
where is the elementwise product. For ReLU, is the mask : the gradient passes through active units unchanged and stops at inactive ones.
A mini-batch. As in the previous topic, the examples are the rows of , and . With the loss averaged over the batch,
The product sums the per-example outer products, which is how the gradients of a batch add up. Shapes are a reliable guard here: the adjoint has the shape of its variable, and there is usually only one way to multiply the factors so that the shapes match.
A two-layer network, end to end
Now a whole classifier. Take , a hidden layer of ReLU units and classes with true class :
The backward pass starts at the logits. Softmax with cross-entropy has the adjoint
where and is the one-hot vector of class . It is the gradient from the topics Matrix calculus and Multiclass and multilabel classification: predicted probabilities minus the target. A network ends exactly like softmax regression; only its features are learned.
Then the three rules, in the reverse order of the forward pass:
The shapes confirm every line:
| quantity | shape | adjoint | shapes of the product |
|---|---|---|---|
For a batch of examples with the averaged loss, , where the rows of are the predicted probabilities and the rows of the one-hot targets. From there the batch rules of the previous block take over.
The example in numbers
Numbers make the flow visible. Take , , , zero biases, the first class as the true one (), and
Forward: , so ; then , and .
Backward:
- ;
- has the rows and ;
- ;
- ;
- has the rows , and .
The same in NumPy. In code the classes are numbered from 0, so the first class is index 0:
import numpy as np
x, y = np.array([1.0, 2.0]), 0 # the true class is the first one, index 0
W1 = np.array([[1.0, 0.0], [-1.0, 1.0], [0.5, -1.0]])
W2 = np.array([[1.0, -1.0, 2.0], [0.5, 1.0, -1.0]])
def forward_backward(W1, W2, mask=True):
z1 = W1 @ x; h = np.maximum(z1, 0); z2 = W2 @ h
p = np.exp(z2) / np.exp(z2).sum(); L = -np.log(p[y])
dz2 = p - np.eye(2)[y] # softmax + cross-entropy
dh = W2.T @ dz2
dz1 = np.where(z1 > 0, dh, 0.0) if mask else dh # mask=False plants a bug
return L, np.outer(dz1, x), np.outer(dz2, h)
L, dW1, dW2 = forward_backward(W1, W2)
print(round(L, 3))
print(dW1.round(3))1.701
[[-0.409 -0.818]
[ 1.635 3.27 ]
[ 0. 0. ]]Look at the third hidden unit. Its adjoint is the largest in magnitude, yet the unit is inactive, the mask stops the signal, and its incoming weights get a zero gradient from this example. A unit that is inactive on every example never learns. This is the dead ReLU from the previous topic, now seen from the gradient's side.
What the backward pass costs
Why is the price about three forward passes? Count the work of one linear layer on a batch of examples. The forward product takes multiply–adds. The backward pass computes two products of the same size, and , so it costs twice as much; the elementwise steps are negligible next to the matrix products. Forward plus backward is about three forward passes, whatever the number of parameters. Numerical differentiation pays two forward passes per parameter.
This is a special case of reverse-mode automatic differentiation. For a map , one reverse sweep gives one row of the Jacobian, a vector–Jacobian product . A loss is a single number, , so one sweep gives the whole gradient.
Forward mode runs the chain rule the other way. Along with every value it carries the derivative along one input direction and produces a Jacobian–vector product in one pass. A gradient with respect to parameters then needs passes. Forward mode wins when there are few inputs and many outputs. Training has millions of inputs, the parameters, and one output, the loss, which is why deep learning libraries are built on reverse mode.
The price of reverse mode is memory. The backward pass needs the forward values: for , the ReLU masks for . So the activations of all layers are kept until the backward pass reaches them, and in large networks they, not the parameters, fill the accelerator's memory. Gradient checkpointing keeps only some layers and recomputes the rest during the backward pass. For a chain of layers it needs memory for the cost of about one extra forward pass (Chen et al., 2016).
What autograd does
PyTorch implements reverse mode for us. During the forward pass, every operation on a tensor with requires_grad=True records a node of the computational graph, together with a function that maps the adjoint of its output to the adjoints of its inputs. The graph is rebuilt on every forward pass, so ordinary Python if and for are differentiable. The topic PyTorch and automatic differentiation of the Deep Learning course builds a small autograd from scratch; here we only map it onto the formulas.
| mathematics | PyTorch |
|---|---|
| the parameters | tensors with requires_grad=True (every nn.Parameter) |
| the recorded graph | the chain of grad_fn nodes attached to the results |
| start the backward pass with | loss.backward() |
| the adjoint | param.grad |
| the sum over the users of a node | gradients are added into .grad |
The worked example, now without a single derivative written by hand:
import torch
x = torch.tensor([1.0, 2.0])
W1 = torch.tensor([[1.0, 0.0], [-1.0, 1.0], [0.5, -1.0]], requires_grad=True)
W2 = torch.tensor([[1.0, -1.0, 2.0], [0.5, 1.0, -1.0]], requires_grad=True)
z2 = W2 @ torch.relu(W1 @ x) # logits; the biases are zero
loss = torch.nn.functional.cross_entropy(z2[None], torch.tensor([0]))
print(round(loss.item(), 3), loss.grad_fn.name())
loss.backward() # starts the backward pass with 1
print(W1.grad)1.701 NllLossBackward0
tensor([[-0.4088, -0.8176],
[ 1.6351, 3.2703],
[ 0.0000, 0.0000]])Three conventions are worth knowing.
- Gradients accumulate.
backward()adds into.gradinstead of overwriting it. This is the sum over users from the chain rule, and it lets you accumulate gradients over several small batches on purpose. It is also why every training step begins withoptimizer.zero_grad(). - Kinks get a convention. ReLU has no derivative at 0, and PyTorch uses 0 there. Any value in is a valid subgradient, and exact zeros are rare in practice.
- Discrete choices have no gradient.
torch.argmaxreturns an integer index outside the graph. A loss that depends on the choice only through such an index sends nothing back to the scores. When the choice itself must be learned, it is replaced by something smooth, such as a softmax with a temperature.
Autograd computes exact derivatives of the program that ran, up to rounding. It does not judge them: a gradient that is nearly zero or enormous is computed just as faithfully.
Checking gradients, and what comes next
A backward pass written by hand, or a custom autograd function, can be wrong in a way that still lets the loss decrease. The standard test compares it, coordinate by coordinate, with the central difference of the first block, through the relative error
with a small floor such as , so that two zero gradients count as agreement and not as . The topic Derivatives and Taylor series showed why the difference is central: the even terms of the Taylor expansion cancel, and the error is instead of the of the one-sided quotient.
A smaller is not always better. Every value of the loss carries a rounding error of about in double precision, and division by amplifies it. For the weight of the worked example, the central difference is off by at , by at , and by again at . In practice:
- compute in double precision, where the check is reliable (in single precision rounding is about );
- take around to ; a relative error near or below means agreement, near or above a bug;
- avoid points next to a kink: if a ReLU input lies within of zero, the two sides see different slopes;
- in a large network check a few random coordinates of each parameter tensor.
Here is the check on all 12 weights of the worked example. It reuses forward_backward from that block; mask=False drops the ReLU mask from the backward pass, a typical bug:
def check(mask, eps=1e-6):
_, dW1, dW2 = forward_backward(W1, W2, mask)
worst = 0.0
for P, G in ((W1, dW1), (W2, dW2)):
for i in np.ndindex(P.shape):
old = P[i]
P[i] = old + eps; Lp = forward_backward(W1, W2)[0]
P[i] = old - eps; Lm = forward_backward(W1, W2)[0]
P[i] = old
num = (Lp - Lm) / (2 * eps)
worst = max(worst, abs(num - G[i]) / max(abs(num), abs(G[i]), 1e-8))
return worst
print(f"{check(True):.1e} {check(False):.1e}")9.1e-11 1.0e+00The correct backward pass agrees to . Without the mask the third unit's weights get a nonzero gradient where the true one is zero, and the relative error jumps to .
We now have exact gradients for a network of any depth. Exact does not mean useful. In a deep stack the gradient is a product of one Jacobian per layer and can shrink or grow geometrically, and a network flexible enough to fit anything also fits the noise in its labels. The next topic, Training deep networks, collects what makes deep networks trainable and keeps them from overfitting: initialization that preserves the scale of signals, dropout, weight decay, learning-rate schedules, residual connections and normalization.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.