Automatic Differentiation: Forward and Reverse Mode
Automatic differentiation (autodiff) computes exact derivatives of a program by applying the chain rule to each elementary operation it executes. It is neither symbolic differentiation (no formula blow-up) nor finite differences (no truncation error). It comes in two modes that traverse the chain rule in opposite directions, and choosing between them is a matter of counting inputs and outputs. Background: Automatic Differentiation.
Two ways to multiply Jacobians
A program from to has Jacobian . The product can be evaluated right-to-left or left-to-right:
- Forward mode pushes a tangent vector through: , a Jacobian-vector product (JVP). One pass gives one column-combination; the full Jacobian needs passes.
- Reverse mode pulls a cotangent vector back: , a vector-Jacobian product (VJP). One pass gives one row-combination; the full Jacobian needs passes.
A loss function has output and in the millions or billions, so reverse mode (backpropagation) wins by a factor of . Forward mode wins when there are few inputs and many outputs.
Forward mode with dual numbers
Forward mode can be implemented by dual numbers with . Then : evaluating the program on a dual number carries the derivative along.
import math
class Dual:
def __init__(self, v, d=0.0): self.v, self.d = v, d
def __add__(s, o): o = o if isinstance(o, Dual) else Dual(o); return Dual(s.v + o.v, s.d + o.d)
__radd__ = __add__
def __mul__(s, o): o = o if isinstance(o, Dual) else Dual(o); return Dual(s.v * o.v, s.d * o.v + s.v * o.d)
__rmul__ = __mul__
def sin(x): return Dual(math.sin(x.v), math.cos(x.v) * x.d)
def exp(x): return Dual(math.exp(x.v), math.exp(x.v) * x.d)
f = lambda x: x * sin(x) + exp(x * 0.5)
x = Dual(1.3, 1.0) # seed: dx/dx = 1
out = f(x)
exact = math.sin(1.3) + 1.3 * math.cos(1.3) + 0.5 * math.exp(0.65)
print(f"f(1.3) = {out.v:.6f}, f'(1.3) by dual numbers = {out.d:.6f}, by hand = {exact:.6f}")f(1.3) = 3.168166, f'(1.3) by dual numbers = 2.269077, by hand = 2.269077
Reverse mode: record, then sweep back
Reverse mode first runs the program forward, recording every operation and its inputs on a tape, then sweeps the tape backward accumulating adjoints . Its cost is a small constant (typically 2 to 4) times the forward pass, but it must store the intermediate values, which is why training uses more memory than inference. You build a reverse-mode engine in the next lesson, Building a Tiny Autodiff Engine.
Counting the cost
import numpy as np
rng = np.random.default_rng(0)
n, m = 200, 3
A = rng.normal(size=(m, n))
f = lambda x: np.tanh(A @ x) # R^200 -> R^3
x = rng.normal(size=n)
s = 1 - np.tanh(A @ x)**2
J_exact = s[:, None] * A
jvp = lambda v: s * (A @ v) # forward mode: one column combination per pass
vjp = lambda u: (u * s) @ A # reverse mode: one row per pass
J_fwd = np.stack([jvp(e) for e in np.eye(n)], axis=1)
J_rev = np.stack([vjp(e) for e in np.eye(m)])
print("forward-mode passes:", n, " reverse-mode passes:", m)
print("both match:", np.allclose(J_fwd, J_exact), np.allclose(J_rev, J_exact))forward-mode passes: 200 reverse-mode passes: 3
both match: True True
Mixing modes
Hessian-vector products, needed for curvature (Curvature), are computed as forward-over-reverse: a JVP of the gradient function. It costs a few gradient evaluations and never forms the Hessian.
In software
- JAX exposes both modes directly:
jax.jvp,jax.vjp,jax.jacfwd,jax.jacrev, andjax.grad(reverse mode for scalar outputs). - PyTorch is reverse mode by default (
backward,torch.autograd.grad);torch.func.jvpandtorch.func.jacfwdadd forward mode. - Finite differences remain useful only to test autodiff code.
Exercises
Exercise 1: Choose the mode
Which mode is cheaper for (a) the gradient of a scalar loss with parameters, and (b) the derivatives of 1000 outputs of a simulation with respect to 2 input parameters?
Answer
(a) reverse, (b) forward.
Solution
Reverse needs one pass per output, forward one pass per input: (a) 1 versus passes, (b) 2 forward passes versus 1000 reverse passes.
Exercise 2: Dual number product
Compute and explain what it gives.
Answer
: the value of and its derivative at .
Solution
since .
Exercise 3: A dual-number gradient (code)
Use the Dual idea to get both partial derivatives of at with two forward passes.
Answer
, .
Solution
Seed with derivative 1 and with 0 for the first pass, and the reverse for the second.
import math
class D:
def __init__(s, v, d): s.v, s.d = v, d
def __add__(s, o): return D(s.v + o.v, s.d + o.d)
def __mul__(s, o): return D(s.v * o.v, s.d * o.v + s.v * o.d)
sin = lambda a: D(math.sin(a.v), math.cos(a.v) * a.d)
g = lambda x, y: x * y + sin(x)
print(round(g(D(2, 1), D(3, 0)).d, 4), round(g(D(2, 0), D(3, 1)).d, 4))2.5839 2.0
Test yourself
Reverse-mode autodiff computes in one pass…
- a Jacobian-vector product
- a vector-Jacobian product, e.g. the full gradient of a scalar
- the Hessian
- a finite difference
Dual numbers implement…
- reverse mode
- forward mode
- symbolic differentiation
- finite differences
Why does training need more memory than inference?
- Gradients are larger than weights
- Reverse mode stores intermediate values for the backward sweep
- Inference uses smaller batches
- It does not