Skip to content
BIASED

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, zl=Wlhl−1+blz_l = W_l h_{l-1} + b_l and hl=φ(zl)h_l = \varphi(z_l) with h0=xh_0 = x. It left one question open, and it comes with a bill. The small digit classifier 64→128→64→1064 \to 128 \to 64 \to 10 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 θi\theta_i both ways, rerun the network and divide:

∂L∂θi≈L(θ+εei)−L(θ−εei)2ε.\frac{\partial L}{\partial \theta_i} \approx \frac{L(\theta + \varepsilon e_i) - L(\theta - \varepsilon e_i)}{2\varepsilon}.

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 LL 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 LL 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 uu to vv means that vv is computed from uu. The forward pass evaluates the nodes in order.

For every node write

uˉ=∂L∂u,\bar u = \frac{\partial L}{\partial u},

the adjoint of uu. It has the shape of uu, as every gradient does in the topic Matrix calculus. The backward pass starts from Lˉ=1\bar L = 1 and visits the nodes in reverse order. If uu feeds several nodes v1,…,vkv_1, \dots, v_k, its influence on LL goes through all of them, and the multivariate chain rule adds up the contributions:

uˉ=∑c=1kvˉc ∂vc∂u.\bar u = \sum_{c=1}^{k} \bar v_c \, \frac{\partial v_c}{\partial u}.

A sigmoid unit with the squared error shows the whole procedure: z=wx+bz = wx + b, a=σ(z)a = \sigma(z), L=(a−y)2L = (a - y)^2 at x=1.5x = 1.5, w=0.8w = 0.8, b=−0.2b = -0.2, y=1y = 1.

node forward adjoint backward
z=wx+bz = wx + b 1.01.0 aˉ=2(a−y)\bar a = 2(a - y) −0.538-0.538
a=σ(z)a = \sigma(z) 0.7310.731 zˉ=aˉ a(1−a)=−0.538⋅0.197\bar z = \bar a \, a(1 - a) = -0.538 \cdot 0.197 −0.106-0.106
L=(a−y)2L = (a - y)^2 0.07230.0723 wˉ=zˉ x\bar w = \bar z \, x,  bˉ=zˉ\ \bar b = \bar z −0.159-0.159,  −0.106\ -0.106

Each step of the backward column multiplies by one local derivative. The local derivative σ′(z)=a(1−a)\sigma'(z) = a(1 - a) uses the value aa 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 v=g(u)v = g(u) with u∈Rnu \in \mathbb R^n, v∈Rmv \in \mathbb R^m and the m×nm \times n Jacobian JJ, then

uˉ=J⊤vˉ.\bar u = J^\top \bar v.

The backward pass multiplies vectors by transposed Jacobians and never forms the Jacobians as matrices. Three operations cover an MLP.

A linear layer z=Wh+bz = Wh + b with W∈Rm×nW \in \mathbb R^{m \times n}. The topic Matrix calculus derived its weight gradient; the input gradient is the transposed Jacobian W⊤W^\top:

Wˉ=zˉ h⊤,bˉ=zˉ,hˉ=W⊤zˉ.\bar W = \bar z \, h^\top, \qquad \bar b = \bar z, \qquad \bar h = W^\top \bar z.

The weight gradient is an outer product: the adjoint arriving from above times the input stored during the forward pass.

