How does backpropagation compute every gradient?
Company tags are compiled from public interview reports and are signals, not guarantees.
What interviewers are testing
This question tests whether you understand training as a computational graph rather than a library call. Interviewers listen for the chain rule stated precisely, for why activations are cached, and for the intuition that depth turns gradients into long products that can vanish or explode. The follow-ups — reverse versus forward mode, residual connections, gradient accumulation — show whether the model extends to the debugging questions that real training runs generate.
Mental model
The forward pass computes activations and a scalar loss, caching everything the derivatives will need. The backward pass walks the graph in reverse, letting each layer multiply the gradient it receives by its own local Jacobian, so every weight ends up with dL/dW. An optimizer then nudges each parameter along the negative gradient scaled by the learning rate. Depth makes that backward product long, which is why gradient magnitudes need residual paths, normalization, and careful initialization to stay near one.
Step-by-step solution
Step 1: Forward pass computes the loss
Training starts with a forward pass. The input batch flows through each layer: a linear transform followed by a nonlinearity, producing activations a1, a2, and finally the output prediction. The loss function compares that prediction with the target and reduces the difference to a single scalar — cross-entropy for classification, mean squared error for regression. Watch the animation as the signal moves left to right, one node at a time, until the scalar loss appears at the end. The crucial detail is what the framework does silently: every intermediate activation and pre-activation is cached, because the backward pass will need those exact values as multiplicative factors. Without the cache, gradient computation would have to recompute the forward pass; with it, each local derivative can be evaluated cheaply. That cached graph of tensors is the computation graph autograd builds, and the scalar loss is its root.
Step 2: Backward pass applies the chain rule
The backward pass is the chain rule applied mechanically, from the loss toward the inputs. Start with dL/dL = 1 at the scalar root. Each layer receives a gradient with respect to its output and multiplies it by its own local Jacobian to produce the gradient with respect to its input: dL/dx = dL/dz · dz/dx. For a linear layer z = Wx + b, that local derivative is just W; for an activation, it is the elementwise derivative evaluated at the cached pre-activation. Watch the animation as gradient packets travel in reverse, each hop multiplying the signal by a local term. The reverse order is forced by dependencies: a layer's gradient is only computable once the gradient from the layer above it is known. That is also why reverse-mode autodiff is the right choice for deep learning — one scalar loss and millions of parameters means a single backward sweep yields every parameter gradient at once.
Step 3: Gradients accumulate at every weight
Parameter gradients appear at the point where each weight multiplies an activation. For a linear layer, the gradient with respect to the weights is the outer product of the incoming gradient δ and the cached input: dL/dW = δ aᵀ, and the bias gradient is δ summed over the batch. This is why forward activations were cached — they are the second factor in every weight gradient. Watch the animation: the reverse signal reaches the output weights first, then hidden-2 weights, then hidden-1 weights, and each layer fills a gradient buffer shaped exactly like its parameters. Frameworks accumulate into that buffer rather than overwrite it, which is convenient for gradient accumulation over micro-batches but dangerous if you forget to zero the buffers between optimization steps. Batch size is folded in by summing or averaging these per-example gradients. After the sweep every parameter has a gradient of the same shape, ready for the optimizer.
Step 4: Descend in the negative direction
Gradients point uphill. The gradient dL/dW tells you how the loss changes as a weight increases, so the descent update moves the parameter in the opposite direction: W ← W − η · dL/dW, where η is the learning rate. Watch the animation as the optimizer consumes the gradient buffer and writes new values back into the parameters. Plain SGD uses the raw gradient; momentum adds a running velocity that smooths noisy directions; Adam divides each gradient by a running estimate of its scale, giving every weight an adaptive step. Modern frameworks zero the gradient buffers after each update, because accumulation across iterations would otherwise mix in stale information. The learning rate matters as much as the direction: too small and training crawls, too large and the step overshoots the minimum, making the loss bounce or diverge even though every gradient was computed correctly.
Step 5: When gradients vanish or explode
Backpropagation multiplies one local derivative per layer, so depth turns the gradient into a product of many factors with its own dynamics. If each factor has magnitude below one — sigmoid saturates at a derivative of at most 0.25 — the product shrinks geometrically and early layers receive a vanishing signal that barely moves them. If the factors exceed one, the same product explodes into massive updates or NaNs. Watch the animation: the backward signal decays through the stack until almost nothing reaches layer one. The fixes restore the product's magnitude near one from both sides. Residual connections add an identity term that carries gradients across blocks unchanged. Normalization layers keep activations and their derivatives well-scaled. Non-saturating activations like ReLU or GELU avoid the sigmoid's tiny derivative, careful He or Xavier initialization starts the product balanced, and gradient clipping caps the occasional spike. Diagnose by logging per-layer gradient norms, not just the loss.
Edge cases & traps
- Forgetting to zero gradients between steps: PyTorch accumulates into .grad, so two iterations without zero_grad() sum two batches of gradients — call optimizer.zero_grad() every step.
- Blowing up memory by keeping the whole autograd graph alive: detach tensors used only for metrics and wrap evaluation in torch.no_grad(), or the graph pins activations for the entire run.
- Debugging a silent vanishing signal by watching the loss alone: log per-layer gradient norms (hooks or a profiler) so a decaying backward signal is visible before training plateaus.
- Clipping gradients and declaring victory: clipping caps NaNs but does not fix a bad init or saturated activations — pair it with residual and normalization fixes.
- Choosing a learning rate too large for the loss surface: the step overshoots and the loss diverges even though gradients are correct — sweep the LR or add warmup and a schedule.