Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsCalculus

Computational graphs and automatic differentiation

P1.C1045 min●●○ IntermediateReviewed Nov 30, 2026

Why this matters for machine learning

Training a model means finding the slope of one loss with respect to millions of parameters, at every step. Nudging each parameter would cost millions of loss evaluations. Automatic differentiation in reverse mode gets all the slopes for a small constant multiple of the cost of one evaluation, and it is the engine inside every deep-learning library.

  • Backpropagation is reverse-mode automatic differentiation applied to a neural network: a forward pass stores the values, a backward pass multiplies local derivatives from the loss to the weights. (P4.8: Backpropagation: step by step with numbers)
  • PyTorch's requires_grad and .backward() build a graph during the forward pass and run a backward pass over it. (P2.6: PyTorch tensors and autograd, coming soon)
  • Building a small autograd engine yourself, a Value class with a topological sort and a backward(), is the next step after the version of about 30 lines in this lesson. (P4.9: Build an autograd engine from scratch, coming soon)
  • Gradient descent needs the gradient of the loss at every step, so the cost of getting it decides how big a model can be trained. (P1.F3: Gradient descent)

Before this: The chain rule, Partial derivatives

After this lesson you can

  • Draw a computational graph for a small expression, compute its forward pass, and write down the local derivative of each node
  • Run a backward pass by hand, multiplying local derivatives by the gradient arriving from above and adding the contributions when a value is used more than once
  • Run forward mode on the same graph, and say how many passes each mode needs for nn inputs and mm outputs
  • Explain why reverse mode is the right choice for training (one loss, many parameters), what it costs in memory, and when forward mode is better
  • Compare automatic differentiation with finite differences and with symbolic differentiation, and read a reverse-mode engine of about 30 lines

P1.C4 ended with a price tag. To find the slope of a loss with respect to each of nn weights by nudging, you evaluate the loss twice per weight: 2n2n 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 f(x,y)=(x+y)sin⁡xf(x,y)=(x+y)\sin x. To compute it, a program does three small steps and names the results:

a=x+y,s=sin⁡x,f=a⋅s.\begin{aligned} a&=x+y,\\ s&=\sin x,\\ f&=a\cdot s. \end{aligned}

A computational graph draws each value as a node and draws an edge from a value to every step that uses it. The inputs xx and yy are nodes with nothing feeding them. Each other node is one simple operation applied to the nodes that feed it. Here the edges are x→ax\to a, y→ay\to a, x→sx\to s, a→fa\to f and s→fs\to f.

Notice that xx has two outgoing edges: it is used in aa and again in ss. 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 x=1x=1, y=2y=2:

a=1+2=3,s=sin⁡1=0.8415,f=3×0.8415=2.5244.\begin{aligned} a&=1+2=3,\\ s&=\sin 1=0.8415,\\ f&=3\times0.8415=2.5244. \end{aligned}

