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.
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
A program as a graph
ReadWrite as two small steps: , then . 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.
Forward, then backward
ReadTake , .
Forward: , . Keep both.
Backward: start with and walk the graph in reverse, multiplying by each node's local derivative.
- At : and the direct .
- At : pass on to and to .
- is used twice, so its two contributions add: .
Result: . Check against : .
Predict
PredictPredict first
A value feeds two later nodes. During the backward pass, how do the two derivative contributions that reach it combine?
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.
Why reverse mode wins for training
ReadForward 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.
Trust, but check
ReadA 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:
Use double precision, a small (around times the parameter's scale) and a few random inputs. The relative error should be tiny, near or below. Errors near mean a bug.
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)))))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))))Step through the backward pass
ExploreDExplorable · 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?
Each step processes one operation, from the loss back toward the inputs.
Activation
Gradient-check step ε
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 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.
See backprop train a network
ExploreEvery 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?
Data
Activation
Commit your prediction above to see the result
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.
Check: autodiff
CheckpointCheck yourself
at , . What is ?
Show the answer
Answer: 7
, so . By the graph: the direct path gives , the path through gives , 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 , agreement is usually near . A few percent points to a bug.
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