AI from scratch · Chapter 4

Backprop you can watch

Chapter 3 ended with a hidden layer that learned XOR, and a question: how does a neuron deep inside a network know which way to change, when it only affects the answer through other neurons? The answer is to pass blame backwards, one step at a time. It's called backpropagation, and it's just the chain rule from calculus, done in the right order.

1. A relay of nudges

Three machines in a row: the first triples its input, the second adds 2, the third squares. Nudge x a little and watch the nudge travel.

Each machine stretches the nudge by its own slope: ×3, then ×1, then ×2·(its input). The final nudge is the product of all three, so the derivative of the whole chain is the product of the local slopes. That's the chain rule. Notice we can compute it either way: start at x and multiply forward, or start at the end and multiply backward. Backward turns out to be the magic trick.

The pictureEach machine stretches a small nudge by its own slope. Stretches multiply.
The mathThe chain rule: for \(c(b(a(x)))\), \(\dfrac{dc}{dx} = \dfrac{dc}{db} \cdot \dfrac{db}{da} \cdot \dfrac{da}{dx}\).

A small nudge travels down a chain, stretched by each link's slope along the way; the stretches multiply.

Set \(x = 0.5\). Then \(a = 3x = 1.5\), \(b = a + 2 = 3.5\), \(c = b^2\). What is \(dc/dx\)? (Multiply the three local slopes.)

\(3 \times 1 \times 2b = 3 \times 1 \times 7 = 21\). A nudge of 0.01 in \(x\) moves \(c\) by about 0.21. Check it with the sliders.

2. A tiny network, forward and backward

Here's one neuron feeding another, computing a prediction ŷ for an input x = 1.5, and the loss: how far ŷ is from the target y = 0.8, squared. Dashed boxes are the weights we can change. Press Forward to compute values left to right, then Backward to pass blame right to left.

