Simple Algorithm
Deep Learning · Activation · 17 min

Backpropagation & Gradient Flow

How the error signal travels backward through depth, and how to keep it alive.

To train a network you need one number for every weight: how the loss would change if you nudged that weight. Modern networks have billions of weights. Backpropagation computes every one of those numbers for the price of about three forward passes, and that single fact makes deep learning possible. It also exposes the catch: the signal that reaches the early layers is a product of many factors, and long products tend to vanish or explode.

What you’ll learn

  • Explain why training needs the gradient of the loss with respect to every weight, and why nudging the weights one at a time is hopeless at scale.
  • Run the forward and backward pass on a small computational graph, multiplying each local derivative by the gradient arriving from above.
  • Explain why gradients vanish or explode in deep networks, and compute how fast for a chain of sigmoid layers.
  • Describe the four standard remedies (careful initialization, normalization layers, residual connections and gradient clipping) and what each does to the flow of gradients.

A billion knobs, one number

Training adjusts a network's weights to lower a loss LL, a single number that measures how wrong its predictions are on the training data. To know which way to turn each knob, you need, for every weight ww, the partial derivative ∂L/∂w\partial L/\partial w: how fast the loss changes when that weight alone moves. Together these form the gradient ∇L\nabla L, and gradient descent moves every weight a small step against it, w←w−η ∂L/∂ww \leftarrow w - \eta\,\partial L/\partial w, where η\eta is the learning rate.

The obvious way to measure a derivative is to nudge: change ww by a tiny amount hh, run the network again and see how much the loss moved.

∂L∂w≈L(w+h)−L(w)h\frac{\partial L}{\partial w} \approx \frac{L(w + h) - L(w)}{h}
A finite difference. It costs one extra forward pass per weight, and it is only approximate: a large hh measures the slope of a chord rather than the tangent, and a tiny hh drowns the difference in rounding error.
Predict before you look

A network has 10 million weights, and one forward pass over a batch of training data takes 0.1 seconds. Estimating one full gradient by nudging each weight in turn takes about how many days?

Show the answer

11.6 days

10710^7 passes × 0.1\times\,0.1 s =106= 10^6 s, about 11.611.6 days, for one gradient. Training takes many thousands of gradient steps. Backpropagation gets the exact gradient of the same network in roughly 0.30.3 seconds.

Backpropagation computes the exact derivative for every weight at once. For typical networks the backward pass costs about twice the forward pass, so the whole gradient costs about three forward passes, whether the network has a thousand weights or a billion. The next screen shows how; the rest of the lesson shows why the answer can still be useless in a very deep network, and what to do about it.

Think first If backpropagation is so much cheaper, why does anyone still compute finite differences?

As a test. Comparing a handful of backprop derivatives with finite differences, a gradient check, catches bugs in a hand-written backward pass: if the two disagree beyond rounding error, the code is wrong. You will write one in the Representation lesson Backpropagation & Automatic Differentiation.

The chain rule on a graph

Every network, however large, is built from simple operations: multiply, add, apply an activation. Draw each operation as a node and each intermediate value as an arrow, and you have a computational graph. Take the smallest useful one: a model with one weight predicts y^=wx\hat y = wx and is scored by the squared error L=(y^−y)2L = (\hat y - y)^2.

Forward pass (left to right), with input x=2x = 2, target y=3y = 3 and weight w=0.5w = 0.5: the product u=wx=1u = wx = 1, the residual r=u−y=−2r = u - y = -2, the loss L=r2=4L = r^2 = 4. Keep these values; the backward pass needs them.

Backward pass (right to left): start from ∂L/∂L=1\partial L/\partial L = 1 and, at each node, multiply the gradient arriving from above by that node's local derivative. This is the chain rule:

