Skip to content

Autodiff graphs, backpropagation and the gradient check

Draw a program as a graph of small operations, push values forward and derivatives backward, and see why reverse mode gets every gradient for the price of about one extra pass. Then catch a wrong gradient with finite differences.

Advanced ~14 min9 steps

You will be able to

  • Run a forward and a backward pass by hand on a small computational graph
  • Explain why reverse mode suits one loss and many parameters, and what it costs in memory
  • Check gradients with central finite differences and read the relative error

Read first

01

A program as a graph

Read

Write f(x,y)=(x+y) yf(x, y) = (x + y)\,y as two small steps: a=x+ya = x + y, then f=a⋅yf = a \cdot y. Each step is a node; each value flows along an edge. That drawing is a computational graphComputational graphA program drawn as nodes (operations) and edges (values), so each piece's derivative can be chained..

Automatic differentiationAutomatic differentiationExact derivatives of a program, found by applying the chain rule to each recorded operation: not symbolic, not finite differences. records this graph as the program runs and applies the chain rule node by node. It gives exact derivatives of the code that ran: not a symbolic formula, and not an approximation from nudging inputs.

02

Forward, then backward

Read

Take x=1x = 1, y=2y = 2.

Forward: a=3a = 3, f=6f = 6. Keep both.

Backward: start with ∂f/∂f=1\partial f/\partial f = 1 and walk the graph in reverse, multiplying by each node's local derivative.

  • At f=a⋅yf = a \cdot y: ∂f/∂a=y=2\partial f/\partial a = y = 2 and the direct ∂f/∂y=a=3\partial f/\partial y = a = 3.
  • At a=x+ya = x + y: pass 22 on to xx and to yy.
  • yy is used twice, so its two contributions add: 3+2=53 + 2 = 5.

Result: ∇f=(2,5)\nabla f = (2, 5). Check against f=xy+y2f = xy + y^2: (y,  x+2y)=(2,5)(y,\; x + 2y) = (2, 5).

03

Predict

Predict

Predict first

A value feeds two later nodes. During the backward pass, how do the two derivative contributions that reach it combine?

Multiply themAdd themKeep the larger
Reveal

Add them. Each path from the value to the loss is a separate route for a nudge to travel, and the multivariable chain rule sums over routes.

04

Why reverse mode wins for training

Read

Forward mode carries derivatives along with the values: one pass gives the derivatives of every output with respect to one input. Reverse mode goes backward from one output: one pass gives that output's derivative with respect to every input.

Training has one loss and up to billions of weights, so reverse mode delivers the whole gradient for roughly the cost of one extra pass. On a network, reverse mode is called backpropagationBackpropagationReverse-mode autodiff for networks: the forward pass saves values, the backward pass chains derivatives from the loss to every weight..

The price is memory: the backward pass needs the values saved in the forward pass. Gradient checkpointing saves only some of them and recomputes the rest, trading compute for memory.

05

Trust, but check

Read

A hand-written backward pass can be subtly wrong and still train, badly. A gradient checkGradient checkCompare autodiff gradients with finite differences, (f(θ+h) − f(θ−h)) ÷ 2h, to catch a wrong backward pass. compares it with central differences:

∂f∂θi≈f(θ+hei)−f(θ−hei)2h.\frac{\partial f}{\partial \theta_i} \approx \frac{f(\theta + h e_i) - f(\theta - h e_i)}{2h}.

