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 , write its preactivation as and its activation as . 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 maps the incoming gradient to the vector-Jacobian product . 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:
Here is the activation vector, is the preactivation, is the layer’s weight matrix, and is its elementwise activation. is the incoming error signal at that layer. The gradient matrix has the same shape as ; 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 , weight , target , and loss . The prediction is \$0.5-0.5, the loss is \0.125\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.
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.
pythonimport torchfrom torch import nntorch.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].weightwith torch.no_grad():analytic = weight.grad[0, 0].clone()original = weight[0, 0].clone()epsilon = 1e-3weight[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()