Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 4: Neural Network Foundations

Backpropagation: step by step with numbers

P4.825 min●●○ IntermediateReviewed Nov 30, 2026

Why this matters for machine learning

Backpropagation is how every neural network finds out which way to adjust each of its weights. Without it, training a network with millions of weights would be hopelessly slow.

  • Gradient descent needs the gradient of the loss for every weight; backprop computes all of them in one backward sweep. (P1.F3: Gradient descent)
  • PyTorch's loss.backward() runs exactly this algorithm on whatever computation you write. (P2.6: PyTorch tensors and autograd, coming soon)
  • Vanishing and exploding gradients, a classic problem in deep networks, come from multiplying many local gradients along the backward path. (P4.16: Vanishing and exploding gradients, coming soon)

Before this: The chain rule, Gradient descent, Loss functions (coming soon), Backpropagation: intuition (coming soon)

After this lesson you can

  • Break a model's computation into a graph of tiny steps
  • Run a forward pass and a backward pass through that graph by hand
  • Apply the local rules for add, subtract, multiply, square, ReLU, sigmoid, exp and log nodes
  • Explain why the backward pass runs in reverse order and why the forward pass must store its values
  • Use the resulting gradients to take one gradient-descent step, and average them over a batch
  • Check backprop with finite differences

A neural network makes a wrong prediction. It has millions of weights. Which way should each one move, and how sensitive is the loss to it?

You could nudge each weight a tiny bit, rerun the whole network, and see what happens to the loss. With a million weights that is a million extra forward passes, for every single training step. Backpropagation gets all of those answers in one backward pass. That pass typically costs a small multiple of one forward pass (about twice as much). That is what makes training deep networks practical.

The best way to understand it is to do it once with real numbers.

The smallest possible model

One input xx, one weight ww, one bias bb, and a target answer yy:

y^=w x+bL=(y^−y)2\hat{y} = w\,x + b \qquad\qquad L = (\hat{y} - y)^2

y^\hat{y} (“y-hat”) is the prediction and LL is the squared-error loss. We’ll use x=2x = 2, y=3y = 3, w=1.5w = 1.5 and b=−1b = -1.

The trick is to break the computation into tiny steps, one operation each, so every step is easy on its own. Each step is a node in a computation graph:

u=w⋅x    →    y^=u+b→    e=y^−y    →    L=e2\begin{gathered} u = w \cdot x \;\;\rightarrow\;\; \hat{y} = u + b \\ \rightarrow\;\; e = \hat{y} - y \;\;\rightarrow\;\; L = e^2 \end{gathered}
x (input)2w (weight)1.5u = w·x?b (bias)−1ŷ = u + b?y (target)3e = ŷ − y?L = e²?

The setup

One input x = 2 with target y = 3. The model has two parameters, w = 1.5 and b = −1. We break the computation into tiny steps, one box each. Press Next.

Change the numbers

Blue numbers are values computed going forward. Orange numbers are gradients computed going backward.

A computation graph for one neuron with squared-error loss. Step forward to compute the values (blue), then backward to compute the gradients (orange), then apply one gradient-descent update. On a phone the graph runs top to bottom.

Two passes happened. The forward pass computed the values, from inputs to loss. The backward pass computed a gradient for every node: ∂L/∂(node)\partial L/\partial(\text{node}), which means “how much does LL change if I nudge this node a tiny bit?”. Notice that the data xx and yy also received gradients. We ignore them, because we never change data. We only update the parameters ww and bb.

The local rules

Going backward, every node did the same thing: take the gradient arriving from above and multiply it by the node’s own local derivative. That’s the chain rule, applied one node at a time. A local derivative says how a node’s output changes when one of its inputs changes, ignoring the rest of the network.

nodelocal derivative(s)so the gradient…
add: s=a+cs = a + c11 for both inputsis copied unchanged to both inputs
subtract: s=a−cs = a - c+1+1 for aa, −1-1 for ccis copied, with the sign flipped for cc
multiply: u=w⋅xu = w \cdot x∂u∂w=x\dfrac{\partial u}{\partial w} = x, ∂u∂x=w\dfrac{\partial u}{\partial x} = wis multiplied by the other input (“swap”)
square: L=e2L = e^22e2eis multiplied by 2e2e
ReLU: r=max⁡(0,z)r = \max(0, z)11 if z>0z > 0, 00 if z<0z < 0 (undefined at exactly 0; PyTorch uses 0 there)passes through if z>0z > 0, is blocked (becomes 0) otherwise
sigmoid: s=σ(z)s = \sigma(z)σ(z) (1−σ(z))\sigma(z)\,(1 - \sigma(z))is multiplied by that; never more than 0.250.25
exp: r=exp⁡(z)r = \exp(z)exp⁡(z)\exp(z) (the output itself)is multiplied by the output
log: r=ln⁡zr = \ln z (for z>0z > 0)1/z1/zis multiplied by 1/z1/z