Use double precision, a small hh (around 10−610^{-6} times the parameter's scale) and a few random inputs. The relative error ∣gauto−gfd∣/max⁡(∣gauto∣,∣gfd∣)\lvert g_{\text{auto}} - g_{\text{fd}}\rvert / \max(\lvert g_{\text{auto}}\rvert, \lvert g_{\text{fd}}\rvert) should be tiny, near 10−810^{-8} or below. Errors near 10−210^{-2} mean a bug.

Python
import numpy as np

def f(t):                       # loss of a one-neuron model on one row
    x, y = 2.0, 1.0
    p = 1 / (1 + np.exp(-(t[0] * x + t[1])))
    return -(y * np.log(p) + (1 - y) * np.log(1 - p))

def grad(t):                    # hand-derived backward pass
    x, y = 2.0, 1.0
    p = 1 / (1 + np.exp(-(t[0] * x + t[1])))
    return np.array([(p - y) * x, p - y])

t, h = np.array([0.3, -0.1]), 1e-6
fd = np.array([(f(t + h * e) - f(t - h * e)) / (2 * h) for e in np.eye(2)])
print(np.max(np.abs(fd - grad(t)) / np.maximum(np.abs(fd), np.abs(grad(t)))))
R
f <- function(t) {               # loss of a one-neuron model on one row
  x <- 2; y <- 1
  p <- 1 / (1 + exp(-(t[1] * x + t[2])))
  -(y * log(p) + (1 - y) * log(1 - p))
}
grad <- function(t) {            # hand-derived backward pass
  x <- 2; y <- 1
  p <- 1 / (1 + exp(-(t[1] * x + t[2])))
  c((p - y) * x, p - y)
}
t <- c(0.3, -0.1); h <- 1e-6
fd <- sapply(1:2, function(i) { e <- replace(c(0, 0), i, 1); (f(t + h * e) - f(t - h * e)) / (2 * h) })
max(abs(fd - grad(t)) / pmax(abs(fd), abs(grad(t))))
06

Step through the backward pass

Explore

DExplorable · Backprop, one step at a time

How does the chain rule send a loss's gradient back to every weight?

h reaches the output twice: through v·h and through the skip connection. What should its gradient be?

How sure?
0

Each step processes one operation, from the loss back toward the inputs.

Activation

1.5
−0.5
0.8
−1.2
0.1
0.5
0.2

Gradient-check step ε

x₁1.50w₁0.80x₂−0.50w₂−1.20b0.10×1.20×0.60+1.80+ b1.90tanh0.96v0.50× v0.48+ h1.43y0.20− y1.23L = ²1.52∂ 1.000

Each box shows a value from the forward pass; the number under it is ∂L/∂(that value), filled in as the backward pass reaches it. A value used twice collects gradient from both uses.

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Press through the backward steps and watch each node pass its upstream gradient times its local derivative to its inputs. The value h is used twice, so it adds both shares. Then try each step size ε in the gradient check, and turn on the overwrite bug to see the check catch it.

07

See backprop train a network

Explore

Every training step in the playground runs a forward pass, a backward pass through each layer, and a gradient step.

DExplorable · Neural network playground

How do hidden units combine straight lines into curved boundaries?

Each hidden unit can draw one straight line. How accurate will this network be on new data?

0.70
How sure?

Data

2
1

Activation

0.50
500
0.000
0.10
120
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

Add a second hidden layer and watch training slow at first: each layer multiplies another Jacobian into the backward pass, and small factors compound.

08

Check: autodiff

Checkpoint

Check yourself

f(x,y)=(x+y) yf(x, y) = (x + y)\,y at x=3x = 3, y=2y = 2. What is ∂f/∂y\partial f/\partial y?

Show the answer

Answer: 7

f=xy+y2f = xy + y^2, so ∂f/∂y=x+2y=3+4=7\partial f/\partial y = x + 2y = 3 + 4 = 7. By the graph: the direct path gives a=5a = 5, the path through aa gives y=2y = 2, and they add.

Check yourself

A model has one scalar loss and ten million weights. Which mode of automatic differentiation gets the full gradient most cheaply?

Show the answer

Answer: a

Reverse mode's cost scales with the number of outputs (here one); forward mode's with the number of inputs (ten million).

Check yourself

Why does training a deep network need much more memory than running it on new data?

Show the answer

Answer: a

Prediction can discard each layer's activations as soon as the next layer has them. Training keeps them for the backward pass, unless checkpointing recomputes them.

Check yourself

Your gradient check reports a relative error around 0.03 on several weights. What does that suggest?

Show the answer

Answer: b

With double precision and a sensible hh, agreement is usually near 10−810^{-8}. A few percent points to a bug.

09

Recap

Recap
  • Autodiff records the computation as a graph and applies the chain rule node by node, exactly.
  • Reverse mode (backpropagation) gets one loss's gradient for every weight at about the cost of one pass, and pays in memory.
  • A central-difference gradient check in double precision catches wrong backward passes.

Concepts in this lesson