FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Backpropagation Through Neural Networks

Trace reverse-mode differentiation through neural networks, audit gradient accumulation and VJPs, and manage activation memory during training.

Freshness: current•13 min read•Deep Learning and Specialized AI
Full Technical Reference Document

Mental model

Backpropagation computes a scalar objective’s gradient with respect to every parameter by traversing the operations used in the forward pass in reverse. Each operation applies its local derivative to an incoming gradient, so the system propagates vector-Jacobian products instead of constructing a full Jacobian. The optimizer then uses those gradients to update parameters; the graph and saved forward values define the backward calculation.

Theory

A neural network is a composition of functions. For layer ℓ\ell, write its preactivation as zℓ=Wℓaℓ−1+bℓz^\ell = W^\ell a^{\ell-1}+b^\ell and its activation as aℓ=σ(zℓ)a^\ell=\sigma(z^\ell). The forward pass evaluates these operations and records a directed acyclic graph. Backpropagation starts at the loss and visits the graph in reverse topological order. At each node it multiplies the derivative arriving from later nodes by that operation’s local derivative. If a value feeds two later branches, their gradient contributions are added before continuing toward its producer.

For a scalar loss, reverse mode does not materialize the Jacobian of every layer. With column-vector cotangents, an operation with Jacobian J=∂y/∂xJ=\partial y/\partial x maps the incoming gradient yˉ=∂L/∂y\bar y=\partial L/\partial y to the vector-Jacobian product xˉ=J⊤yˉ\bar x=J^\top\bar y. The shapes follow the operation’s input and output, while the computation cost is typically on the order of another forward evaluation for common neural-network layers. Frameworks retain only the intermediates needed by each backward rule: for example, multiplying by a weight needs that weight, while differentiating an activation may need its input or output.

The layerwise recurrence makes the dependency visible:

δℓ=((Wℓ+1)⊤δℓ+1)⊙σ′(zℓ),∇WℓL=δℓ(aℓ−1)⊤.\delta^\ell = \left((W^{\ell+1})^\top\delta^{\ell+1}\right)\odot\sigma'(z^\ell), \qquad \nabla_{W^\ell}L = \delta^\ell(a^{\ell-1})^\top .

Here aℓa^\ell is the activation vector, zℓz^\ell is the preactivation, WℓW^\ell is the layer’s weight matrix, and σ\sigma is its elementwise activation. δℓ=∂L/∂zℓ\delta^\ell=\partial L/\partial z^\ell is the incoming error signal at that layer. The gradient matrix has the same shape as WℓW^\ell; its entries measure change in loss per unit change in the corresponding weight. For a batch, the framework sums or averages per-example gradients according to the loss reduction. That reduction must agree with how the learning rate and batch size are chosen.

Worked gradient calculation

Take one linear unit with input x=2x=2, weight w=0.25w=0.25, target y=1y=1, and loss L=12(wx−y)2L=\tfrac12(wx-y)^2. The prediction is \$0.5,sotheerroris, so the error is -0.5, the loss is \0.125,andthechainrulegives, and the chain rule gives \partial L/\partial w=(wx-y)x=-1. With a learning rate of \0.1, gradient descent changes the weight to \0.35. The new prediction is \0.7 and the loss is \0.045$. This tiny example checks the sign, scale, and update convention before gradients are trusted in a deeper graph.

Compute layer preactivations and save needed tensors
Seed the scalar loss with its upstream gradient
Apply each operation’s local VJP in reverse graph order
Sum contributions at shared weights and inputs
Inspect gradients before the optimizer updates parameters
Conceptual teaching model synthesized from:rumelhart-backprop-1986,pytorch-repository

Trade-offs

The forward graph consumes memory because backward formulas reuse saved activations. Retaining every activation speeds the backward pass but can limit batch size on a memory-constrained accelerator. Activation checkpointing stores selected boundaries and recomputes some forward operations during backward; it exchanges additional compute for lower activation memory. The useful checkpoint interval depends on layer cost, tensor size, recomputation speed, and the memory budget, so measure end-to-end step time rather than assuming checkpointing is always faster.

Reverse mode is attractive when a model has many parameters but one scalar training loss: one reverse traversal yields gradients for all trainable weights. Forward-mode differentiation can be preferable for functions with few inputs and many outputs. Gradient accumulation across microbatches can emulate a larger effective batch without storing all examples at once, but each loss must be scaled consistently and .grad must be cleared between optimizer steps. Mixed precision reduces activation and gradient storage in some paths, yet small derivatives can underflow; dynamic loss scaling helps detect that condition but does not repair a poor conditioning problem.

Failure modes and misconceptions

Vanishing and exploding gradients arise from repeated products of local Jacobians. If their singular values are mostly below one, a signal can shrink as it crosses many layers; values above one can amplify it. Tanh or sigmoid units in saturated regions have small derivatives, while a poorly scaled recurrent product can still explode. Residual paths, initialization, normalization, and activation choice influence these products. Global norm clipping bounds an update’s gradient magnitude, but it cannot recover information already lost to vanishing derivatives.

Two implementation errors often look like an optimizer failure. Calling backward several times without clearing leaf gradients accumulates them, which is correct for intentional microbatching but wrong for independent updates. Detaching a tensor, converting it to a non-differentiable value, or modifying a saved tensor in place can break or invalidate the graph. A decreasing loss on one batch does not prove that every parameter received the intended derivative; finite-difference checks on a tiny deterministic model can catch missing paths and sign errors.

Decision scenario

A team moves a deep classifier to a smaller GPU. The full batch no longer fits, and one training step produces non-finite gradients after mixed precision is enabled. First reproduce the issue with a fixed seed and a small batch in full precision; inspect activation and gradient norms by layer. If gradients remain finite there, add gradient scaling and compare against the full-precision update. Then benchmark checkpointed microbatches with the same total examples and loss reduction. Keep the change only if the update matches within a declared tolerance and memory and step-time targets both pass.

Learning outcomes

  • Explain how local derivatives compose into reverse-mode vector-Jacobian products.
  • Calculate a parameter gradient and update for a small differentiable graph.
  • Diagnose graph breaks, gradient accumulation, vanishing or exploding signals, and activation-memory trade-offs.

Implementation: verify an autograd gradient

The example checks one parameter derivative against a centered finite difference. Use float64 and a deterministic model for a strict gradcheck; this float32 sample uses a looser tolerance to keep the calculation concise.

python
import torch
from torch import nn
​
torch.manual_seed(7)
model = nn.Sequential(nn.Linear(3, 8), nn.Tanh(), nn.Linear(8, 1))
features = torch.tensor([[1.0, 0.2, 0.4], [0.3, 0.7, 0.1]])
targets = torch.tensor([[0.8], [0.2]])
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
​
prediction = model(features)
loss = nn.functional.mse_loss(prediction, targets)
optimizer.zero_grad(set_to_none=True)
loss.backward()
assert all(p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters())
​
weight = model[0].weight
with torch.no_grad():
analytic = weight.grad[0, 0].clone()
original = weight[0, 0].clone()
epsilon = 1e-3
weight[0, 0].copy_(original + epsilon)
loss_plus = nn.functional.mse_loss(model(features), targets)
weight[0, 0].copy_(original - epsilon)
loss_minus = nn.functional.mse_loss(model(features), targets)
weight[0, 0].copy_(original)
numeric = (loss_plus - loss_minus) / (2 * epsilon)
assert torch.allclose(analytic, numeric, rtol=1e-2, atol=1e-3)
optimizer.step()
Reflect before revealing the guide

Prerequisites & Related Concepts (3)

Private notes

0 words
Recommended Free Track
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.