Backpropagation and Automatic Differentiation
A deep network is a long chain of simple functions. Its gradient is a long product of Jacobians, and the order in which you multiply them decides whether training is cheap or impossible. Backpropagation multiplies from the loss backwards; automatic differentiation generalizes the idea to any program built from differentiable operations.
A network is a composition
A network with layers computes
By the chain rule, the gradient with respect to the parameters of layer is
Every layer's gradient shares the same left part . Backpropagation computes it once, from the left: start with the row vector and multiply by one Jacobian at a time. Each step is a cheap vector-Jacobian product, and the partial result is reused for the layer below.
Computation graphs
Autodiff sees a program as a graph of elementary operations. Take . Name the intermediate values:
Reverse mode goes backwards, computing for each node from its children:
The node feeds two children ( and ), so its adjoint sums the contributions.
import numpy as np
x = 0.7
# forward pass: store intermediates
a = x**2; b = np.exp(a); c = a + b; d = np.sqrt(c); e = np.cos(c); f = d + e
# backward pass
d_bar = 1.0; e_bar = 1.0
c_bar = d_bar / (2 * np.sqrt(c)) + e_bar * (-np.sin(c))
b_bar = c_bar
a_bar = c_bar + b_bar * np.exp(a)
x_bar = a_bar * 2 * x
F = lambda x: np.sqrt(x**2 + np.exp(x**2)) + np.cos(x**2 + np.exp(x**2))
numeric = (F(x + 1e-6) - F(x - 1e-6)) / 2e-6
print(f"f = {f:.6f}, reverse-mode df/dx = {x_bar:.6f}, numeric = {numeric:.6f}")f = 0.932835, reverse-mode df/dx = -1.874002, numeric = -1.874002
Forward versus reverse mode
Forward mode pushes derivatives along with values, from inputs to outputs; one pass gives the derivative with respect to one input. Reverse mode needs one forward pass (storing intermediates) and one backward pass, and gives the derivative of one output with respect to all inputs. A loss has one output and millions of parameters, so reverse mode wins by a factor of millions. The price is memory: all intermediate values must be kept for the backward pass.
Backprop for a two-layer network
import numpy as np
rng = np.random.default_rng(0)
x, y = rng.normal(size=3), np.array([1.0, 0.0])
W1, b1 = rng.normal(size=(4, 3)), np.zeros(4)
W2, b2 = rng.normal(size=(2, 4)), np.zeros(2)
def loss(W1):
h = np.tanh(W1 @ x + b1)
return 0.5 * np.sum((W2 @ h + b2 - y) ** 2)
# forward
z1 = W1 @ x + b1; h = np.tanh(z1); out = W2 @ h + b2
# backward (vector-Jacobian products, gradients shaped like the variables)
g_out = out - y # dL/d out
g_W2 = np.outer(g_out, h)
g_h = W2.T @ g_out
g_z1 = g_h * (1 - h**2) # tanh' = 1 - tanh^2, elementwise
g_W1 = np.outer(g_z1, x)
num = np.zeros_like(W1)
for i in range(4):
for j in range(3):
E = np.zeros_like(W1); E[i, j] = 1e-6
num[i, j] = (loss(W1 + E) - loss(W1 - E)) / 2e-6
print("dL/dW1 matches numeric:", np.allclose(g_W1, num, atol=1e-8))
print("dL/dW2 shape:", g_W2.shape, " dL/dW1 shape:", g_W1.shape)dL/dW1 matches numeric: True
dL/dW2 shape: (2, 4) dL/dW1 shape: (4, 3)
The deep-learning course builds a tiny reverse-mode engine and treats backprop through softmax, convolutions and attention: Building a Tiny Autodiff Engine. The calculus course has a gentler introduction.
In software
- PyTorch records the graph during the forward pass and runs reverse mode on
loss.backward(); JAX offers bothjax.grad(reverse) andjax.jvp(forward). - Gradient checkpointing trades compute for memory by recomputing some intermediates in the backward pass.
- Forward mode is preferred when there are few inputs and many outputs (sensitivities of a simulation to a handful of parameters).
Go further: A Small Autograd Engine for Arrays in the Deep Learning course extends this to whole arrays, including the un-broadcast that broadcasting needs.
Exercises
Exercise 1: Adjoints by hand
For with and , compute by reverse mode at .
Answer
Solution
, . , . feeds both: . Check: , .
Exercise 2: Which mode?
You need the gradient of one scalar loss with respect to 10 million weights. Forward or reverse mode?
Answer
Reverse mode.
Solution
Forward mode would need one pass per input, 10 million passes. Reverse mode gets all partial derivatives of the single output in one forward and one backward pass, at a cost of a small constant times the forward pass.
Exercise 3: Backprop through a sigmoid neuron (code)
For with , , , , compute by the chain rule and check numerically.
Answer
About .
Solution
, ; .
import numpy as np
sig = lambda z: 1 / (1 + np.exp(-z))
w, b, x, y = 0.5, -0.2, 2.0, 1.0
s = sig(w * x + b)
g = 2 * (s - y) * s * (1 - s) * x
L = lambda w: (sig(w * x + b) - y) ** 2
print(round(g, 6), round((L(w + 1e-6) - L(w - 1e-6)) / 2e-6, 6))-0.26527 -0.26527
Test yourself
Backpropagation multiplies the chain of Jacobians…
- from the input towards the loss
- from the loss backwards towards the input
- in random order
- only for the last layer
When a node feeds into two later nodes, its adjoint is…
- the larger of the two contributions
- the sum of the contributions
- the product of the contributions
- zero
The main cost of reverse mode compared to forward mode is…
- it gives wrong answers
- memory: intermediate values must be stored
- it only works for linear functions
- it needs symbolic algebra