(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 ww, bias bb, input xx and target tt, the steps are z=wx+bz=wx+b, then e=z−te=z-t, then L=e⋅eL=e\cdot e. Notice that ee is used twice in e⋅ee\cdot e: 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, a=x+ya=x+y: ∂a∂x=1\frac{\partial a}{\partial x}=1 and ∂a∂y=1\frac{\partial a}{\partial y}=1.
  • Multiply, f=a⋅sf=a\cdot s: ∂f∂a=s\frac{\partial f}{\partial a}=s and ∂f∂s=a\frac{\partial f}{\partial s}=a (each input’s slope is the other input).
  • Sine, s=sin⁡xs=\sin x: ∂s∂x=cos⁡x\frac{\partial s}{\partial x}=\cos x.
  • Exponential, v=euv=\mathrm{e}^{u}: ∂v∂u=eu\frac{\partial v}{\partial u}=\mathrm{e}^{u}.
  • Square, q=u2q=u^2: ∂q∂u=2u\frac{\partial q}{\partial u}=2u.
  • Sigmoid, p=σ(z)p=\sigma(z): ∂p∂z=p(1−p)\frac{\partial p}{\partial z}=p(1-p).
  • 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 aa and ss, and the rule for sine needs xx. 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 z=2z=2 was cut into four steps with local rates −1-1, 0.13530.1353, 11 and −0.7758-0.7758, and multiplying them gave σ′(2)=0.1050\sigma'(2)=0.1050. That graph is a straight line: every node has one input and one output. Our ff is more interesting because its graph has branches that join, and xx fans out.

Reverse mode: one backward pass

We want ∂f∂x\frac{\partial f}{\partial x} and ∂f∂y\frac{\partial f}{\partial y}. 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 ∂f∂v\frac{\partial f}{\partial v}, meaning how much the final output ff changes per unit change of the node vv. The rule for a step is the chain rule of P1.C3:

gradient sent to an input=(gradient arriving at the node)×(local derivative of that edge).\begin{aligned} &\text{gradient sent to an input}\\ &=\bigl(\text{gradient arriving at the node}\bigr)\\ &\quad\times\bigl(\text{local derivative of that edge}\bigr). \end{aligned}

For f=(x+y)sin⁡xf=(x+y)\sin x at x=1x=1, y=2y=2:

  1. Seed. ∂f∂f=1\frac{\partial f}{\partial f}=1.
  2. Through the multiply f=a⋅sf=a\cdot s. The gradient at aa is 1×s=0.84151\times s=0.8415. The gradient at ss is 1×a=31\times a=3.
  3. Through the sine s=sin⁡xs=\sin x. Along this path, xx receives 3×cos⁡1=3×0.5403=1.62093\times\cos 1=3\times0.5403=1.6209.
  4. Through the add a=x+ya=x+y. Along this path, xx receives 0.8415×1=0.84150.8415\times1=0.8415, and yy receives 0.8415×1=0.84150.8415\times1=0.8415.

Step 4 raised a question. The value xx received two gradients, 1.62091.6209 from the path through ss and 0.84150.8415 from the path through aa. What is the gradient at xx? A nudge to xx moves ff along both paths, and the two effects add. So the gradients add:

∂f∂x=1.6209+0.8415=2.4624,∂f∂y=0.8415.\begin{aligned} \frac{\partial f}{\partial x}&=1.6209+0.8415=2.4624,\\ \frac{\partial f}{\partial y}&=0.8415. \end{aligned}

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: ∂f∂x=sin⁡x+(x+y)cos⁡x=0.8415+3×0.5403=2.4624\frac{\partial f}{\partial x}=\sin x+(x+y)\cos x=0.8415+3\times0.5403=2.4624. The same two terms appear, one from each path. And ∂f∂y=sin⁡x=0.8415\frac{\partial f}{\partial y}=\sin x=0.8415.

Computational graph of f(x, y) = (x + y) · sin x

used twice:gradients addx (input)·y (input)·a = x + y·s = sin x·f = a · s·

Step backward unlocks when the forward pass is finished: the backward pass needs the stored values.

Nothing is computed yet. The graph has two inputs, x and y, and three operations. Press Step forward to compute the values one node at a time.

Passes for the derivatives of f with respect to all 2 inputs: 1 backward pass (f is a single output) after the forward pass. Forward mode would need 2, one per input.

Blue numbers are values going forward. Orange numbers are derivatives: in reverse mode, ∂f/∂node (how much f changes per unit change of that node), found going backward; in forward mode, ∂node/∂seed, carried forward. The number on each edge is the local derivative of the node it points to with respect to the node it leaves; the arrows show the forward direction.

Computational graph of f(x, y) = (x + y) sin x. Blue numbers are values computed going forward, one node per press of Step forward. After the forward pass, Step backward fills in orange gradients from the output, using the orange local derivative written on each edge. The input x is used twice, so its gradient is a sum. A switch moves to forward mode, which carries a derivative along with each value for one chosen input. The check at the end compares the result with central differences, which use no rules.

Things to try with the graph widget:

  1. Press Step forward four times, and watch the blue values fill in: xx and yy, then a=3a=3, s=0.8415s=0.8415 and f=2.5244f=2.5244. The orange numbers on the edges are the local derivatives; each appears when the node it points to has been computed.
  2. Press Step backward five times. At the third step xx has a gradient of 1.62091.6209 marked with “…”, because it is not finished. At the fourth step the second path arrives and the two add up to 2.46242.4624. The last step gives ∂f∂y=0.8415\frac{\partial f}{\partial y}=0.8415. The check line then compares both results with central differences.
  3. Move the sliders. The steps stay where they are and every number updates. Set xx to 0. Then s=0s=0, and the gradient at aa is 00, so the path through aa sends nothing: ∂f∂y=0\frac{\partial f}{\partial y}=0, and ∂f∂x=y\frac{\partial f}{\partial x}=y comes from the path through ss alone.
  4. Press Reset, then switch to forward mode (steps already taken carry over between modes) and press Step forward to the end with the seed xx. Then change the seed to yy 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 xx in our graph (at x=1x=1, y=2y=2):

  • xx has derivative 11, and yy has 00.
  • a=x+ya=x+y: derivative 1+0=11+0=1.
  • s=sin⁡xs=\sin x: derivative cos⁡x×1=0.5403\cos x\times1=0.5403.
  • f=a⋅sf=a\cdot s: by the product rule, (derivative of a)⋅s+a⋅(derivative of s)=1×0.8415+3×0.5403=2.4624(\text{derivative of }a)\cdot s+a\cdot(\text{derivative of }s)=1\times0.8415+3\times0.5403=2.4624.

The answer is ∂f∂x=2.4624\frac{\partial f}{\partial x}=2.4624, the same number. But this one pass gave only the derivative with respect to the seeded input. For ∂f∂y\frac{\partial f}{\partial y} you seed yy and run the whole pass again, and you get 0.84150.8415.

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 ff need one pass per input.
  • Reverse mode: one pass gives the derivative of one output with respect to every node. All derivatives of ff 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 nn is much larger than mm.

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 a+bεa+b\varepsilon, where ε\varepsilon is a symbol with ε2=0\varepsilon^2=0. Multiplying out gives the product rule for free:

(a+bε)(c+dε)=ac+(ad+bc)ε.\begin{aligned} (a+b\varepsilon)(c+d\varepsilon) \\ {}=ac+(ad+bc)\varepsilon. \end{aligned}

Sums add both parts, and sin⁡(a+bε)=sin⁡a+(cos⁡a) b ε\sin(a+b\varepsilon)=\sin a+(\cos a)\,b\,\varepsilon. Evaluating any function at x+εx+\varepsilon returns f(x)+f′(x)εf(x)+f'(x)\varepsilon, 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.4624

Changing the seed to Dual(1.0, 0.0) and Dual(2.0, 1.0) gives 0.84150.8415 for ∂f∂y\frac{\partial f}{\partial y}. As a one-line check, t=3+εt=3+\varepsilon gives t⋅t=9+6εt\cdot t=9+6\varepsilon, the slope 2t=62t=6.

Why reverse wins for machine learning

Suppose a function has nn inputs and mm outputs. All n×mn\times m derivatives form the Jacobian (P1.C7). The two modes get it like this:

  • Forward mode: nn passes, one per input.
  • Reverse mode: mm passes, one per output.
  • Central finite differences: 2n2n evaluations, two per input (P1.C4).

A training loss is one number (so m=1m=1) that depends on millions or billions of parameters (so nn is huge). Reverse mode needs one backward pass. Forward mode would need nn 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.

Passes needed for every derivative

Forward mode: one pass per input 1,000,000
Reverse mode: one pass per output 1
Central finite differences: two evaluations per input 2,000,000

Reverse mode needs fewer passes: 1 against 1,000,000. There are fewer outputs than inputs, which is the usual situation when training a model. A reverse pass is a forward sweep plus a backward sweep, so for small n it is a close call; the advantage is clear when n is much larger than m.

Each pass of forward or reverse mode costs a small constant multiple of one evaluation of the function (the multiples are not identical for the two modes, so a close call can go either way). The bars use a log scale: every tenfold increase in the number of passes adds the same length, so a million passes and one pass can both be drawn. The rows count passes to get all n × m derivatives, the full Jacobian (P1.C7).

Passes needed for every derivative of a function with n inputs and m outputs: n for forward mode, m for reverse mode, and 2n evaluations for central finite differences. The sliders go from 1 to ten million. The bars use a log scale. The status line says which mode needs fewer passes.

Things to try with the passes widget:

  1. A network loss (n=1,000,000n=1{,}000{,}000 weights, m=1m=1 loss): reverse mode needs 1 pass, forward mode a million, and finite differences two million evaluations.
  2. Few inputs, many outputs (n=3n=3, m=1000m=1000): now forward mode wins, with 3 passes against 1000. Think of a simulation with three settings that produces a thousand measurements.
  3. A square case (n=m=1000n=m=1000): 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 nn.

So one gradient costs a few times the loss evaluation, while checking it by nudging costs 2n2n 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 aa and ss), 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 nn layers, the memory grows like n\sqrt{n} 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 J=J3J2J1\mathbf{J}=\mathbf{J}_3\mathbf{J}_2\mathbf{J}_1, 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, Jv\mathbf{J}\mathbf{v} (a Jacobian-vector product). One pass gives one column of J\mathbf{J}.
  • Reverse mode multiplies from the left: it pulls a row vector back, v⊤J\mathbf{v}^\top\mathbf{J} (a vector-Jacobian product). One pass gives one row of J\mathbf{J}.