∂L∂w=∂L∂r⏟2r = −4⋅∂r∂u⏟1⋅∂u∂w⏟x = 2=−8\frac{\partial L}{\partial w} = \underbrace{\frac{\partial L}{\partial r}}_{2r\,=\,-4}\cdot\underbrace{\frac{\partial r}{\partial u}}_{1}\cdot\underbrace{\frac{\partial u}{\partial w}}_{x\,=\,2} = -8
Read it right to left as the gradient travels: −4-4 arrives at rr, passes unchanged through the subtraction, and is multiplied by x=2x = 2 at the product. Each node only needs its own local derivative and the values it saw on the way forward.
Check your understanding

With ∂L/∂w=−8\partial L/\partial w = -8 and learning rate η=0.1\eta = 0.1, one gradient-descent step moves w=0.5w = 0.5 to what?

  1. w=−0.3w = -0.3
  2. w=0.9w = 0.9
  3. w=1.3w = 1.3
  4. w=8.5w = 8.5
Show the answer

C. w=1.3w = 1.3

w←0.5−0.1×(−8)=1.3w \leftarrow 0.5 - 0.1\times(-8) = 1.3. The prediction becomes 2.62.6 and the loss (2.6−3)2=0.16(2.6 - 3)^2 = 0.16, down from 44. A negative derivative means the loss falls as ww grows, so the step increases ww.

Two rules handle every graph:

  • Multiply along a path. A node receives a gradient from above, multiplies it by its local derivative and sends it on. Nothing else about the rest of the graph matters to that node.
  • Add where paths meet. If a value feeds several later nodes, its gradient is the sum of the gradients coming back along each path.

The backward pass visits each node once, in reverse order, which is why it costs about as much as the forward pass instead of once per weight.

Gradients are products

Now stack many layers. The gradient that reaches the first layer has passed back through every layer above it, picking up one factor per layer: that layer's weight times the slope of its activation function. For a chain with one neuron per layer, hℓ=ϕ(zℓ)h_\ell = \phi(z_\ell) with zℓ=wℓhℓ−1z_\ell = w_\ell h_{\ell-1}:

∂hL∂h0=∏ℓ=1Lwℓ ϕ′(zℓ)=wLϕ′(zL)⋅wL−1ϕ′(zL−1)⋯w1ϕ′(z1)\frac{\partial h_L}{\partial h_0} = \prod_{\ell=1}^{L} w_\ell\,\phi'(z_\ell) = w_L\phi'(z_L)\cdot w_{L-1}\phi'(z_{L-1})\cdots w_1\phi'(z_1)
In a real network each factor is a matrix (the layer's Jacobian), but the moral is the same: the gradient at the bottom is a product of LL factors.

Long products are fragile. If the typical factor is 0.50.5, twenty layers shrink the gradient by 0.520≈10−60.5^{20} \approx 10^{-6}: the vanishing gradient, where the first layers barely learn. If it is 1.51.5, twenty layers amplify it by 1.520≈3,3001.5^{20} \approx 3{,}300: the exploding gradient, where one step can throw the weights far away. Only factors close to 11 survive depth.

The classic sigmoid σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}) makes vanishing almost certain. Its slope σ′(z)=σ(z)(1−σ(z))\sigma'(z) = \sigma(z)(1 - \sigma(z)) is at most 14\tfrac14, at z=0z = 0, and nearly zero in its flat tails, where the unit is saturated.

Predict before you look

A chain of 10 sigmoid layers has weights of size 1 and every unit sits at z=0z = 0, where the slope is largest. The gradient reaching the bottom is multiplied by 0.25100.25^{10}. Write that factor as 10−k10^{-k}: what is kk?

Show the answer

6

0.2510=2−20≈9.5×10−70.25^{10} = 2^{-20} \approx 9.5\times10^{-7}, so k=10log⁡104≈6.0k = 10\log_{10}4 \approx 6.0: a millionfold loss of signal in the best case. Saturated units, with slopes near zero, make it far worse.

Four ways to keep the gradient alive

For two decades, the vanishing gradient was a major reason why networks with more than a few layers were so hard to train. Four remedies, now standard, keep the per-layer factors near one or route around them:

