---
title: Backpropagation
heading: The chain rule organized for networks, errors sent backward from the output, gradients for every weight in one backward pass, checking them with finite differences, the cost compared with numerical gradients, and why gradients vanish through many saturating layers
eyebrow: S14 · Lesson 25 · Backpropagation
xp: 50
---

::: hook
Training a network needs the gradient of the error with respect to every weight, and a large network has billions. Computing each derivative separately by nudging a weight would take two forward passes per weight. Backpropagation gets all of them for roughly the cost of two or three forward passes, by running the chain rule backward through the network and reusing every intermediate result. It's the same reverse-mode differentiation that circuit simulators use for sensitivity analysis, and every deep-learning framework is built around it.
:::

::: play
- A tiny network, $y = w_2\tanh(w_1x)$, with input x = 1, target t and squared error $E = (y - t)^2/2$. The error as a function of $w_1$, and the tangent line whose slope backpropagation computes.
- Move $w_1$ and watch the slope change. Where the tanh saturates (large $|w_1|$), the error curve flattens and the gradient fades.
- The readout is the backpropagated derivative; the tangent should touch the curve exactly.
:::

```sim plot
view: graph
x: u = -4..4
y: E = 0..3
slider: w = -3..3 step 0.05 = 0.5
slider: v = -3..3 step 0.1 = 2
slider: t = -1..1 step 0.1 = 0.5
plot: (v*tanh(u) - t)^2/2 | samples: 400 | label: error E(w₁)
plot: (v*tanh(w) - t)^2/2 + (v*tanh(w) - t)*v*(1 - tanh(w)^2)*(u - w) | samples: 100 | dashed | color: ch3 | label: tangent from backprop
point: w, (v*tanh(w) - t)^2/2 | label: w₁
readout: dE/dw₁ = (v*tanh(w) - t)*v*(1 - tanh(w)^2) | digits: 4
```

::: predict
## A network has 10 sigmoid layers in a chain, each with weight 1. By at most what factor does the gradient shrink from the output back to the first layer?

- [ ] 0.25
- [ ] 0.1
- [x] About $10^{-6}$
- [ ] It doesn't shrink

::: reveal
Each layer multiplies the backward signal by its weight times the sigmoid's derivative, which is at most 0.25. Ten layers give at most $0.25^{10} = 9.5 \times 10^{-7}$. That's the **vanishing gradient** problem, and it's why deep networks use ReLU units (derivative 1 where active), careful initialization and residual connections.
:::
:::

::: nameit
## Forward, then backward

A forward pass computes each unit's activation $a_j = \sum_iw_{ji}z_i$ and output $z_j = h(a_j)$. Define each unit's error signal $\delta_j = \partial E/\partial a_j$. Then every weight's gradient is local:

$$\frac{\partial E}{\partial w_{ji}} = \delta_jz_i$$

## The backward recursion

At an output unit with its matching loss (linear with squared error, sigmoid or softmax with cross-entropy), $\delta_k = y_k - t_k$. Hidden units collect the errors of the units they feed:

$$\delta_j = h'(a_j)\sum_kw_{kj}\delta_k$$

For tanh, $h' = 1 - z^2$; for ReLU, h′ is 1 where a > 0 and 0 otherwise.

## Cost

One backward pass costs about as much as a forward pass (each weight is used once more for δ and once for its gradient), so the full gradient costs a small multiple of a forward pass. Finite differences need two forward passes per weight: $2W$ for W weights.

## Gradient checking

