core29 min studyLesson 14 in Engineering

Backpropagation through a computation graph

Trace how a scalar loss sends sensitivity backward through shared operations and learn to verify a gradient.

On this page

What you’ll understand

  • Apply the chain rule along a computation graph.
  • Accumulate contributions when a value feeds multiple paths.
  • Distinguish gradient calculation from an optimizer update.

A neural network is a composition of ordinary operations. Backpropagation makes the derivative of a scalar loss with respect to many parameters efficient by reusing local derivatives. It does not choose a learning rate or update weights by itself. Understanding this distinction helps diagnose disconnected graphs, exploding sensitivities, and training loops that run without learning anything useful.

Local derivatives compose into global sensitivity

Consider a=wx+ba=wx+b, h=σ(a)h=\sigma(a), and a loss L(h,y)L(h,y). The forward pass stores values needed for derivatives. Starting with the derivative of the loss with respect to its own value equal to one, the reverse pass multiplies each arriving sensitivity by the local derivative. The derivative of aa with respect to ww is xx, so a large input can amplify the weight gradient even when the upstream sensitivity is modest. Units and input scaling matter here too.

Reverse-mode differentiation is especially useful when many parameters influence one scalar objective. It computes vector-Jacobian products without constructing every full Jacobian. The graph is the actual executed computation, including branches that were taken. Automatic differentiation follows the implemented expression; it cannot infer a missing operation or correct a wrongly normalized loss. A perfectly computed gradient of the wrong objective is still the wrong training signal.

∂L∂w=∂L∂h∂h∂a∂a∂w\frac{\partial L}{\partial w}=\frac{\partial L}{\partial h}\frac{\partial h}{\partial a}\frac{\partial a}{\partial w}
The chain rule applies at differentiable points of this scalar chain. More general tensor operations use the same principle through vector-Jacobian products.↔ Scroll wide equations horizontally.

Shared paths require addition, not replacement

If one parameter feeds two downstream branches, its derivative is the sum of both contributions. For L=w2+3wL=w^2+3w, one branch contributes 2w2w and the other contributes 33. Forgetting one branch loses real sensitivity. This also explains gradient accumulation across examples: a mean loss averages their contributions, whereas a summed loss adds them. Changing reduction semantics silently changes update scale if the learning rate stays fixed.

In PyTorch, backward accumulates into parameter gradient buffers, so ordinary independent optimization steps need gradients cleared at the intended boundary. Accumulation over microbatches is deliberate only when scaling matches the desired global objective. Detaching a value or converting it into an unrelated constant breaks its differentiable path. In-place changes to saved values can invalidate a backward calculation. Watch tensor shapes, graph connectivity, and reduction rules before blaming the optimizer.

L=1n∑iLi⟹∇θL=1n∑i∇θLiL=\frac{1}{n}\sum_i L_i\quad\Longrightarrow\quad \nabla_\theta L=\frac{1}{n}\sum_i\nabla_\theta L_i
Differentiation is linear for these finite differentiable sums. Correct microbatch accumulation must reproduce the weighting of the intended per-example mean, including an uneven final microbatch.↔ Scroll wide equations horizontally.

Check a gradient and understand its limits

For a small smooth function, compare an automatic derivative to a central finite difference: evaluate the loss at a parameter slightly above and below its current value. A discrepancy can reveal a graph error or a wrong analytical derivative. The step must balance truncation error against floating-point cancellation. Use higher precision for a diagnostic and avoid nondifferentiable points such as exactly zero for ReLU, where different conventions or nearby slopes complicate the comparison.

Deep compositions multiply many local derivatives. Repeated small factors can shrink early-layer gradients; large factors can amplify them. Initialization, activation choice, normalization, and residual paths influence this behavior. A zero derivative through an inactive ReLU is a model property, not necessarily an autograd bug. Inspect gradient norms by layer and try to overfit a tiny clean dataset. A system that cannot fit a few examples usually needs debugging before more data or compute.

Follow a scalar graph all the way back

Let a=wx+b, h=a², and L=(h−y)²/2. Use x=2, w=1, b=0, and y=1.

  1. Forward: a=2, h=4, and L=(4−1)²/2=4.5. Keep these intermediate values for the reverse calculation.

  2. Backward from the loss: the sensitivity to h is h−y=3. The sensitivity to a is 3×2a=12.

  3. The weight sensitivity is 12×x=24 and the bias sensitivity is 12×1=12. A small increase in w therefore raises this loss about twice as fast as the same increase in b at this point.

∂L∂w=(a2−y)(2a)x=3⋅4⋅2=24\frac{\partial L}{\partial w}=(a^2-y)(2a)x=3\cdot4\cdot2=24
The derivative uses the squared activation specified in the example, not sigmoid or ReLU.↔ Scroll wide equations horizontally.
The result

Backpropagation produces gradients 24 and 12; a separate optimizer decides how far to move. These are local sensitivities, not a guarantee that a large step lowers loss.

Explore the model

Interactive lab

Interactive lab · network

Inspect one differentiable composition

The graph computes sigma(wx−0.5). Vary input x and weight w to inspect the multiplication, fixed bias, and sigmoid stages. This forward computation does not animate a reverse pass or a shared-branch network; derive its local sensitivities using the chain rule.

Inspect one differentiable compositionOne inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Current readings: Product · wx: 1.2; Logit · wx − 0.5: 0.7; Sigmoid output: 0.6682. All parameters are adjustable with the labeled controls below.One input. One weight. One sigmoid.x1.20× w1.20+ b0.70σ0.668output0.668w = 1.00b = −0.50σ(z) = 1 / (1 + exp(−z))
Computation graphSignal trace
Product · wx
1.2
Logit · wx − 0.5
0.7
Sigmoid output
0.6682
t = 0 s

One inspectable sigmoid unit, σ(wx − 0.5). Playback traces the computation graph. There is no training, attention mechanism or hidden deep network. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA small auditable composition is a useful starting point for checking how each operation contributes sensitivity.

Check your understanding

A parameter contributes to two branches of a scalar loss. How are its reverse-pass contributions combined?

Try it yourself

For L=w²+3w at w=2, compute the analytical derivative and check it with a central difference of step 0.01.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Evaluate L at 2.01 and 1.99, subtract, then divide by 0.02.

Compare with the solution

The analytical derivative is 2w+3=7. L(2.01)=10.0701 and L(1.99)=9.9301; their difference 0.14 divided by 0.02 is 7. Agreement validates this local derivative for this smooth quadratic; it does not validate an entire training pipeline.

f′(w)≈f(w+ε)−f(w−ε)2εf'(w)\approx\frac{f(w+\varepsilon)-f(w-\varepsilon)}{2\varepsilon}
Central differencing has second-order truncation error for a sufficiently smooth function, but finite precision limits how small epsilon should be.↔ Scroll wide equations horizontally.

Take it with you

  • Backpropagation evaluates derivatives; optimization applies an update.
  • Shared graph paths and microbatches require correct accumulation.
  • Use tiny examples and finite differences to debug a training signal.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.