A made-up size shows the difference: let J1\mathbf{J}_1 be 1000×10001000\times1000, J2\mathbf{J}_2 be 1000×10001000\times1000 and J3\mathbf{J}_3 be 1×10001\times1000 (one output). Grouping the products from the right (a matrix times a matrix first) costs about 1000⋅1000⋅1000+1000⋅1000=1.001×1091000\cdot1000\cdot1000+1000\cdot1000=1.001\times10^{9} multiply-adds, about 10910^9. Grouping from the left (a row vector times a matrix each time) costs 1⋅1000⋅1000+1⋅1000⋅1000=2×1061\cdot1000\cdot1000+1\cdot1000\cdot1000=2\times10^{6}, 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 Wx\mathbf{W}\mathbf{x} 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: f(x+h)−f(x−h)2h\frac{f(x+h)-f(x-h)}{2h} (P1.C1). They need no knowledge of how ff is built, but they are approximate, they need a good hh, and they cost 2n2n evaluations for nn inputs.
  • Symbolic differentiation takes the formula of ff 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 x=1x=1, y=2y=2 the exact value is ∂f∂x=2.46238\frac{\partial f}{\partial x}=2.46238. A central difference with h=10−2h=10^{-2} is off by about 7×10−57\times10^{-5}, with h=10−5h=10^{-5} by about 5×10−115\times10^{-11}, and with h=10−8h=10^{-8} by about 8×10−108\times10^{-10}. Shrinking hh further makes it worse: at h=10−12h=10^{-12} the error is about 10−410^{-4}. Small hh 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 10−1610^{-16} here. It is therefore called exact up to floating-point rounding.