The first four rows are all the widget used. Subtract is just add with one sign flipped. The last four are activation and helper nodes you will meet in real networks (sigmoid is introduced in P1.A5; ReLU and the other activations in P4.4). Every node, however fancy, follows the same pattern: a local derivative, multiplied by the gradient arriving from above.

Why backward, and why store the forward values?

Why in reverse order? The gradient of a node is: (gradient from the nodes that use it) × (its local derivative). So a node can only finish its gradient after every node downstream of it (closer to the loss) has finished. The loss is the end of the graph and has the simplest gradient, ∂L/∂L=1\partial L/\partial L = 1. So we start there and walk back. Going forward would not work: ∂L/∂w\partial L/\partial w needs ∂L/∂u\partial L/\partial u first, which needs ∂L/∂y^\partial L/\partial \hat{y}, and so on.

Why must the forward pass store its values? Look at the local rules. Multiply needs the other input (xx or ww). Square needs ee. Sigmoid needs its output. ReLU needs to know whether zz was positive. All of these are numbers from the forward pass. So training keeps every intermediate value in memory until the backward pass has used it. This is why training needs much more memory than just running a trained model, and it is a big reason large models need big GPUs. P10.B4 counts exactly how much.

Intuition

Think of the gradient as blame: how much each value is responsible for the loss, and in which direction. The loss starts with a gradient of 1. Each node then hands a gradient back to whatever produced its inputs.

But blame is not shared out like a pie. An add node does not split the gradient between its inputs. It gives the full gradient to each of them, because nudging either input moves the sum by the same amount. A multiply node scales the gradient by the other input: if xx is large, a small change in ww has a big effect. Gradients can also be negative, so they are not “shares” that add up to the total.

The sign says which way to move. Here ∂L/∂w=−4\partial L/\partial w = -4: increasing ww would decrease the loss, so gradient descent increases ww.

Math

Chaining the local derivatives from the loss down to ww:

∂L∂w=∂L∂e⋅∂e∂y^⋅∂y^∂u⋅∂u∂w=2e⋅1⋅1⋅x=2(wx+b−y) x\begin{aligned} \frac{\partial L}{\partial w} &= \frac{\partial L}{\partial e}\cdot\frac{\partial e}{\partial \hat{y}}\cdot\frac{\partial \hat{y}}{\partial u}\cdot\frac{\partial u}{\partial w} \\ &= 2e \cdot 1 \cdot 1 \cdot x \\ &= 2(wx + b - y)\,x \end{aligned}

With our numbers: 2×(3−1−3)×2=−42 \times (3 - 1 - 3) \times 2 = -4. Similarly ∂L∂b=2(wx+b−y)=−2\dfrac{\partial L}{\partial b} = 2(wx + b - y) = -2.

Backprop computes these products from the loss downward, reusing each partial result: ∂L/∂u\partial L/\partial u is computed once and then used for both ∂L/∂w\partial L/\partial w and ∂L/∂x\partial L/\partial x. In a big network, this sharing is what makes one backward pass enough. The general version is reverse-mode automatic differentiation (P1.C10).

Code

PyTorch does all of this for you. It records the operations during the forward pass, then backward() walks the graph in reverse:

import torch

x, y = torch.tensor(2.0), torch.tensor(3.0)
w = torch.tensor(1.5, requires_grad=True)
b = torch.tensor(-1.0, requires_grad=True)

L = (w * x + b - y) ** 2   # forward pass
L.backward()               # backward pass

print(L.item(), w.grad.item(), b.grad.item())   # 1.0  -4.0  -2.0

Same numbers as the widget.

From gradients to learning

Backprop only measures. The last step in the widget is plain gradient descent from P1.F3: move each parameter against its gradient, scaled by the learning rate η=0.05\eta = 0.05:

