Automatic Differentiation
Automatic differentiation (autodiff, AD) computes exact derivatives of a program, not of a formula, by applying the chain rule to each elementary operation as the program runs. It is neither symbolic algebra nor finite differences. This lesson compares the three approaches, then builds forward mode with dual numbers and reverse mode with a small Value class, the same idea that powers PyTorch and JAX.
Three ways to get a derivative
| Approach | How | Weakness |
|---|---|---|
| Symbolic (SymPy) | Rewrites the formula with differentiation rules | Needs a formula; expressions can grow huge; loops and ifs are awkward |
| Numeric (finite differences) | Truncation error for big , rounding error for small ; one extra run per input | |
| Automatic | Carries derivatives alongside values through every +, *, sin, … |
Needs operator overloading or a tracing framework |
The numeric approach has an annoying sweet spot. For at :
import math
f = lambda x: math.sin(x) * math.exp(x)
exact = (math.cos(1) + math.sin(1)) * math.e # product rule
print(f"exact f'(1) = {exact:.12f}")
for k in [1, 2, 4, 6, 8, 10, 12, 14]:
h = 10.0 ** -k
fd = (f(1 + h) - f(1)) / h
print(f"h = 1e-{k:<2} forward difference error {abs(fd - exact):.2e}")exact f'(1) = 3.756049227095
h = 1e-1 forward difference error 1.44e-01
h = 1e-2 forward difference error 1.47e-02
h = 1e-4 forward difference error 1.47e-04
h = 1e-6 forward difference error 1.47e-06
h = 1e-8 forward difference error 2.21e-08
h = 1e-10 forward difference error 4.22e-07
h = 1e-12 forward difference error 5.01e-04
h = 1e-14 forward difference error 1.87e-02
The error first shrinks with (less truncation), then grows again (subtracting two almost equal floats loses digits). The best you get is about 8 correct digits. Autodiff gives all 16.
Forward mode: dual numbers
Extend numbers with a symbol that satisfies (but ), and write a dual number as . Then
The part follows the sum rule, the product rule and the chain rule automatically. Evaluate any function at and read the derivative off the part.
import math
class Dual:
def __init__(self, val, der=0.0):
self.val, self.der = val, der
def __add__(self, o):
o = o if isinstance(o, Dual) else Dual(o)
return Dual(self.val + o.val, self.der + o.der)
__radd__ = __add__
def __mul__(self, o):
o = o if isinstance(o, Dual) else Dual(o)
return Dual(self.val * o.val, self.der * o.val + self.val * o.der)
__rmul__ = __mul__
def sin(d): return Dual(math.sin(d.val), math.cos(d.val) * d.der)
def exp(d): return Dual(math.exp(d.val), math.exp(d.val) * d.der)
x = Dual(1.0, 1.0) # x = 1, dx/dx = 1
y = sin(x) * exp(x)
print(f"f(1) = {y.val:.12f}")
print(f"f'(1) = {y.der:.12f}")
p = 3 * x * x + 2 * x + 5 # works on any code made of these operations
print("p(1) =", p.val, " p'(1) =", p.der)f(1) = 2.287355287179
f'(1) = 3.756049227095
p(1) = 10.0 p'(1) = 8.0
The derivative matches the exact value to the last printed digit. Forward mode costs about one extra multiplication per operation, but it computes the derivative with respect to one input per run. For a function of a million inputs you would need a million runs.
Reverse mode: record, then walk backwards
Reverse mode first runs the program and records a graph of operations (each node remembers its inputs and how to pass a gradient to them). Then it starts at the output with gradient 1 and walks the graph in reverse topological order, adding each node's contribution to its inputs' .grad. That is backpropagation for arbitrary code.
import math
class Value:
def __init__(self, data, parents=(), op=""):
self.data, self.grad = data, 0.0
self.parents, self.op = parents, op
self.backward_step = lambda: None
def __add__(self, other):
out = Value(self.data + other.data, (self, other), "+")
def step():
self.grad += out.grad
other.grad += out.grad
out.backward_step = step
return out
def __mul__(self, other):
out = Value(self.data * other.data, (self, other), "*")
def step():
self.grad += other.data * out.grad
other.grad += self.data * out.grad
out.backward_step = step
return out
def tanh(self):
th = math.tanh(self.data)
out = Value(th, (self,), "tanh")
def step():
self.grad += (1 - th * th) * out.grad
out.backward_step = step
return out
def backward(self):
order, seen = [], set()
def visit(v):
if id(v) not in seen:
seen.add(id(v))
for p in v.parents:
visit(p)
order.append(v)
visit(self)
self.grad = 1.0
for v in reversed(order):
v.backward_step()
x, y = Value(0.5), Value(-1.5)
f = (x * y + x).tanh() # f = tanh(x·y + x)
f.backward()
print(f"f = {f.data:.6f} df/dx = {x.grad:.6f} df/dy = {y.grad:.6f}")f = -0.244919 df/dx = -0.470007 df/dy = 0.470007
One backward pass gave the derivative with respect to both inputs. Note the +=: is used twice (in and in ), and its two contributions add up, exactly the multivariable chain rule. Let's confirm with SymPy:
import sympy as sp
x, y = sp.symbols("x y")
f = sp.tanh(x * y + x)
vals = {x: 0.5, y: -1.5}
print("df/dx =", sp.diff(f, x))
print(f"df/dx = {float(sp.diff(f, x).subs(vals)):.6f} df/dy = {float(sp.diff(f, y).subs(vals)):.6f}")df/dx = (1 - tanh(x*y + x)**2)*(y + 1)
df/dx = -0.470007 df/dy = 0.470007
Forward or reverse?
| Forward mode | Reverse mode | |
|---|---|---|
| One pass gives | derivatives of all outputs w.r.t. one input | derivatives of one output w.r.t. all inputs |
| Best when | few inputs, many outputs (sensitivities, Jacobian columns) | many inputs, one output: a loss with millions of weights |
| Memory | small, nothing stored | stores the whole graph of the forward pass |
| Implementation | dual numbers, operator overloading | tape or graph + topological sort |
Training a neural network is the extreme "many inputs, one output" case, which is why deep learning uses reverse mode. The full Jacobian of a function costs forward passes or reverse passes.
In software
- PyTorch builds the graph as your Python code runs ("define by run");
loss.backward()is thebackward()above, with each tensor operation knowing its local derivative. - JAX offers both modes:
jax.jvp(forward) andjax.vjp/jax.grad(reverse), and composes them for Hessians. - Beyond ML: physics engines and robotics use AD for sensitivities and controller tuning; finance uses "adjoint AD" (reverse mode) to compute the price sensitivities ("Greeks") of a portfolio in one pass; differentiable renderers optimise 3D scenes from images.
Build a complete engine yourself, with more operations and a training loop, in the mini project.
Exercises
Exercise 1: Dual numbers by hand
Compute using . What derivative does it give?
Answer
, so at is 12.
Solution
Exercise 2: Division for duals
Derive the rule for . Hint: multiply top and bottom by .
Answer
, the quotient rule.
Solution
With , this is .
Exercise 3: Reverse mode by hand
For at , , draw the graph (, ) and push the gradient backwards to get and .
Answer
, .
Solution
forward: u = 5, f = 15
f.grad = 1
f = u·x: u.grad += x·1 = 3, x.grad += u·1 = 5
u = x+y: x.grad += u.grad = 3 → x.grad = 8, y.grad += 3 → y.grad = 3
check: f = x² + xy, ∂f/∂x = 2x + y = 8, ∂f/∂y = x = 3 ✓Exercise 4: Add exp to forward mode
Using the Dual class idea, compute the derivative of at and compare with the exact .
Answer
.
Solution
import math
class Dual:
def __init__(self, val, der=0.0):
self.val, self.der = val, der
def __mul__(self, o):
return Dual(self.val * o.val, self.der * o.val + self.val * o.der)
def exp(d):
return Dual(math.exp(d.val), math.exp(d.val) * d.der) # chain rule
x = Dual(0.5, 1.0)
g = exp(x * x)
print(f"dual {g.der:.6f}")
print(f"exact {2 * 0.5 * math.exp(0.25):.6f}")dual 1.284025
exact 1.284025
Test yourself
What is with ?
- 9
A loss depends on 10 million weights. Which mode gives all gradients in about one extra pass?
- Forward mode
- Reverse mode
- Finite differences
- Symbolic differentiation
Why does the reverse-mode Value class use grad += instead of grad =?
- For speed
- A value used in several places gets one contribution per use, and they must be summed
- To avoid negative gradients
- Python requires it