Backpropagation is the algorithm that computes the gradient of a scalar loss with respect to every parameter of a network, in time comparable to one forward pass. It is the chain rule applied in a clever order, and it is reverse-mode automatic differentiation specialized to neural nets. Once you have done one by hand with numbers, loss.backward() stops being magic and starts being bookkeeping.

Blame flows backwards: each connection learns how much it caused the mistake. Rendered for this page.
Mental Model
- A model is a computational graph: nodes are operations, edges carry tensors. Each node knows its own local derivative.
- The chain rule multiplies local derivatives along paths. Backprop organizes those products so shared work is done once.
- Reverse mode costs about one extra pass for a scalar output, no matter how many parameters there are. Forward mode would need one pass per parameter.
- Memory is the price: reverse mode stores forward activations until the backward pass uses them.
- Deep stacks multiply many Jacobians, so gradients tend to shrink or grow exponentially with depth.
1. Computational Graphs and the Chain Rule
Write the loss as a composition . With intermediate values , the chain rule gives
So if you know the gradient arriving from above (, often called the upstream gradient), multiplying by the transpose of the node’s local Jacobian passes it down. Each node needs only two things: how to compute its output, and how to turn an upstream gradient into gradients for its inputs and parameters. When a value is used in several places, the gradients from each use are summed.
For a linear layer with upstream gradient :
For an elementwise activation the Jacobian is diagonal, so the backward step is the elementwise product .
2. Forward Mode Versus Reverse Mode
Take a function with Jacobian factored as a product of per-node Jacobians, . The order of multiplication is up to you.
Forward mode pushes a tangent vector from the input side. One sweep yields one column of (the effect of one input direction on all outputs), so a full Jacobian costs sweeps. Reverse mode pulls a cotangent from the output side. One sweep yields one row of (the sensitivity of one output to all inputs), so a full Jacobian costs sweeps.
A training loss has and in the millions or billions. Reverse mode gets the full gradient in one backward sweep, at a cost of a small constant multiple of the forward pass. Forward mode would need sweeps. This asymmetry is the whole reason deep learning is practical. Forward mode wins in the opposite regime, few inputs and many outputs, and it also lets you compute Jacobian-vector products without storing activations.
3. A Two-Layer MLP by Hand
Network: input , hidden layer of two ReLU units, one linear output, squared-error loss with target .
with , , (hidden biases left at zero).
Forward pass
. Both are positive, so . . .
Backward pass
Start at the loss: . Output layer: and . Into the hidden layer: . Through the ReLU, both units were active, so the mask is and . First layer: .
A ReLU unit with would have blocked its gradient entirely, contributing a zero row to . A gradient step with then moves toward the target, because every update is .
4. Gradient Checking
Hand-written backward passes are easy to get subtly wrong. The standard test compares the analytic gradient with a central finite difference,
whose error is (a forward difference is only ). Compare with a relative error . As a rule of thumb, in float64 with a correct implementation lands around or below, and an error near or more points to a bug. Use float64, because float32 round-off swamps the difference. Avoid checking exactly at ReLU kinks, where the numeric derivative is not defined.
import numpy as np
x, t = np.array([1.0, 2.0]), 1.0
W1 = np.array([[0.1, 0.2], [0.3, -0.1]]); w2 = np.array([0.5, -0.4]); b2 = 0.1
def loss(W1, w2, b2):
h = np.maximum(W1 @ x, 0)
return 0.5 * (w2 @ h + b2 - t) ** 2
# analytic gradients (the hand calculation)
z1 = W1 @ x; h = np.maximum(z1, 0); dy = w2 @ h + b2 - t
dw2 = dy * h
dW1 = np.outer(dy * w2 * (z1 > 0), x)
def numeric(P, f, eps=1e-5):
G = np.zeros_like(P)
for i in np.ndindex(P.shape):
old = P[i]
P[i] = old + eps; up = f()
P[i] = old - eps; dn = f()
P[i] = old
G[i] = (up - dn) / (2 * eps)
return G
rel = lambda a, b: np.linalg.norm(a - b) / (np.linalg.norm(a) + np.linalg.norm(b))
print("dW1 rel err:", rel(dW1, numeric(W1, lambda: loss(W1, w2, b2))))
print("dw2 rel err:", rel(dw2, numeric(w2, lambda: loss(W1, w2, b2))))Running this gives relative errors of about for and for , and the numeric matches the matrix computed by hand in section 3. The loop makes two forward passes per parameter, so gradient checking is for tests on tiny models, never for training.
5. Vanishing and Exploding Gradients
Back through layers, the gradient is a product of factors of the form . If the typical singular value of each factor is below 1 the product shrinks exponentially, and above 1 it grows exponentially. Sigmoid is a bad case: , so even with unit-scale weights each layer cuts the gradient by 4x or more.
A quick experiment (random 50-wide layers, weights drawn from , 20 layers, gradient of the sum of the top activations with respect to the input) shows the effect:
| Activation | Weight scale | Input gradient norm after 20 layers |
|---|---|---|
| sigmoid | 1.0 | |
| ReLU | 0.5 | |
| ReLU | 1.0 | |
| ReLU | 2.0 |
The ReLU rows show both failure modes from one knob. The balance point for ReLU is (He initialization), which keeps activation variance roughly constant from layer to layer and sits between the last two rows. The standard defenses are sensible initialization (Xavier or He), non-saturating activations, normalization layers, residual connections (they give the gradient an identity path), and gradient clipping for the exploding case. Recurrent nets suffer worst because the same matrix is multiplied once per time step.
Common mistake
Forgetting to zero gradients between steps in PyTorch silently accumulates them, because backward adds into
.gradinstead of overwriting it. Gradient accumulation is deliberate in some setups, but in a plain loop callzero_grad()every step.
Related
- Gradient Descent and Optimizers: what to do with the gradients once you have them
- Linear and Logistic Regression: the one-layer case, where
- The PyTorch Training Loop:
backward(),zero_grad()andstep()in context - Convolutional Networks: backprop through weight-shared layers
- Foundation Models L02: ML Basics: backpropagation as presented in the lecture
- MLP L04: RNNs: backpropagation through time, where the vanishing gradient problem is sharpest