w←1.5−0.05×(−4)=1.7b←−1−0.05×(−2)=−0.9\begin{gathered} w \leftarrow 1.5 - 0.05 \times (-4) = 1.7 \\ b \leftarrow -1 - 0.05 \times (-2) = -0.9 \end{gathered}

The new prediction is 1.7×2−0.9=2.51.7 \times 2 - 0.9 = 2.5, and the loss falls from 1 to 0.25. Press “Apply update and run another round” in the widget to keep going. Training a neural network is exactly this loop, repeated: forward, backward, update.

Try it: the whole training loop by hand

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

More than one training example

So far we had one example. Real training data has many. The loss is then the average of the per-example losses:

L=1N∑i=1NLi\mathcal{L} = \frac{1}{N}\sum_{i=1}^{N} L_i

The gradient of an average is the average of the gradients. So: run forward and backward for each example, then average the gradients before the update. (In practice a batch of BB examples is used per step, and the average is over the batch.)

Example with w=1.5w = 1.5, b=−1b = -1 and two examples, (x,y)=(2,3)(x, y) = (2, 3) and (1,0)(1, 0):

exampleeeLiL_i∂Li/∂w\partial L_i/\partial w∂Li/∂b\partial L_i/\partial b
(2,3)(2, 3)−1-111−4-4−2-2
(1,0)(1, 0)0.50.50.250.251111
average0.6250.625−1.5-1.5−0.5-0.5

With η=0.05\eta = 0.05: w←1.5−0.05(−1.5)=1.575w \leftarrow 1.5 - 0.05(-1.5) = 1.575 and b←−1−0.05(−0.5)=−0.975b \leftarrow -1 - 0.05(-0.5) = -0.975. The average loss falls from 0.6250.625 to about 0.5200.520. The two examples pulled in different directions for ww (−4-4 and +1+1). The average is a compromise.

Is my backprop correct? Gradient checking

Backprop code is easy to get subtly wrong, and wrong gradients still “run” without errors. The standard test needs no calculus. Use the idea behind the definition of the derivative: nudge a parameter up and down by a tiny ε\varepsilon and measure the slope of the loss:

∂L∂w≈L(w+ε)−L(w−ε)2ε\frac{\partial L}{\partial w} \approx \frac{L(w+\varepsilon) - L(w-\varepsilon)}{2\varepsilon}

This is gradient checking with finite differences. It is far too slow for training (one extra pair of forward passes per parameter, the very cost backprop avoids), but it is perfect for testing. If the two numbers disagree, your backprop has a bug. Run the cell below. It also does the batch average from the table above.

Try it: batch gradients and a gradient check

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

Try breaking it: change gw += 2 * e * x to gw += 2 * e (forgetting the “swap”) and watch the two lines disagree.

Go deeper Why the two-sided (central) difference, and how close is close enough?

A one-sided difference, (L(w+ε)−L(w))/ε(L(w+\varepsilon) - L(w))/\varepsilon, has an error that shrinks in proportion to ε\varepsilon. The two-sided version cancels the first error term, so its error shrinks like ε2\varepsilon^2. That makes it more accurate for the same ε\varepsilon.

But ε\varepsilon cannot be too small: the computer rounds numbers, and subtracting two nearly equal numbers loses digits. Values around 10−510^{-5} to 10−710^{-7} are common choices (with 64-bit floats). Compare the two gradients by relative difference, ∣gbackprop−gnumeric∣/max⁡(∣gbackprop∣,∣gnumeric∣)|g_{\text{backprop}} - g_{\text{numeric}}| / \max(|g_{\text{backprop}}|, |g_{\text{numeric}}|). As a rule of thumb, tiny values (say below 10−610^{-6} with 64-bit numbers) mean “agree”; a relative difference near 11 or even 0.10.1 means a bug. Check a few parameters, not all.

Gradient checking also cannot be trusted exactly at a kink such as ReLU at z=0z = 0, where the true derivative is not defined.

Go deeper What if a value is used in more than one place?

Then its gradient is the sum of the gradients from each use. Here’s a quick check: take f=x⋅xf = x \cdot x. The multiply rule says each input gets “the other input” times the incoming gradient of 1, so the two uses contribute xx and xx. Adding them gives 2x2x, which is exactly the derivative of x2x^2.