An elementwise activation h=φ(z)h = \varphi(z). Its Jacobian is diag⁡(φ′(z))\operatorname{diag}(\varphi'(z)), so

zˉ=φ′(z)⊙hˉ,\bar z = \varphi'(z) \odot \bar h,

where ⊙\odot is the elementwise product. For ReLU, φ′(z)\varphi'(z) is the mask 1[z>0]\mathbf 1[z > 0]: the gradient passes through active units unchanged and stops at inactive ones.

A mini-batch. As in the previous topic, the nn examples are the rows of HH, and Z=HW⊤+1b⊤Z = H W^\top + \mathbf 1 b^\top. With the loss averaged over the batch,

Hˉ=Zˉ W,Wˉ=Zˉ⊤H,bˉ=Zˉ⊤1.\bar H = \bar Z \, W, \qquad \bar W = \bar Z^\top H, \qquad \bar b = \bar Z^\top \mathbf 1.

The product Zˉ⊤H\bar Z^\top H 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 x∈Rdx \in \mathbb R^d, a hidden layer of d1d_1 ReLU units and KK classes with true class yy:

z1=W1x+b1,h=ReLU⁡(z1),z2=W2h+b2,L=−log⁡softmax⁡(z2)y.z_1 = W_1 x + b_1, \qquad h = \operatorname{ReLU}(z_1), \qquad z_2 = W_2 h + b_2, \qquad L = -\log \operatorname{softmax}(z_2)_y.

The backward pass starts at the logits. Softmax with cross-entropy has the adjoint

zˉ2=p−ey,\bar z_2 = p - e_y,

where p=softmax⁡(z2)p = \operatorname{softmax}(z_2) and eye_y is the one-hot vector of class yy. 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 hh are learned.

Then the three rules, in the reverse order of the forward pass:

Wˉ2=zˉ2 h⊤,bˉ2=zˉ2,hˉ=W2⊤zˉ2,\bar W_2 = \bar z_2 \, h^\top, \qquad \bar b_2 = \bar z_2, \qquad \bar h = W_2^\top \bar z_2, zˉ1=hˉ⊙1[z1>0],Wˉ1=zˉ1 x⊤,bˉ1=zˉ1.\bar z_1 = \bar h \odot \mathbf 1[z_1 > 0], \qquad \bar W_1 = \bar z_1 \, x^\top, \qquad \bar b_1 = \bar z_1.

The shapes confirm every line:

quantity shape adjoint shapes of the product
z2z_2 KK p−eyp - e_y KK
W2W_2 K×d1K \times d_1 zˉ2h⊤\bar z_2 h^\top (K×1)(1×d1)(K \times 1)(1 \times d_1)
hh d1d_1 W2⊤zˉ2W_2^\top \bar z_2 (d1×K)(K)(d_1 \times K)(K)
z1z_1 d1d_1 hˉ⊙1[z1>0]\bar h \odot \mathbf 1[z_1 > 0] d1d_1
W1W_1 d1×dd_1 \times d zˉ1x⊤\bar z_1 x^\top (d1×1)(1×d)(d_1 \times 1)(1 \times d)

For a batch of nn examples with the averaged loss, Zˉ2=(P−Y)/n\bar Z_2 = (P - Y)/n, where the rows of PP are the predicted probabilities and the rows of YY 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 d=2d = 2, d1=3d_1 = 3, K=2K = 2, zero biases, the first class as the true one (y=1y = 1), and

x=(12),W1=(10−110.5−1),W2=(1−120.51−1).x = \begin{pmatrix} 1 \\ 2 \end{pmatrix}, \qquad W_1 = \begin{pmatrix} 1 & 0 \\ -1 & 1 \\ 0.5 & -1 \end{pmatrix}, \qquad W_2 = \begin{pmatrix} 1 & -1 & 2 \\ 0.5 & 1 & -1 \end{pmatrix}.

Forward: z1=(1,1,−1.5)z_1 = (1, 1, -1.5), so h=(1,1,0)h = (1, 1, 0); then z2=(0,1.5)z_2 = (0, 1.5), p=(0.182,0.818)p = (0.182, 0.818) and L=−log⁡0.182=1.701L = -\log 0.182 = 1.701.

Backward:

  • zˉ2=p−e1=(−0.818,0.818)\bar z_2 = p - e_1 = (-0.818, 0.818);
  • Wˉ2=zˉ2h⊤\bar W_2 = \bar z_2 h^\top has the rows (−0.818,−0.818,0)(-0.818, -0.818, 0) and (0.818,0.818,0)(0.818, 0.818, 0);
  • hˉ=W2⊤zˉ2=(−0.409,1.635,−2.453)\bar h = W_2^\top \bar z_2 = (-0.409, 1.635, -2.453);
  • zˉ1=hˉ⊙(1,1,0)=(−0.409,1.635,0)\bar z_1 = \bar h \odot (1, 1, 0) = (-0.409, 1.635, 0);
  • Wˉ1=zˉ1x⊤\bar W_1 = \bar z_1 x^\top has the rows (−0.409,−0.818)(-0.409, -0.818), (1.635,3.270)(1.635, 3.270) and (0,0)(0, 0).

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 hˉ3=−2.453\bar h_3 = -2.453 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 nn examples. The forward product HW⊤H W^\top takes n din doutn \, d_{\text{in}} \, d_{\text{out}} multiply–adds. The backward pass computes two products of the same size, ZˉW\bar Z W and Zˉ⊤H\bar Z^\top H, 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 f:Rn→Rmf: \mathbb R^n \to \mathbb R^m, one reverse sweep gives one row of the Jacobian, a vector–Jacobian product vˉ⊤J\bar v^\top J. A loss is a single number, m=1m = 1, so one sweep gives the whole gradient.

Forward mode runs the chain rule the other way. Along with every value uu it carries the derivative u˙\dot u along one input direction and produces a Jacobian–vector product JvJ v in one pass. A gradient with respect to nn parameters then needs nn 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: hh for Wˉ2\bar W_2, the ReLU masks for zˉ1\bar z_1. 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 nn layers it needs O(n)O(\sqrt n) 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 θ\theta 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 Lˉ=1\bar L = 1 loss.backward()
the adjoint θˉ\bar\theta 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 .grad instead 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 with optimizer.zero_grad().
  • Kinks get a convention. ReLU has no derivative at 0, and PyTorch uses 0 there. Any value in [0,1][0, 1] is a valid subgradient, and exact zeros are rare in practice.
  • Discrete choices have no gradient. torch.argmax returns 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

∣gbackprop−gnumeric∣max⁡(∣gbackprop∣,∣gnumeric∣,δ),\frac{\lvert g_{\text{backprop}} - g_{\text{numeric}} \rvert}{\max\big(\lvert g_{\text{backprop}} \rvert, \lvert g_{\text{numeric}} \rvert, \delta\big)},

with a small floor such as δ=10−8\delta = 10^{-8}, so that two zero gradients count as agreement and not as 0/00/0. The topic Derivatives and Taylor series showed why the difference is central: the even terms of the Taylor expansion cancel, and the error is 16ε2L′′′\tfrac16 \varepsilon^2 L''' instead of the 12εL′′\tfrac12 \varepsilon L'' of the one-sided quotient.

A smaller ε\varepsilon is not always better. Every value of the loss carries a rounding error of about 10−1610^{-16} in double precision, and division by ε\varepsilon amplifies it. For the weight (W1)11(W_1)_{11} of the worked example, the central difference is off by 2⋅10−52 \cdot 10^{-5} at ε=10−1\varepsilon = 10^{-1}, by 4⋅10−124 \cdot 10^{-12} at ε=10−5\varepsilon = 10^{-5}, and by 10−410^{-4} again at ε=10−12\varepsilon = 10^{-12}. In practice:

  • compute in double precision, where the check is reliable (in single precision rounding is about 10−710^{-7});
  • take ε\varepsilon around 10−610^{-6} to 10−510^{-5}; a relative error near 10−810^{-8} or below means agreement, near 10−210^{-2} or above a bug;
  • avoid points next to a kink: if a ReLU input lies within ε\varepsilon 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+00

The correct backward pass agrees to 10−1010^{-10}. Without the mask the third unit's weights get a nonzero gradient where the true one is zero, and the relative error jumps to 11.

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.

Full notes

Answers are saved on the server and tied to this browser until you sign in.