RemedyWhat it doesWhere you study it
InitializationScales the random starting weights so each layer's factor starts near 11: Xavier for tanh, He for ReLU, which must make up for zeroing half its inputs.Initialization & Vanishing Gradients
Normalization layersRescale the activations inside the network to a fixed size at every layer, so the forward signal cannot shrink or blow up (BatchNorm, LayerNorm, RMSNorm). In deep networks they work best combined with residual connections.BatchNorm, LayerNorm & RMSNorm
Residual connectionsCompute h+F(h)\mathbf h + F(\mathbf h) instead of F(h)F(\mathbf h). The identity part has derivative exactly 11, so the gradient has a direct path back through every block: a gradient highway.Residual Connections
Gradient clippingIf the gradient's length exceeds a threshold, shrink it to that length before the step. It does not prevent explosions, but it stops one from wrecking the weights.Exploding Gradients & Clipping (Emergence)
A fifth, quieter fix is the activation itself: ReLU's slope is exactly 11 wherever it is active, so it does not shrink the gradients it passes, unlike the sigmoid's 14\tfrac14.
Check your understanding

A residual block computes y=x+F(x)\mathbf y = \mathbf x + F(\mathbf x). Why does a useful gradient reach x\mathbf x even when FF's own derivative is tiny?

  1. Because ∂y/∂x=I+∂F/∂x\partial\mathbf y/\partial\mathbf x = I + \partial F/\partial\mathbf x: the identity term passes the gradient through unchanged
  2. Because the residual block has fewer weights, so each one gets a larger share of the gradient
  3. Because FF is always initialized to the identity
  4. Because the gradient skips the block entirely and FF is never trained
Show the answer

A. Because ∂y/∂x=I+∂F/∂x\partial\mathbf y/\partial\mathbf x = I + \partial F/\partial\mathbf x: the identity term passes the gradient through unchanged

The chain rule through y=x+F(x)\mathbf y = \mathbf x + F(\mathbf x) gives ∂L/∂x=∂L/∂y (I+∂F/∂x)\partial L/\partial\mathbf x = \partial L/\partial\mathbf y\,(I + \partial F/\partial\mathbf x). Even if ∂F/∂x\partial F/\partial\mathbf x is near zero, the II carries the gradient down intact. Through many blocks the gradient becomes a sum over paths, including the all-identity path, instead of a product of small factors.

Where it came from, and where it goes

In the Representation lessons you will derive and build each piece:

  • Backpropagation & Automatic Differentiation: backprop for a whole layer in matrix form, what it costs in time and memory, forward versus reverse mode, and PyTorch's autograd.
  • Initialization & Vanishing Gradients: the variance calculation behind the Xavier and He scales, and why all-zero weights fail.
  • BatchNorm, LayerNorm & RMSNorm: what each normalizes, over which axes, and why training gets easier.
  • Residual Connections: the degradation problem, the identity shortcut and how skip connections made networks hundreds of layers deep trainable.

The Emergence lessons then reach the research frontier: differentiating through fixed points and optimization problems, tracing predictions back to training examples, the exact learning dynamics of deep linear networks, criticality and the finite-width effects that make the depth-to-width ratio matter, training without normalization layers, and the stability problems of normalization and residual streams in large transformers.

Think first Backpropagation needs every intermediate value from the forward pass. What does that imply for training a very deep network on long inputs?

Memory grows with depth times batch size times input length, because every layer's activations must be stored until the backward pass reaches it. Training therefore needs far more memory than running the trained model. Tricks such as gradient checkpointing, which stores only some activations and recomputes the rest during the backward pass, trade extra compute for memory.

