TExcelTAD
Home › Math for Machine Learning › Backpropagation and Automatic Differentiation

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 KK layers computes

f0=x,fk=σk(Ak−1fk−1+bk−1),L=ℓ(fK,y)\mathbf{f}_0 = \mathbf{x}, \qquad \mathbf{f}_k = \sigma_k(A_{k-1}\mathbf{f}_{k-1} + \mathbf{b}_{k-1}), \qquad L = \ell(\mathbf{f}_K, \mathbf{y})

By the chain rule, the gradient with respect to the parameters θk=(Ak,bk)\boldsymbol{\theta}_k = (A_k, \mathbf{b}_k) of layer kk is

∂L∂θk=∂L∂fK ∂fK∂fK−1⋯∂fk+2∂fk+1 ∂fk+1∂θk\frac{\partial L}{\partial \boldsymbol{\theta}_k} = \frac{\partial L}{\partial \mathbf{f}_K}\,\frac{\partial \mathbf{f}_K}{\partial \mathbf{f}_{K-1}} \cdots \frac{\partial \mathbf{f}_{k+2}}{\partial \mathbf{f}_{k+1}}\,\frac{\partial \mathbf{f}_{k+1}}{\partial \boldsymbol{\theta}_k}

Every layer's gradient shares the same left part ∂L∂fK⋯\frac{\partial L}{\partial \mathbf{f}_K}\cdots. Backpropagation computes it once, from the left: start with the row vector ∂L/∂fK\partial L / \partial \mathbf{f}_K 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 f(x)=x2+exp⁡(x2)+cos⁡(x2+exp⁡(x2))f(x) = \sqrt{x^2 + \exp(x^2)} + \cos(x^2 + \exp(x^2)). Name the intermediate values:

a=x2,b=exp⁡(a),c=a+b,d=c,e=cos⁡(c),f=d+ea = x^2, \quad b = \exp(a), \quad c = a + b, \quad d = \sqrt{c}, \quad e = \cos(c), \quad f = d + e

Reverse mode goes backwards, computing vˉ=∂f/∂v\bar{v} = \partial f / \partial v for each node from its children:

dˉ=1,eˉ=1cˉ=dˉ 12c+eˉ (−sin⁡c)bˉ=cˉ,aˉ=cˉ+bˉ exp⁡(a)xˉ=aˉ⋅2x\begin{aligned} \bar{d} &= 1, \quad \bar{e} = 1 \\ \bar{c} &= \bar{d}\,\frac{1}{2\sqrt{c}} + \bar{e}\,(-\sin c) \\ \bar{b} &= \bar{c}, \quad \bar{a} = \bar{c} + \bar{b}\,\exp(a) \\ \bar{x} &= \bar{a}\cdot 2x \end{aligned}

The node aa feeds two children (bb and cc), so its adjoint sums the contributions.

python · try it yourself
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

python · try it yourself
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 both jax.grad (reverse) and jax.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 f=a⋅bf = a \cdot b with a=x+ya = x + y and b=x−yb = x - y, compute ∂f/∂x\partial f / \partial x by reverse mode at (x,y)=(3,1)(x, y) = (3, 1).

Answer
Solution

a=4a = 4, b=2b = 2. aˉ=b=2\bar{a} = b = 2, bˉ=a=4\bar{b} = a = 4. xx feeds both: xˉ=aˉ⋅1+bˉ⋅1=6\bar{x} = \bar{a} \cdot 1 + \bar{b} \cdot 1 = 6. Check: f=x2−y2f = x^2 - y^2, ∂f/∂x=2x=6\partial f / \partial x = 2x = 6.

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 L=(σ(wx+b)−y)2L = (\sigma(wx + b) - y)^2 with w=0.5w = 0.5, b=−0.2b = -0.2, x=2x = 2, y=1y = 1, compute ∂L/∂w\partial L / \partial w by the chain rule and check numerically.

Answer

About −0.2653-0.2653.

Solution

z=0.8z = 0.8, s=σ(0.8)s = \sigma(0.8); ∂L∂w=2(s−y) s(1−s) x\frac{\partial L}{\partial w} = 2(s - y)\,s(1 - s)\,x.

python · try it yourself
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…

  1. from the input towards the loss
  2. from the loss backwards towards the input
  3. in random order
  4. only for the last layer

When a node feeds into two later nodes, its adjoint is…

  1. the larger of the two contributions
  2. the sum of the contributions
  3. the product of the contributions
  4. zero

The main cost of reverse mode compared to forward mode is…

  1. it gives wrong answers
  2. memory: intermediate values must be stored
  3. it only works for linear functions
  4. it needs symbolic algebra