P1.C4 ended with a price tag. To find the slope of a loss with respect to each of weights by nudging, you evaluate the loss twice per weight: evaluations, and a model can have billions of weights. Yet every training step gets all those slopes for roughly the cost of a few evaluations of the loss. How?
The trick is to stop treating the program as one big function and look at how it is built. It is a sequence of tiny steps (add, multiply, take a sine), and each tiny step has a derivative you already know. The chain rule of P1.C3 joins them. This lesson draws that picture, the computational graph, and shows the two ways to run the chain rule over it.
A program drawn as a graph
Take the function . To compute it, a program does three small steps and names the results:
A computational graph draws each value as a node and draws an edge from a value to every step that uses it. The inputs and are nodes with nothing feeding them. Each other node is one simple operation applied to the nodes that feed it. Here the edges are , , , and .
Notice that has two outgoing edges: it is used in and again in . This is called a fan-out, and it needs care later.
The forward pass computes the values in an order where every node comes after the nodes that feed it. At , :
(Angles are in radians. Every number in this lesson was computed with code.)
Any calculation can be broken up like this, from this small function to a network with billions of operations. A neuron with a loss is also a graph. For a weight , bias , input and target , the steps are , then , then . Notice that is used twice in : another fan-out.
Each node knows one small derivative
Here is the key to the whole lesson. We never differentiate the whole function. Each node only needs its local derivative: how its output changes when one of its inputs is nudged, with everything else held fixed. That is a partial derivative (P1.C4) of a very simple operation, and you know them all:
- Add, : and .
- Multiply, : and (each input’s slope is the other input).
- Sine, : .
- Exponential, : .
- Square, : .
- Sigmoid, : .
- Divide, logarithm, power and the rest of the table of P1.C2 work the same way: one small rule each.
A local derivative is read at the forward values: the rule for multiply needs and , and the rule for sine needs . This is why the forward pass comes first, and why the values must be kept.
You have already met a chain of such nodes. In P1.C3 the sigmoid at was cut into four steps with local rates , , and , and multiplying them gave . That graph is a straight line: every node has one input and one output. Our is more interesting because its graph has branches that join, and fans out.
Reverse mode: one backward pass
We want and . Reverse mode answers both with one sweep, starting at the output and moving toward the inputs. At each node it keeps one number: the gradient at the node, written , meaning how much the final output changes per unit change of the node . The rule for a step is the chain rule of P1.C3:
For at , :
- Seed. .
- Through the multiply . The gradient at is . The gradient at is .
- Through the sine . Along this path, receives .
- Through the add . Along this path, receives , and receives .
Step 4 raised a question. The value received two gradients, from the path through and from the path through . What is the gradient at ? A nudge to moves along both paths, and the two effects add. So the gradients add:
This is the rule you met in the two-paths box of P1.C3: multiply along each path, add over the paths. Compare with the formula from the product rule: . The same two terms appear, one from each path. And .
Things to try with the graph widget:
- Press Step forward four times, and watch the blue values fill in: and , then , and . The orange numbers on the edges are the local derivatives; each appears when the node it points to has been computed.
- Press Step backward five times. At the third step has a gradient of marked with “…”, because it is not finished. At the fourth step the second path arrives and the two add up to . The last step gives . The check line then compares both results with central differences.
- Move the sliders. The steps stay where they are and every number updates. Set to 0. Then , and the gradient at is , so the path through sends nothing: , and comes from the path through alone.
- Press Reset, then switch to forward mode (steps already taken carry over between modes) and press Step forward to the end with the seed . Then change the seed to and compare. This is the subject of the next section.
Forward mode: carry the derivative along
There is another way to run the chain rule. Instead of going from the output back, go forward and carry a derivative along with every value. Choose one input to nudge, called the seed, and give it the derivative 1. Every other input gets 0. Then each node works out the derivative of its own value with respect to the seed, from the derivatives of its inputs.
Seed in our graph (at , ):
- has derivative , and has .
- : derivative .
- : derivative .
- : by the product rule, .
The answer is , the same number. But this one pass gave only the derivative with respect to the seeded input. For you seed and run the whole pass again, and you get .
So the two modes differ in what one pass buys you:
- Forward mode: one pass gives the derivative of every node with respect to one input. All derivatives of need one pass per input.
- Reverse mode: one pass gives the derivative of one output with respect to every node. All derivatives of need one pass per output.
With 2 inputs and 1 output, reverse mode needs 1 pass to forward mode’s 2. A reverse pass is a forward sweep plus a backward sweep, so for so few inputs it is a close call. The advantage becomes clear when is much larger than .
Go deeper Dual numbers: forward mode as a new kind of number
Forward mode can be written as arithmetic on pairs. A dual number is a pair (value, derivative), written , where is a symbol with . Multiplying out gives the product rule for free:
Sums add both parts, and . Evaluating any function at returns , so the derivative comes out as the second part. In Python:
import math
class Dual:
def __init__(self, val, dot):
self.val, self.dot = val, dot
def __add__(self, o):
return Dual(self.val + o.val, self.dot + o.dot)
def __mul__(self, o):
return Dual(self.val * o.val, self.dot * o.val + self.val * o.dot)
def sin(d):
return Dual(math.sin(d.val), math.cos(d.val) * d.dot)
x, y = Dual(1.0, 1.0), Dual(2.0, 0.0) # seed x
f = (x + y) * sin(x)
print(f.val, f.dot) # 2.5244 and 2.4624Changing the seed to Dual(1.0, 0.0) and Dual(2.0, 1.0) gives for . As a one-line check, gives , the slope .
Why reverse wins for machine learning
Suppose a function has inputs and outputs. All derivatives form the Jacobian (P1.C7). The two modes get it like this:
- Forward mode: passes, one per input.
- Reverse mode: passes, one per output.
- Central finite differences: evaluations, two per input (P1.C4).
A training loss is one number (so ) that depends on millions or billions of parameters (so is huge). Reverse mode needs one backward pass. Forward mode would need passes, one per parameter, which is no better in spirit than nudging each weight. This is the reason backpropagation is reverse mode, and why it is the standard method.
Things to try with the passes widget:
- A network loss ( weights, loss): reverse mode needs 1 pass, forward mode a million, and finite differences two million evaluations.
- Few inputs, many outputs (, ): now forward mode wins, with 3 passes against 1000. Think of a simulation with three settings that produces a thousand measurements.
- A square case (): a tie in the number of passes.
What one pass costs
Counting passes is only half the story: we also need the price of one pass. For reverse mode, a standard result of the automatic-differentiation literature is that the whole gradient (the forward evaluation plus the backward sweep) costs a small constant multiple of one evaluation of the function, and the multiple does not depend on the number of inputs. Lecture notes often quote a factor of about 5 as an upper estimate for the whole gradient, counted in arithmetic operations. For the large matrix multiplications that dominate a network, the backward sweep alone is often described as roughly twice the arithmetic of the forward pass. These are rules of thumb, not exact figures: they change with the operations used. The cell below counts the operations of a small graph to show that the ratio does not grow with .
So one gradient costs a few times the loss evaluation, while checking it by nudging costs evaluations. That is what P1.C4 promised, and why nudging is kept for gradient checking (P4.8) on small models.
What reverse mode costs: memory
Reverse mode is not free. The backward pass needs the forward values (the multiply rule needs and ), so they must be kept in memory from the moment they are computed until the backward pass uses them. For a deep network the stored values can take more memory than the weights themselves. Forward mode does not need to keep the whole history of values for a later sweep: it uses each value as it goes.
Go deeper Checkpointing: trading computation for memory
A way to cut the memory of reverse mode is to not store every value. Store only a few chosen values (checkpoints), and when the backward pass needs a missing one, recompute it from the nearest checkpoint. You pay with extra forward computation and save memory. In the scheme of Chen and colleagues (2016) for a network of layers, the memory grows like and the price is about one extra forward pass. The major libraries offer this as an option (for example, PyTorch has torch.utils.checkpoint). It is a trade, not a free lunch.
Go deeper The matrix view: why the order of multiplication matters
For vector-valued nodes, the local derivative of each node is a matrix, its Jacobian (P1.C7), and the chain rule multiplies the matrices. For three steps, the derivative of the output with respect to the input is , and matrix multiplication can be grouped in different orders with the same answer but a different cost.
- Forward mode multiplies from the right: it pushes a vector through, (a Jacobian-vector product). One pass gives one column of .
- Reverse mode multiplies from the left: it pulls a row vector back, (a vector-Jacobian product). One pass gives one row of .
A made-up size shows the difference: let be , be and be (one output). Grouping the products from the right (a matrix times a matrix first) costs about multiply-adds, about . Grouping from the left (a row vector times a matrix each time) costs , roughly 500 times less. Libraries do not normally write out the full Jacobians: they compute these products directly (though they can build a full Jacobian on request). P1.C11 gives the matrix rules for and friends.
Three ways to get a derivative
There are three ways to get the derivative of a function that a computer evaluates. Only one of them is used inside deep-learning libraries.
- Finite differences nudge the inputs and measure: (P1.C1). They need no knowledge of how is built, but they are approximate, they need a good , and they cost evaluations for inputs.
- Symbolic differentiation takes the formula of and writes a formula for the derivative, as in a computer algebra system. It is exact, but the formula can grow much larger than the program, a problem called expression swell.
- Automatic differentiation runs the program on numbers and applies the exact local rule of every operation, with the chain rule. It gives the derivative at a point, with no step size and no formula for the derivative.
Finite differences have two kinds of error
At , the exact value is . A central difference with is off by about , with by about , and with by about . Shrinking further makes it worse: at the error is about . Small means subtracting two almost equal numbers, and rounding then dominates (P1.C1). Automatic differentiation has no such trade: its error is the rounding of the few operations it performs, around here. It is therefore called exact up to floating-point rounding.
Expression swell
Take a short program that repeats one step: , starting from . Each step has 3 operations, so steps have . Now write the derivative of the result with respect to by the product rule, without naming any intermediate value or simplifying. For steps the program has 18 operations, but the written-out derivative has over a thousand arithmetic operators. The program reuses each value, and the formula repeats the same sub-expressions again and again. A computer algebra system can simplify and share sub-expressions, but in general this growth is a real cost. Automatic differentiation avoids it by never writing the formula: it only passes numbers.
How a library does it
A library like PyTorch or JAX does what the graph widget does, in code:
- Record while running. As the forward pass runs, every operation creates its result and remembers its inputs and what its backward rule needs (the forward values, such as and for a multiply). That record is the graph, sometimes called a tape.
- Walk it backward.
backward()puts a gradient of 1 at the output, visits the nodes in reverse order, and sends each node’s gradient, times its local derivative, to its inputs. Gradients that arrive at the same node are added. - Keep the answer on the leaves. The gradients of the parameters are stored in
.grad.
In PyTorch the graph is built dynamically: it is created anew during each forward pass, so ordinary Python if statements and loops work, and the derivative is that of the path actually taken. By default the graph’s saved values are freed after backward(). JAX takes another route: it traces a function and transforms it, and it offers both modes (jax.jvp for forward mode, jax.grad and jax.vjp for reverse mode).
Two consequences are worth knowing:
- Gradients accumulate. A backward pass adds to
.grad; it does not overwrite it. This follows from the add rule at a fan-out. So a training loop must reset the gradients before each step (optimizer.zero_grad(), P2.7), or the old ones pile up. P2.6 shows this in a real library, and the engine below reproduces it. - Only differentiable steps pass gradients. At a kink such as ReLU at 0, the library picks one value by convention (PyTorch gives 0 there). Rounding and comparisons have slope 0 wherever they are defined, so nothing flows back through them.
Real nodes hold whole tensors rather than single numbers, so a node’s local derivative is a matrix. The method is the same: P1.C11 gives the rules, and P4.10 builds a network with them.
Autodiff in three depths
Intuition
Break the program into tiny steps. Each step knows how a nudge to its inputs changes its output. Going backward from the output, ask of each value: “If I nudge you by one unit, how much does the output move?” The answer for a value is the sum, over the steps that use it, of the step’s local rate times the answer for that step. One sweep from the end answers the question for every value at once. That sweep is why training is affordable.
Math
Let the nodes be in forward order, with the output and each . Define the adjoint (the gradient at the node) . Reverse mode computes and, going down,
The sum over the children is the fan-out rule. Each edge is used once, so the backward pass does work proportional to the forward pass, which is the reason for the constant factor. Forward mode propagates for a seeded input . For with Jacobian , forward mode computes and reverse mode computes per pass.
Code
import torch
x = torch.tensor(1.0, requires_grad=True)
y = torch.tensor(2.0, requires_grad=True)
f = (x + y) * torch.sin(x) # the graph is recorded as this runs
f.backward() # one backward pass
print(x.grad, y.grad) # about 2.4624 and 0.8415This needs PyTorch, so it runs in Colab or on your machine, not in the browser here. Calling backward() on a new graph adds to x.grad again unless you reset it (x.grad.zero_(), or optimizer.zero_grad() in a training loop).
Try it: an autodiff engine in about 30 lines
PyTorch is not available in the browser, so here is the idea in plain Python. A Value holds a number, remembers its parents and the local derivative along each edge, and backward() visits the nodes in reverse topological order (parents before children, reversed). The cell then checks it against the hand computation and a central difference, shows a fan-out ( has slope ), runs the one-neuron squared error of P4.8, shows gradients accumulating, and counts the work for a larger graph. P4.9 builds a fuller engine in the same style.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Things to notice in the output: the engine, the hand formula and the central difference agree on and . The slope of is because receives two gradients of . The neuron gives and , the numbers of P4.8. The accumulating holds until it is reset. For and the number of backward updates is twice the number of forward operations, whatever is, while the finite-difference cost in operations grows like ( and ).
Challenge: change += to = in backward and rerun. Which results change, and why?
The second cell compares finite differences at many step sizes with the exact value from a hand-written backward pass. Predict where the error is smallest before you run it.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
The central error falls until is near (about ), then rises again as rounding takes over. The last digits can differ a little between computers.
Common mistakes
Check your understanding
For at , , what is ?
The value is used twice, so its gradient is the sum over its two paths: through the sine and through the sum , giving . The value keeps only the path through the sine. The value keeps only the path through the sum (it is ). The value is the value of , not a derivative.
A model has 1,000,000 parameters and a single scalar loss. What is the cheapest way to get the derivative of the loss with respect to every parameter, in number of passes?
Reverse mode needs one pass per output, and there is one output. Forward mode carries the derivative with respect to one seeded input, so it needs one pass per parameter, a million. Central finite differences need two evaluations per parameter. Reverse mode does not need a pass per parameter: that is its whole advantage.
A node feeds two later steps. The gradient arriving from the first is and from the second . What gradient does the node hold?
Effects through different paths add, so the gradients add: . The value multiplies them, which is how gradients combine along one path, not across paths. The value keeps only the larger one. The value averages them.
You compute a loss, call
backward(), then run a fresh forward pass for a second loss and callbackward()again, without resetting any gradient. What does the gradient stored on a parameter hold?A backward pass adds to the stored gradient of a parameter, following the same rule as a fan-out. That is why training loops reset the gradients before each step. The stored value is neither replaced nor averaged.
How does automatic differentiation differ from finite differences and from symbolic differentiation?
Autodiff passes numbers through the operations with their exact local rules, so it has no and writes no formula. It is not a small-step finite difference (those are approximate and need ), and it does not build a formula (that is symbolic differentiation). It differentiates the path that the program actually took, so loops and branches are fine.
Exercises
- Draw the graph of and run a backward pass at , . What are and ?
Show answer
The nodes are , and . The gradient at is 1, and both and receive (add rule). Then receives through and through , and these add: . And receives . So and , which match and . - Use a graph with two steps, and , to find at . Where is the fan-out?
Show answer
Forward: , . Backward: the gradient at is , and the last multiply sends to . The first multiply sends to along each of its two inputs, in all. The total at is . The fan-out is at , which is used three times. - A function has 3 inputs and 2 outputs. How many passes does each mode need for all six derivatives? What about 2 inputs and 5 outputs?
Show answer
3 inputs and 2 outputs: forward mode 3 passes, reverse mode 2 passes. 2 inputs and 5 outputs: forward mode 2, reverse mode 5. Reverse mode wins when there are fewer outputs than inputs, forward mode when there are fewer inputs than outputs. - A neuron is with , , . Find , and with a backward pass through and .
Show answer
Forward: , . The local derivative of the sigmoid is , so the gradient at is . The add rule passes to . The multiply rule sends to and to . So , and . - In the
Valueengine,backwardusedp.grad += .... What wouldt * tat give with=instead?Show answer
The multiply node has the same parent twice, and each edge sends . With=, the second assignment overwrites the first, sot.gradis instead of the correct . The+=is the fan-out rule. - A function has one input and 1000 outputs. Which mode would you use, and roughly how many passes?
Show answer
Forward mode: one pass, seeded at the single input, gives the derivative of every output. Reverse mode would need 1000 backward passes, one per output. - Evaluate with the dual number and read off the derivative.
Show answer
, since . The value is and the derivative is .
Next: P1.C11 gives the rules for nodes that hold whole vectors and matrices, such as , and P4.8 uses the backward pass on a full network. P4.9 builds a larger autograd engine from scratch, and P2.6 shows the same ideas in PyTorch.