This matters in real networks, where one value often feeds many later computations (a hidden unit feeds every unit in the next layer). Forgetting to add these contributions is a classic bug when writing backprop by hand. It also explains a PyTorch habit: .grad accumulates (adds) every time you call backward(). So you must reset the gradients to zero before each training step (optimizer.zero_grad()), or old gradients pile up. P2.6 shows this in detail. You’ll handle the summing yourself when you build your own autograd engine in P4.9.

Go deeper What changes in a real network? (a preview)

Real layers work on vectors and matrices, not single numbers: h=Wx+b\mathbf{h} = \mathbf{W}\mathbf{x} + \mathbf{b}. The method is the same: forward, then backward in reverse, each node multiplying the gradient from above by its local derivative. The multiply rule’s “swap” becomes a matrix product with a transpose, and the gradient of every weight matrix has the same shape as the matrix. The bookkeeping is more complex; the idea is not. P1.C11 covers the matrix calculus and P4.10 builds a full network this way.

Check your understanding

  1. A multiply node computes u=w⋅xu = w \cdot x with w=3w = 3 and x=5x = 5. The gradient arriving from above is ∂L/∂u=2\partial L / \partial u = 2. What is ∂L/∂w\partial L / \partial w?

  2. An add node s=a+bs = a + b receives a gradient of −7-7 from above. What gradients do aa and bb get?

  3. After the backward pass, ∂L/∂w=−4\partial L/\partial w = -4. With learning rate 0.10.1, what does gradient descent do to ww?

  4. Why is backprop much faster than nudging each weight separately to see how the loss changes?

  5. A ReLU node r=max⁡(0,z)r = \max(0, z) has input z=−2z = -2. The gradient arriving from above is 55. What gradient does it pass back to zz?

Exercises

  1. In the widget, open “Change the numbers” and set w=1w = 1, b=1b = 1 (with x=2x = 2, y=3y = 3). Before stepping, predict the loss and both gradients.
    Show answerthe prediction is exactly 3, so the loss and every gradient are 0. Nothing to learn.
  2. By hand, compute ∂L/∂w\partial L/\partial w and ∂L/∂b\partial L/\partial b for x=1x = 1, y=0y = 0, w=2w = 2, b=1b = 1.
    Show answere = 3, so ∂L/∂b = 6 and ∂L/∂w = 6.
  3. In the first code cell, change the learning rate to 0.3. What happens to the loss, and why?
    Show answerthe loss goes 1, 4, 16, 64, 256: it quadruples each step. The step is so large that it overshoots the minimum by more than it started away. See the learning-rate table in P1.F3.
  4. A sigmoid node has input z=0z = 0 and receives a gradient of 33 from above. What does it pass back?
    Show answerσ(0)=0.5\sigma(0) = 0.5, so the local derivative is 0.5×0.5=0.250.5 \times 0.5 = 0.25, and the gradient is 3×0.25=0.753 \times 0.25 = 0.75.
  5. Use f=a⋅a+af = a \cdot a + a at a=3a = 3. Using the rule for values used more than once, find ∂f/∂a\partial f/\partial a.
    Show answeraa is used three times. The multiply node gives aa and aa, which is 3+3=63 + 3 = 6. The add node gives 11. They sum to 77. Check: d(a2+a)/da=2a+1=7d(a^2 + a)/da = 2a + 1 = 7.
  6. In the second code cell, change the data to a single example (2,3)(2, 3). What should the gradients be?
    Show answer−4-4 and −2-2, as in the widget, and finite differences should match.

Next: in P4.9 you’ll turn these rules into a tiny automatic-differentiation engine, about 100 lines of Python, that can run backprop on any expression.

Key takeaways

  • Backprop computes how much the loss changes when each value is nudged: one gradient per value, in a single backward sweep.
  • Each node only needs its local derivative. Its gradient = gradient arriving from above × local derivative. That's the chain rule.
  • Add nodes copy the gradient to every input. Multiply nodes swap: each input gets the gradient times the other input.
  • When a value is used in several places, the gradients from each use add up.
  • The backward pass runs in reverse because a node needs the gradient from everything downstream of it first. It also needs the values stored during the forward pass.
  • With many examples the loss is an average, so the gradient is the average of the per-example gradients.
  • Check any backprop code against finite differences: nudge a weight both ways and compare the slope with the gradient.
  • Backprop finds the gradients; gradient descent uses them to update the weights. They are two separate steps.
Found a mistake? Tell us