Compare backpropagation against the central difference $[E(w + \epsilon) - E(w - \epsilon)]/2\epsilon$, whose error falls as $\epsilon^2$ (the one-sided difference's falls only as ε). Agreement to about $10^{-6}$ relative is the standard test that a backward pass is right.

## Vanishing and exploding gradients

Through L layers, δ is multiplied by $w\,h'$ at every step. Products below 1 vanish exponentially and above 1 explode, which is why initialization keeps $w\,h'$ near 1.
:::

::: example
## For $y = w_2\tanh(w_1x)$ with x = 1, $w_1$ = 0.5, $w_2$ = 2 and t = 0.5, backpropagate the squared error.

::: solution
1. **Forward pass.**
   $$\begin{aligned} z &= \tanh(0.5) \\ &= 0.4621 \\ y &= 0.9242 \\ E &= 0.4242^2/2 \\ &= 0.0900 \end{aligned}$$
2. **Output delta.**
   $$\begin{aligned} \delta_\text{out} &= y - t \\ &= 0.4242 \\ \frac{\partial E}{\partial w_2} &= 0.4242 \times 0.4621 \\ &= 0.1960 \end{aligned}$$
3. **Hidden delta.** Here $1 - z^2$ = 0.7864, and
   $$\begin{aligned} \delta_\text{hidden} &= (1 - z^2)\,w_2\,\delta_\text{out} \\ &= 0.6673 \end{aligned}$$
4. **First-layer gradient.**
   $$\begin{aligned} \frac{\partial E}{\partial w_1} &= 0.6673 \times x \\ &= 0.6673 \end{aligned}$$

**Answer:** E = 0.0900, $\partial E/\partial w_2$ = 0.1960 and $\partial E/\partial w_1$ = 0.6673.
:::
:::

::: example
## Check that gradient with ε = 0.001.

::: solution
1. **Central difference.**
   $$\frac{E(w + \epsilon) - E(w - \epsilon)}{2\epsilon} = 0.667275$$
   off by $1.2 \times 10^{-6}$.
2. **One-sided difference.**
   $$\frac{E(w + \epsilon) - E(w)}{\epsilon} = 0.66820$$
   off by $9.3 \times 10^{-4}$.
3. **Halving ε.** It would cut the first error by 4 and the second by 2.

**Answer:** the central difference gives 0.667275, within $1.2 \times 10^{-6}$ of the backpropagated gradient, and the one-sided difference 0.66820, off by $9.3 \times 10^{-4}$.
:::
:::

::: example
## A linear layer computes $\mathbf y = W\mathbf x$ with $W = \begin{bmatrix}1 & 2 \\ 0 & -1\end{bmatrix}$ and x = (1, 3). The loss's gradient with respect to y is g = (0.5, −1). Find the gradients with respect to W and x.

::: solution
1. **Gradient with respect to W.** Each weight $W_{ij}$ multiplies $x_j$ into $y_i$, so $\partial L/\partial W_{ij} = g_ix_j$, the outer product:
   $$\mathbf g\mathbf x^T = \begin{bmatrix}0.5 & 1.5 \\ -1 & -3\end{bmatrix}$$
2. **Gradient with respect to x.** It sums over the outputs each input feeds:
   $$\begin{aligned} W^T\mathbf g &= \begin{bmatrix}1 \times 0.5 + 0 \times (-1) \\ 2 \times 0.5 + (-1)(-1)\end{bmatrix} \\ &= (0.5, 2) \end{aligned}$$
3. **Cost.** Every layer's backward pass is these two products, which is why it costs about twice the forward pass.

**Answer:** the gradient with respect to W is $\begin{bmatrix}0.5 & 1.5 \\ -1 & -3\end{bmatrix}$, and with respect to x it's (0.5, 2).
:::
:::

::: check
given: u = 0.3 | 1.2 | -0.6; v = 1.5 | -2; t = 0 | 1; x = 1 | 2
answer: (v*tanh(u*x) - t)*tanh(u*x)
tolerance: 0.5%

## For $y = w_2\tanh(w_1x)$ with $w_1$ = {u}, $w_2$ = {v}, input {x}, target {t} and squared error, what's $\partial E/\partial w_2$?

::: right
Right. $(y - t)z$ = {answer}.
:::

::: misses
- [(v*tanh(u*x) - t)] That's δ at the output; multiply by the input to the weight, z.
- [any] Not yet. Output error times the hidden unit's output.
:::
:::

::: check
given: u = 0.3 | 1.2 | -0.6; v = 1.5 | -2; t = 0 | 1; x = 1 | 2
answer: (v*tanh(u*x) - t)*v*(1 - tanh(u*x)^2)*x
tolerance: 0.5%

## For the same network ($w_1$ = {u}, $w_2$ = {v}, x = {x}, t = {t}), what's $\partial E/\partial w_1$?

::: right
Right. $(y - t)w_2(1 - z^2)x$ = {answer}.
:::

::: misses
- [(v*tanh(u*x) - t)*v*x] Include the tanh's derivative, $1 - z^2$.
- [any] Not yet. Send the error back through $w_2$ and the tanh.
:::
:::

::: check
given: w = 0.5 | 2 | 1.5; b = -0.25 | 0.5; v = 2 | -1; t = 0 | 1; x = 1 | 2
answer: (v*(w*x + b + abs(w*x + b))/2 - t)*v*step(w*x + b)*x
tolerance: 0.5%

## A network computes $y = v\,\text{ReLU}(wx + b)$ with w = {w}, b = {b}, v = {v}. For input {x}, target {t} and squared error, what's $\partial E/\partial w$?

::: right
Right. $(y - t)\,v\,\text{step}(wx + b)\,x$ = {answer}. Here the unit is on; a ReLU that's off would pass no gradient at all.
:::

::: misses
- [any] Not yet. Output error, back through v, through the ReLU's 0-or-1 slope, times x.
:::
:::

::: check
given: d = 0.1 | 0.25; w = 1 | 2 | 3; L = 5 | 10 | 20
answer: (d*w)^L
tolerance: 0.5%

## Through each of {L} layers, the backward signal is multiplied by a weight {w} and an activation slope {d}. By what overall factor is it scaled?

::: right
Right. $(wh')^L$ = {answer}.
:::

::: misses
- [d*w*L] The factors multiply.
- [any] Not yet. A product of L equal factors.
:::
:::

::: check
given: e = 1e-6 | 4e-5; a = 1e-3 | 1e-2; r = 2 | 10
answer: e/r^2
tolerance: 0.5%

## A central-difference gradient check with step {a} is off by {e}. What error do you expect with a step {r} times smaller (rounding aside)?

::: right
Right. The error falls as ε², to {answer}.
:::

::: misses
- [e/r] That's the one-sided difference's rate.
- [any] Not yet. Central differences are second-order.
:::
:::

::: check
given: W = 1000 | 1e6 | 1e9; c = 2 | 3
answer: 2*W/c
tolerance: 0.5%

## A network has {W} weights. Backpropagation computes the gradient for about {c} forward passes' cost. How many times more work does a central-difference gradient take?

::: right
Right. $2W/c$ = {answer}.
:::

::: misses
- [W/c] Central differences need two passes per weight.
- [any] Not yet. Compare 2W passes with c.
:::
:::

::: check
kind: parts
given: a = 1 | -2; b = 0.5 | 3; c = -1 | 2; d = 1 | 4; p = 1 | 2; q = -1 | 3; u = 0.5 | -1; v = 2 | -0.5

## A linear layer $\mathbf y = W\mathbf x$ has $W = \begin{bmatrix}a & b \\ c & d\end{bmatrix}$ with a = {a}, b = {b}, c = {c}, d = {d}. The input is x = ({p}, {q}) and the upstream gradient $\partial L/\partial\mathbf y$ = ({u}, {v}).

::: part
answer: a*p + b*q
tolerance: 0.5%

### What is $y_1$?

::: misses
- [a*p + c*q] Row 1 of W multiplies x: $W_{11}x_1 + W_{12}x_2$.
- [any] $ax_1 + bx_2$.
:::
:::

::: part
answer: u*q
tolerance: 0.5%

### What is $\partial L/\partial b$ (the weight from $x_2$ to $y_1$)?

::: misses
- [u*p] b multiplies $x_2$, not $x_1$.
- [any] $g_1x_2$.
:::
:::

::: part
answer: b*u + d*v
tolerance: 0.5%

### What is $\partial L/\partial x_2$?

::: misses
- [c*u + d*v] That's the second row; use the second column ($W^T\mathbf g$).
- [any] Sum over the outputs $x_2$ feeds: $W_{12}g_1 + W_{22}g_2$.
:::
:::

::: part
answer: a*u + c*v
tolerance: 0.5%

### What is $\partial L/\partial x_1$?

::: misses
- [a*u + b*v] Use the first column of W.
- [any] $W_{11}g_1 + W_{21}g_2$.
:::
:::
:::

::: check
kind: derivation
vars: w = -3..3, x = -3..3, t = 0..1

## A single logistic unit $y = \sigma(wx)$ is trained with cross-entropy against target t.

::: step
answer: 1/(1 + exp(-w*x))

### What is its output?
:::

::: step
answer: (1/(1 + exp(-w*x)) - t)*x

### What is the loss's gradient with respect to w?
:::

::: right
Right. The sigmoid's slope cancels against the cross-entropy's, leaving the error times the input.
:::
:::

::: explain
## Why does backpropagation compute all the gradients for the price of a few forward passes?

::: model
Every weight's gradient is the product of the error signal δ at the unit it feeds and the activation coming into it. The δ's for a whole layer can be computed from the δ's of the layer above in one sweep, because each unit's error is just its activation slope times the weighted sum of the errors it caused downstream. So one backward pass through the network, using the activations saved from the forward pass, produces every δ, and every gradient follows by one multiplication. Finite differences instead treat the network as a black box, rerunning it for each weight, so they cost two forward passes per weight; backpropagation shares the work across all weights.
:::
:::

::: practice

::: check
given: u = -1.5 | 1.5; v = -3 | 3; t = -1 | 1; x = 0.5 | 2
answer: (v*tanh(u*x) - t)*v*(1 - tanh(u*x)^2)*x
tolerance: 0.5%

## $\partial E/\partial w_1$: $w_1$ = {u}, $w_2$ = {v}, x = {x}, t = {t}?

::: misses
- [any] $(y - t)w_2(1 - z^2)x$.
:::
:::

::: check
given: d = 0.05 | 0.5; w = 0.5 | 4; L = 2 | 30
answer: (d*w)^L
tolerance: 0.5%

## Gradient scale through {L} layers, slope {d}, weight {w}?

::: misses
- [any] $(wh')^L$.
:::
:::

::: check
given: e = 1e-8 | 1e-3; r = 1.5 | 20
answer: e/r^2
tolerance: 0.5%

## Central-difference error {e}, step divided by {r}?

::: misses
- [any] $e/r^2$.
:::
:::
:::