Read the red numbers right to left. The loss starts with blame 1 (it's what we measure). Each node hands blame to the nodes it came from, multiplied by the local slope on the arrow between them: how much it moves when that input moves. A node used twice would add up the blame from both uses. When the pass reaches a weight, its red number is exactly ∂loss/∂weight: chapter 2's gradient. "Step downhill" moves every weight against its gradient, and the next forward pass has a smaller loss.

The math, every number

Forward, with \(w_1 = 0.6,\ b_1 = -0.2,\ w_2 = -0.9,\ b_2 = 0.3,\ x = 1.5,\ y = 0.8\):

\[ z = 0.6 \cdot 1.5 - 0.2 = 0.7,\quad h = \tanh 0.7 = 0.604,\quad \hat y = -0.9 \cdot 0.604 + 0.3 = -0.244,\quad L = (-0.244 - 0.8)^2 = 1.090 \]

Backward. Start with \(\partial L / \partial L = 1\) and multiply by each local slope as you go left:

\[ \frac{\partial L}{\partial \hat y} = 2(\hat y - y) = -2.088 \]

\[ \frac{\partial L}{\partial w_2} = -2.088 \cdot h = -1.262, \qquad \frac{\partial L}{\partial b_2} = -2.088 \cdot 1, \qquad \frac{\partial L}{\partial h} = -2.088 \cdot w_2 = 1.879 \]

\[ \frac{\partial L}{\partial z} = 1.879 \cdot (1 - h^2) = 1.879 \cdot 0.635 = 1.193 \qquad (\tanh' z = 1 - \tanh^2 z) \]

\[ \frac{\partial L}{\partial w_1} = 1.193 \cdot x = 1.789, \qquad \frac{\partial L}{\partial b_1} = 1.193 \]

Notice the bookkeeping: each node needs only the blame arriving from its right and its own local slope, which uses values saved from the forward pass. No node needs to know anything about the rest of the graph. That locality is why backprop can be written once, as a library, and work for any network.

Two rules cover every graph. Along a path, slopes multiply. Where a value feeds into several places, the blames coming back from each place add up (because a nudge to it moves all of them at once).

Press Forward, Backward, then "Step downhill" with a learning rate of 0.1. Which way does \(w_1\) move, and roughly by how much?

\(w_1 \leftarrow 0.6 - 0.1 \cdot 1.789 \approx 0.42\). Smaller \(w_1\) means smaller \(h\), and since \(w_2\) is negative, a larger \(\hat y\): closer to the target 0.8.

A value \(u\) feeds two later nodes. Backward brings blame 0.5 from one and −2 from the other. What is \(\partial L/\partial u\)?

Nudge \(u\) by \(\varepsilon\): the first use changes the loss by \(0.5\varepsilon\), the second by \(-2\varepsilon\), together \(-1.5\varepsilon\).

Backprop passes blame from right to left: each node multiplies the blame it receives by its own local slope and hands it on, and blame arriving from several uses adds up.

Why does training need so much more memory than running a model?
  1. Every local slope depends on values from the forward pass: \(\tanh\)'s slope needs \(h\), a weight's blame needs its input \(x\).
  2. The backward pass runs after the whole forward pass, so every one of those values must be kept until it's used: one saved number per neuron, per layer, per example in the batch.
  3. Running a trained model (inference) needs no backward pass, so each layer's values can be thrown away as soon as the next layer has them.
  4. For big models the saved values (the activations) take more memory than the weights. Libraries trade time for memory by saving only some layers and recomputing the rest during the backward pass (gradient checkpointing).
Where it breaks: long chains, hard decisions, small numbers

3. Did backprop get it right? Nudge and see

The slow, obvious way to get a gradient: nudge one weight by a tiny ε, rerun the forward pass, and see how much the loss changed. Real libraries use this as a test.

The math: how exact is "nudge and see"?

The one-sided nudge \(\frac{L(w + \varepsilon) - L(w)}{\varepsilon}\) is off by an amount proportional to \(\varepsilon\). The centered one, \(\frac{L(w + \varepsilon) - L(w - \varepsilon)}{2\varepsilon}\), is off by an amount proportional to \(\varepsilon^2\): with \(\varepsilon = 10^{-4}\), about \(10^{-8}\). Libraries compare it with backprop using a relative error, \(\frac{|g_{\text{backprop}} - g_{\text{nudge}}|}{|g_{\text{backprop}}| + |g_{\text{nudge}}|}\); below about \(10^{-7}\) means the backward code is right. Bigger means a bug, usually a forgotten += or a wrong local slope.

4. Why this is the trick that made deep learning

Nudging works, but it needs one extra forward pass per weight. Backprop gets every gradient from one forward and one backward pass, about the cost of three forward passes, however many weights there are.

That gap is why networks with billions of weights can be trained at all. Everything since, convolutions for images and attention for language, is new shapes of graphs with the same forward and backward passes running through them. Coming up on the path: what the loss should actually be when a network has to choose between answers, probability and loss.

A network has a million weights. How many forward passes does the "nudge each weight" method need for one full gradient (one for the starting loss, plus one per nudged weight)?

\(1 + 10^6\). Backprop gets the same million numbers for about the cost of 3 forward passes: a forward, and a backward that does roughly twice a forward's arithmetic. For GPT-sized models (\(10^{11}\) weights) that's the difference between possible and not.

All chapters: AI from scratch. Inspired by 3Blue1Brown's Backpropagation calculus and Andrej Karpathy's micrograd.

5. Backprop as matrix products

Calculus 2 introduced the Jacobian, the matrix of every output's slope with respect to every input. In that language the whole backward pass is one line. A network is a chain: \(x \to h_1 \to h_2 \to \dots \to L\). The multivariable chain rule says the Jacobian of a chain is the product of the Jacobians of its links:

\[ \frac{\partial L}{\partial x} = \underbrace{\frac{\partial L}{\partial h_k}}_{1 \times m} \; \underbrace{\frac{\partial h_k}{\partial h_{k-1}}}_{m \times m} \cdots \underbrace{\frac{\partial h_1}{\partial x}}_{m \times n} \]

Matrix products are associative, so you can multiply in either order and get the same answer, but not for the same price. The loss is one number, so the leftmost factor is a single row. Multiply left to right and every step is a row times a matrix: a vector-Jacobian product, about \(m^2\) work, and the result is still one row. That is reverse mode, and it's exactly what backprop does in chapter 4. Multiply right to left (forward mode) and you carry whole matrices along, which only pays off when there are few inputs and many outputs.

Better still, nobody ever builds those \(m \times m\) matrices. The Jacobian of an elementwise \(\tanh\) is diagonal, so its vector-Jacobian product is just "multiply each entry by \(1 - h^2\)"; for \(h = Wx\) it's "row times \(W\)". Every layer in a framework ships one small function: given the blame on my output, return the blame on my input.

A model has a billion parameters and one loss. How many backward passes does reverse mode need to get the derivative for every parameter?

One. A backward pass carries one row (the loss's gradient) through the chain and hands back all billion partials at once, for about the cost of a couple of forward passes. Forward mode would need a pass per parameter: a billion of them. That gap is why deep learning runs on reverse mode.

Last updated