Module 3

Backpropagation

Module 0 pushed gradients back through a graph one number at a time. Backpropagation is the same sweep done a whole layer at a time, and it comes down to three matrix formulas.

Why it matters

These three formulas are what every deep-learning library runs when you ask for a gradient, and they are the reason training a network costs only about as much as running it twice. Knowing them in matrix form also explains things that otherwise look like folklore: why activations must be stored, why saturated units stop learning, and why gradients can shrink or blow up with depth.

The idea

The forward pass, with names for everything

Take a network of $L$ layers and a batch of $n$ examples stacked as the rows of $X$. Keep both the pre-activations $Z$ and the activations $A$ of every layer:

$$A^{(0)} = X, \qquad Z^{(l)} = A^{(l-1)} W^{(l)} + b^{(l)}, \qquad A^{(l)} = \phi\big(Z^{(l)}\big).$$

To keep the algebra clean, let the last layer be linear, $\hat Y = Z^{(L)}$, and use half the mean squared error as the loss:

$$\mathcal{L} = \frac{1}{2n} \big\lVert \hat Y - Y \big\rVert^2 .$$

The backward pass

Define $\Delta^{(l)} = \partial \mathcal{L} / \partial Z^{(l)}$: how the loss responds to each pre-activation of layer $l$. It has the same shape as $Z^{(l)}$. Backpropagation computes $\Delta^{(L)}$ first and works down.

  1. Start at the output. Differentiating the loss directly, $$\Delta^{(L)} = \frac{1}{n} \big(\hat Y - Y\big).$$
  2. Read off the parameter gradients of a layer from its $\Delta$ and its input: $$\frac{\partial \mathcal{L}}{\partial W^{(l)}} = A^{(l-1)\top} \Delta^{(l)}, \qquad \frac{\partial \mathcal{L}}{\partial b^{(l)}} = \mathbf{1}^{\top} \Delta^{(l)} \;\;\text{(the column sums of } \Delta^{(l)}\text{)}.$$
  3. Step down one layer, through the weights and then through the activation: $$\Delta^{(l-1)} = \Big(\Delta^{(l)} W^{(l)\top}\Big) \odot \phi'\big(Z^{(l-1)}\big),$$ where $\odot$ multiplies entry by entry. For tanh, $\phi'(Z^{(l-1)}) = 1 - \big(A^{(l-1)}\big)^2$.

Repeat steps 2 and 3 until layer 1. That is the whole algorithm.

Where the formulas come from

Write one entry of the forward step: $Z_{ij} = \sum_k A_{ik} W_{kj} + b_j$, with $A$ the layer's input. The entry $W_{kj}$ affects the loss only through column $j$ of $Z$, once for each example $i$, so by the chain rule from module 0

$$\frac{\partial \mathcal{L}}{\partial W_{kj}} = \sum_i \Delta_{ij}\, A_{ik} = \big(A^{\top} \Delta\big)_{kj}, \qquad \frac{\partial \mathcal{L}}{\partial A_{ik}} = \sum_j \Delta_{ij}\, W_{kj} = \big(\Delta W^{\top}\big)_{ik}.$$

The first is formula 2. The second, multiplied by the slope of the activation that produced $A$, is formula 3. You never have to remember where the transposes go: the gradient with respect to a matrix always has the shape of that matrix, and only one arrangement of the factors has that shape.

With a sigmoid output and cross-entropy loss, as in modules 1 and 2, only step 1 changes, and barely: $\Delta^{(L)} = \frac{1}{n}(p - y)$. Look back at the training function you were given in module 2: its three gradient lines are steps 1, 3 and 2.

What it costs

Each backward step is a matrix product of the same size as the forward step it mirrors, so a full gradient costs about as much as one extra forward pass. The price is memory: every $A^{(l)}$ from the forward pass must be kept until the backward pass has used it.

Checking a gradient

As in module 0, finite differences give an independent check. Perturb one parameter by $\pm h$, recompute the loss, and compare. For whole arrays of gradients, the usual summary is the relative error between the analytic gradient $g$ and the numerical one $\hat g$:

$$\frac{\lVert g - \hat g \rVert}{\lVert g \rVert + \lVert \hat g \rVert}.$$

With $h = 10^{-5}$ in double precision, a correct implementation gives around $10^{-8}$ or smaller. A value near 1 means a formula is wrong; a value like $10^{-3}$ usually means something small is, such as a missing factor.

Live demo: one pass, one matrix at a time

Forward values, then each layer’s gradient

Forward pass

Backward pass

A 2 → 3 → 1 network on the four XOR examples. Orange cells are positive, blue cells negative, stronger colour means larger size within that matrix. The solid outline marks what the current step computes; dashed outlines mark what it uses.

Try this

  1. Step through to the end once. At each backward step, find the forward matrix with the same shape as the one just computed. Every gradient has a partner.
  2. At the last step, press Apply the update and start again several times and watch the loss in the line underneath. Then step forward to $\Delta^{(2)}$: it shrinks as the predictions approach the targets.
  3. The first example is $x = (0, 0)$. Explain why it contributes nothing to $\partial \mathcal{L} / \partial W^{(1)}$, whatever its error. Which parameter of layer 1 can it still change?
  4. Press New random weights until some entry of $A^{(1)}$ is beyond ±0.9, and run to the end. Compare that entry of $\partial \mathcal{L} / \partial A^{(1)}$ with the same entry of $\Delta^{(1)}$.

Exercise

Vectorised backpropagation for any depth

The forward pass and the loss are written for you, for a network with any number of tanh layers and a linear output. Complete backward so that it returns the gradient of the loss with respect to every weight matrix and bias. The hidden tests run a finite-difference gradient check on random networks of several depths.

Check yourself

A layer maps 5 inputs to 3 outputs and the batch has 10 examples. What shape is $\partial \mathcal{L} / \partial W$, and which product gives it?

$W$ is $5 \times 3$, so its gradient is too. The layer's input $A$ is $10 \times 5$ and $\Delta$ is $10 \times 3$; the only product of the two with shape $5 \times 3$ is $A^{\top} \Delta$.

Why must the forward pass keep every layer's activations?

The backward pass needs them twice: the gradient of $W^{(l)}$ uses the layer's input $A^{(l-1)}$, and stepping down through the activation uses its slope, which for tanh is computed from $A^{(l-1)}$ itself.

Your backward passes a gradient check on a network with no hidden layer but fails with one hidden layer. Which formula do you look at?

Formula 3, the step down a layer. With no hidden layer it is never used, so formulas 1 and 2 must be right; the fault is in the product with $W^{\top}$ or the slope of the activation.

Where this leads

You can now compute the gradient of any layered network. Module 4 is about using those gradients well: momentum and Adam to reach a minimum faster, and regularisation to stop a network from simply memorising its training data. Formula 3 will be back in module 7, where multiplying by it many times in a row makes gradients vanish.

Sources: D. E. Rumelhart, G. E. Hinton and R. J. Williams, “Learning representations by back-propagating errors”, Nature 323 (1986); I. Goodfellow, Y. Bengio and A. Courville, Deep Learning, MIT Press (2016), §6.5; M. Nielsen, Neural Networks and Deep Learning, Determination Press (2015), ch. 2.