Expression swell

Take a short program that repeats one step: v←4v(1−v)v\leftarrow4v(1-v), starting from v=xv=x. Each step has 3 operations, so kk steps have 3k3k. Now write the derivative of the result with respect to xx by the product rule, without naming any intermediate value or simplifying. For k=6k=6 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:

  1. 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 aa and ss for a multiply). That record is the graph, sometimes called a tape.
  2. 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.
  3. 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 v1,…,vNv_1,\dots,v_N in forward order, with vN=fv_N=f the output and each vj=ϕj(its parents)v_j=\phi_j(\text{its parents}). Define the adjoint (the gradient at the node) vˉj=∂f∂vj\bar v_j=\frac{\partial f}{\partial v_j}. Reverse mode computes vˉN=1\bar v_N=1 and, going down,

vˉi=∑j: vi is a parent of vjvˉj ∂vj∂vi.\bar v_i=\sum_{j:\ v_i\text{ is a parent of }v_j}\bar v_j\,\frac{\partial v_j}{\partial v_i}.

The sum over the children jj 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 v˙j=∂vj∂xk=∑i∂vj∂viv˙i\dot v_j=\frac{\partial v_j}{\partial x_k}=\sum_i\frac{\partial v_j}{\partial v_i}\dot v_i for a seeded input xkx_k. For f:Rn→Rm\mathbf{f}:\mathbb{R}^n\to\mathbb{R}^m with Jacobian J\mathbf{J}, forward mode computes Jv\mathbf{J}\mathbf{v} and reverse mode computes u⊤J\mathbf{u}^\top\mathbf{J} 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.8415

