Backpropagation

How neural networks compute gradients — computational graphs, the chain rule applied backwards, a worked numeric example, vectorised backprop for layers, automatic differentiation (reverse mode) in PyTorch, a tiny autograd engine, and vanishing/exploding gradients.

Advanced 5 min readLesson 8 of 14 Interview Q&A

To train with gradient descent, we need the gradient of the loss with respect to every weight — millions or billions of them. Computing each separately would be hopeless. Backpropagation computes all of them in one backward pass, at roughly the cost of a forward pass, by applying the chain rule systematically from the output back to the inputs.

Computational graphs

Any computation can be written as a graph of simple operations. For L=(wx+b−y)2L = (wx + b - y)^2:

w = 2x = 3× u = 6b = 1+z = 7y = 10−e = −3²L = 9

Forward pass: compute values left to right: u = wx = 6, z = u + b = 7, e = z − y = −3, L = e² = 9.

The backward pass

Start at the output with ∂L/∂L=1\partial L / \partial L = 1 and move right to left. At each node, multiply the incoming gradient (the upstream gradient) by the node's local derivative — the chain rule:

∂L∂w=∂L∂e⋅∂e∂z⋅∂z∂u⋅∂u∂w\frac{\partial L}{\partial w} = \frac{\partial L}{\partial e} \cdot \frac{\partial e}{\partial z} \cdot \frac{\partial z}{\partial u} \cdot \frac{\partial u}{\partial w}
NodeLocal derivativeGradient of L
L = e²∂L/∂e = 2e = −6∂L/∂e = −6
e = z − y∂e/∂z = 1∂L/∂z = −6 × 1 = −6
z = u + b∂z/∂u = 1, ∂z/∂b = 1∂L/∂u = −6, ∂L/∂b = −6
u = w·x∂u/∂w = x = 3, ∂u/∂x = w = 2∂L/∂w = −6 × 3 = −18, ∂L/∂x = −12

The gradient says: increasing w increases L at rate −18 — i.e. increasing w decreases the loss. A gradient step with η = 0.01 gives w = 2 + 0.18 = 2.18, moving the prediction from 7 toward the target 10.

Patterns worth remembering:

  • Addition distributes the upstream gradient unchanged to all inputs.
  • Multiplication sends each input the upstream gradient times the other input.
  • When a value feeds several nodes, its gradients from each path are summed.

Why "reverse mode" is efficient

The network has one scalar output (the loss) and many inputs (parameters). Going backwards from that single output, one pass yields the gradient for all parameters simultaneously, reusing intermediate results — dynamic programming over the graph. (Forward-mode differentiation would need one pass per parameter.) The cost: forward activations must be stored for the backward pass, which is why training needs much more memory than inference.

Backprop through a layer

For a dense layer z=Wx+b\mathbf{z} = W\mathbf{x} + \mathbf{b}, a=f(z)\mathbf{a} = f(\mathbf{z}), given the upstream gradient δ=∂L/∂a\boldsymbol{\delta} = \partial L / \partial \mathbf{a}:

∂L∂z=δ⊙f′(z),∂L∂W=∂L∂z x⊤,∂L∂b=∂L∂z,∂L∂x=W⊤∂L∂z\frac{\partial L}{\partial \mathbf{z}} = \boldsymbol{\delta} \odot f'(\mathbf{z}), \quad \frac{\partial L}{\partial W} = \frac{\partial L}{\partial \mathbf{z}} \, \mathbf{x}^\top, \quad \frac{\partial L}{\partial \mathbf{b}} = \frac{\partial L}{\partial \mathbf{z}}, \quad \frac{\partial L}{\partial \mathbf{x}} = W^\top \frac{\partial L}{\partial \mathbf{z}}

The last term becomes the upstream gradient for the previous layer. Backprop is just these matrix multiplications, layer after layer — the same GPU-friendly operations as the forward pass.

Python
import numpy as np

def relu(z): return np.maximum(0, z)