Key takeaways

  • Training needs ∂L/∂w\partial L/\partial w for every weight. Finite differences cost one forward pass per weight; backpropagation gets all of them for about three forward passes.
  • Backpropagation is the chain rule on a computational graph: the forward pass stores intermediate values, and the backward pass multiplies each local derivative by the gradient from above, adding where paths meet.
  • The gradient reaching early layers is a product of one factor per layer, so it vanishes when the factors are below one and explodes when they are above; the sigmoid's slope is at most 14\tfrac14.
  • Careful initialization, normalization layers, residual connections and gradient clipping keep the signal alive; modern networks use all four.
  • Reverse-mode differentiation dates to 1970, its use in neural networks to Werbos and to Rumelhart, Hinton and Williams (1986); the vanishing gradient was identified by Hochreiter (1991) and Bengio, Simard and Frasconi (1994).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A network has NN weights. Roughly how many forward passes' worth of computation does one full gradient cost by finite differences, and by backpropagation?

  1. About 33 either way
  2. About NN by finite differences; about 33 by backpropagation
  3. About NN either way, since every weight needs its own derivative
  4. About 33 by finite differences; about NN by backpropagation
Show the answer

B. About NN by finite differences; about 33 by backpropagation

Nudging needs one extra forward pass per weight. Backpropagation runs one forward pass and one backward pass, which costs about twice the forward pass, so about three in total regardless of NN.

Question 2

For L=(wx−y)2L = (wx - y)^2 with w=1w = 1, x=3x = 3 and y=1y = 1, what is ∂L/∂w\partial L/\partial w?

  1. 44
  2. 66
  3. 22
  4. 1212
Show the answer

D. 1212

Forward: wx=3wx = 3, residual r=2r = 2, L=4L = 4. Backward: ∂L/∂r=2r=4\partial L/\partial r = 2r = 4, passed through the subtraction unchanged, then multiplied by ∂(wx)/∂w=x=3\partial(wx)/\partial w = x = 3: 1212.

Question 3

In a 30-layer network the backward signal is multiplied by about 0.80.8 at each layer. Compared with the last layer, how large is the gradient at the first?

  1. About a thousandth as large
  2. About 0.80.8 times as large
  3. About 2424 times as large
  4. Exactly zero
Show the answer

A. About a thousandth as large

0.830≈1.2×10−30.8^{30} \approx 1.2\times10^{-3}. Factors compound multiplicatively: a modest per-layer shrinkage becomes a thousandfold loss over thirty layers.

Question 4

Why does He initialization for ReLU networks use weight variance 2/n2/n where LeCun's scale for tanh uses 1/n1/n (nn inputs per neuron)?

  1. ReLU networks are usually wider, so they need larger weights
  2. ReLU's slope is 22 on positive inputs
  3. ReLU sets about half of its inputs to zero, halving the signal's mean square at every layer; doubling the weight variance compensates
  4. Larger weights make ReLU units saturate, which stabilizes training
Show the answer

C. ReLU sets about half of its inputs to zero, halving the signal's mean square at every layer; doubling the weight variance compensates

For a zero-mean symmetric pre-activation zz, E[ReLU⁡(z)2]=12E[z2]\E[\operatorname{ReLU}(z)^2] = \tfrac12\E[z^2]. Each layer would lose half its mean square; a factor of 22 in the weight variance puts it back, so the per-layer factor is 11.

Question 5

Gradient clipping by norm rescales the gradient g\mathbf g to length cc whenever ∥g∥>c\norm{\mathbf g} > c. What does it change?

  1. It flips the sign of the largest gradient entries
  2. It shortens the step but keeps its direction, so one exploding gradient cannot throw the weights far away
  3. It removes the cause of exploding gradients from the network
  4. It sets small gradient entries to zero to save computation
Show the answer

B. It shortens the step but keeps its direction, so one exploding gradient cannot throw the weights far away

Clipping replaces g\mathbf g by c g/∥g∥c\,\mathbf g/\norm{\mathbf g}: same direction, bounded length. The network can still produce huge gradients; clipping only limits the damage of a single step. The Emergence lesson Exploding Gradients & Clipping shows why this can even speed training up.

Go deeper

Further reading

  • S. J. D. Prince, Understanding Deep Learning, ch. 7 "Gradients and initialization" (MIT Press, 2023), free at udlbook.github.io/udlbook.
  • D. E. Rumelhart, G. E. Hinton & R. J. Williams, "Learning representations by back-propagating errors," Nature 323 (1986).