This 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 (t⋅tt\cdot t has slope 2t2t), 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.

Try it: a reverse-mode autodiff engine

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 2.4623782.462378 and 0.8414710.841471. The slope of t⋅tt\cdot t is 66 because tt receives two gradients of 33. The neuron gives −4-4 and −2-2, the numbers of P4.8. The accumulating uu holds 7=4+37=4+3 until it is reset. For n=10n=10 and n=100n=100 the number of backward updates is twice the number of forward operations, whatever nn is, while the finite-difference cost in operations grows like n2n^2 (400400 and 40,00040{,}000).

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.

Try it: the error of a finite difference against the backward pass

Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).

The central error falls until hh is near 10−510^{-5} (about 5×10−115\times10^{-11}), then rises again as rounding takes over. The last digits can differ a little between computers.

Common mistakes

Check your understanding

  1. For f(x,y)=(x+y)sin⁡xf(x,y)=(x+y)\sin x at x=1x=1, y=2y=2, what is ∂f∂x\frac{\partial f}{\partial x}?

  2. 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?

  3. A node feeds two later steps. The gradient arriving from the first is 0.80.8 and from the second 1.51.5. What gradient does the node hold?

  4. You compute a loss, call backward(), then run a fresh forward pass for a second loss and call backward() again, without resetting any gradient. What does the gradient stored on a parameter hold?

  5. How does automatic differentiation differ from finite differences and from symbolic differentiation?

Exercises

  1. Draw the graph of g(x,y)=xy+sin⁡xg(x,y)=xy+\sin x and run a backward pass at x=0x=0, y=3y=3. What are ∂g∂x\frac{\partial g}{\partial x} and ∂g∂y\frac{\partial g}{\partial y}?
    Show answerThe nodes are p=xy=0p=xy=0, s=sin⁡x=0s=\sin x=0 and g=p+s=0g=p+s=0. The gradient at gg is 1, and both pp and ss receive 1×1=11\times1=1 (add rule). Then xx receives 1×y=31\times y=3 through pp and 1×cos⁡0=11\times\cos0=1 through ss, and these add: 44. And yy receives 1×x=01\times x=0. So ∂g∂x=4\frac{\partial g}{\partial x}=4 and ∂g∂y=0\frac{\partial g}{\partial y}=0, which match y+cos⁡xy+\cos x and xx.
  2. Use a graph with two steps, u=x⋅xu=x\cdot x and f=u⋅xf=u\cdot x, to find ddxx3\frac{d}{dx}x^3 at x=2x=2. Where is the fan-out?
    Show answerForward: u=4u=4, f=8f=8. Backward: the gradient at uu is 1×x=21\times x=2, and the last multiply sends 1×u=41\times u=4 to xx. The first multiply sends 2×x=42\times x=4 to xx along each of its two inputs, 88 in all. The total at xx is 4+8=12=3x24+8=12=3x^2. The fan-out is at xx, which is used three times.
  3. 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 answer3 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.
  4. A neuron is p=σ(wx+b)p=\sigma(wx+b) with x=2x=2, w=0.5w=0.5, b=−1b=-1. Find ∂p∂w\frac{\partial p}{\partial w}, ∂p∂b\frac{\partial p}{\partial b} and ∂p∂x\frac{\partial p}{\partial x} with a backward pass through z=wx+bz=wx+b and p=σ(z)p=\sigma(z).
    Show answerForward: z=0z=0, p=0.5p=0.5. The local derivative of the sigmoid is p(1−p)=0.25p(1-p)=0.25, so the gradient at zz is 0.250.25. The add rule passes 0.250.25 to bb. The multiply rule sends 0.25×x=0.50.25\times x=0.5 to ww and 0.25×w=0.1250.25\times w=0.125 to xx. So ∂p∂w=0.5\frac{\partial p}{\partial w}=0.5, ∂p∂b=0.25\frac{\partial p}{\partial b}=0.25 and ∂p∂x=0.125\frac{\partial p}{\partial x}=0.125.
  5. In the Value engine, backward used p.grad += .... What would t * t at t=3t=3 give with = instead?
    Show answerThe multiply node has the same parent twice, and each edge sends 3×1=33\times1=3. With =, the second assignment overwrites the first, so t.grad is 33 instead of the correct 66. The += is the fan-out rule.
  6. A function has one input and 1000 outputs. Which mode would you use, and roughly how many passes?
    Show answerForward mode: one pass, seeded at the single input, gives the derivative of every output. Reverse mode would need 1000 backward passes, one per output.
  7. Evaluate f=x⋅xf=x\cdot x with the dual number x=3+εx=3+\varepsilon and read off the derivative.
    Show answer(3+ε)(3+ε)=9+6ε+ε2=9+6ε(3+\varepsilon)(3+\varepsilon)=9+6\varepsilon+\varepsilon^2=9+6\varepsilon, since ε2=0\varepsilon^2=0. The value is 99 and the derivative is 6=2x6=2x.