# Two-layer network, one batch: X (n×d), y (n×1)
def train_step(X, y, W1, b1, W2, b2, lr=1e-2):
    # forward
    z1 = X @ W1 + b1;  a1 = relu(z1)
    pred = a1 @ W2 + b2
    loss = ((pred - y) ** 2).mean()

    # backward
    n = len(X)
    d_pred = 2 * (pred - y) / n          # ∂L/∂pred
    dW2 = a1.T @ d_pred;  db2 = d_pred.sum(0)
    d_a1 = d_pred @ W2.T                 # pass gradient to the previous layer
    d_z1 = d_a1 * (z1 > 0)               # ReLU derivative
    dW1 = X.T @ d_z1;     db1 = d_z1.sum(0)

    # update
    for p, g in ((W1, dW1), (b1, db1), (W2, dW2), (b2, db2)):
        p -= lr * g
    return loss

Automatic differentiation

Nobody writes backward passes by hand any more. Frameworks — PyTorch, JAX, TensorFlow — record the operations of the forward pass into a graph and apply each operation's known derivative in reverse:

Python
import torch

w = torch.tensor(2.0, requires_grad=True)
b = torch.tensor(1.0, requires_grad=True)
x, y = torch.tensor(3.0), torch.tensor(10.0)

L = (w * x + b - y) ** 2
L.backward()                    # reverse-mode autodiff through the recorded graph
print(w.grad, b.grad)           # tensor(-18.) tensor(-6.) — matches the table above

A tiny autograd engine

The core idea fits in a few dozen lines (in the spirit of Karpathy's micrograd):

Python
class Value:
    def __init__(self, data, parents=(), backward=lambda: None):
        self.data, self.grad = data, 0.0
        self._parents, self._backward = parents, backward

    def __add__(self, other):
        out = Value(self.data + other.data, (self, other))
        def backward():
            self.grad += out.grad            # addition passes the gradient through
            other.grad += out.grad
        out._backward = backward
        return out

    def __mul__(self, other):
        out = Value(self.data * other.data, (self, other))
        def backward():
            self.grad += other.data * out.grad   # times the other input
            other.grad += self.data * out.grad
        out._backward = backward
        return out

    def backward(self):
        order, seen = [], set()
        def visit(v):                        # topological sort
            if v not in seen:
                seen.add(v)
                for p in v._parents: visit(p)
                order.append(v)
        visit(self)
        self.grad = 1.0
        for v in reversed(order):            # apply the chain rule in reverse order
            v._backward()

Vanishing and exploding gradients

Backprop multiplies many local derivatives together. In deep networks:

  • If they're mostly < 1 (e.g. sigmoid's derivative is at most 0.25), gradients shrink exponentially toward the early layers — vanishing gradients: early layers barely learn.
  • If they're mostly > 1, gradients grow exponentially — exploding gradients: unstable updates, NaN losses.

This plagued early deep networks and plain RNNs (RNNs). The fixes are now standard:

FixHow it helps
ReLU-family activationsDerivative 1 for positive inputs — no shrinking
He / Xavier initialisationKeeps signal variance roughly constant across layers
Normalisation layersKeep activations in a healthy range
Residual connectionsThe identity path passes gradients through unchanged
LSTM/GRU gatingAdditive memory paths for sequences
Gradient clippingCaps exploding gradient norms

Memory and compute tricks

  • Gradient checkpointing: store only some activations and recompute the rest during the backward pass — trades compute for memory.
  • Mixed precision (bf16/fp16 with fp32 master weights): halves memory and speeds up GPU math.
  • Gradient accumulation: sum gradients over several small batches before an update to simulate a larger batch.
Key takeaways
  • Backpropagation is the chain rule applied backwards through a computational graph.
  • One backward pass gives the gradient for every parameter at roughly the cost of the forward pass (reverse-mode autodiff).
  • Add nodes pass gradients through; multiply nodes scale by the other input; branches sum.
  • For dense layers, backprop is matrix multiplications: dW = δ xᵀ, dx = Wᵀ δ.
  • Frameworks record the forward graph and differentiate automatically.
  • Deep products of derivatives cause vanishing or exploding gradients; ReLU, good initialisation, normalisation, residuals and clipping fix them.
Interview questions
QExplain backpropagation in simple terms.medium

The network computes a loss through a chain of simple operations. Backpropagation walks that chain in reverse: starting from the loss, it uses each operation's local derivative and the chain rule to work out how much each intermediate value — and ultimately each weight — contributed to the error. Because intermediate results are reused, one backward pass gives gradients for all weights at about the cost of a forward pass; the optimiser then nudges every weight in the direction that reduces the loss.