Next: P1.C11 gives the rules for nodes that hold whole vectors and matrices, such as Wx\mathbf{W}\mathbf{x}, 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.

Key takeaways

  • A computational graph has one node per simple operation and one edge per value passed on. The forward pass computes the values node by node. For f(x,y)=(x+y)sin⁡xf(x,y)=(x+y)\sin x at x=1x=1, y=2y=2: a=x+y=3a=x+y=3, s=sin⁡x=0.8415s=\sin x=0.8415, f=a⋅s=2.5244f=a\cdot s=2.5244.
  • Each node knows only its local derivative: 11 for an addition, the other factor for a multiplication, cos⁡x\cos x for sin⁡x\sin x, ex\mathrm{e}^{x} for ex\mathrm{e}^{x}, 2x2x for x2x^2, σ(1−σ)\sigma(1-\sigma) for the sigmoid. The chain rule combines them: multiply along a path, add over the paths.
  • Reverse mode starts at the output with gradient 11 and goes backward, multiplying each local derivative by the gradient arriving from above. A value used twice receives two gradients, and they add to give ∂f∂x=2.4624\frac{\partial f}{\partial x}=2.4624 here (from 1.62091.6209 and 0.84150.8415). One backward pass gives the derivative with respect to every input.
  • Forward mode carries a derivative along with each value, for one seeded input at a time. For nn inputs and mm outputs, forward mode needs nn passes and reverse mode needs mm passes for all the derivatives. Training has one scalar loss and millions of parameters, so reverse mode wins. Forward mode wins when there are few inputs and many outputs.
  • Each pass costs a small constant multiple of one evaluation of the function, however many inputs there are. Central finite differences need two evaluations per input. The price of reverse mode is memory: the forward values must be kept until the backward pass uses them. Checkpointing trades extra computation for less memory.
  • Automatic differentiation is exact up to floating-point rounding: there is no step size hh to tune, unlike a finite difference. It is not symbolic differentiation either: no formula for the derivative is built, so there is no expression swell.
  • A library records the graph while the forward pass runs. Each operation stores what its backward rule needs, and backward() walks the graph in reverse. Gradients on leaf values accumulate across backward() calls, which is why training loops reset them (zero_grad, P2.7).
Found a mistake? Tell us