TExcelTAD
Home › Math for Deep Learning & LLMs › Forward and Reverse Mode

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 f=f3∘f2∘f1f = f_3 \circ f_2 \circ f_1 from Rn\mathbb{R}^n to Rm\mathbb{R}^m has Jacobian J=J3J2J1J = J_3J_2J_1. The product can be evaluated right-to-left or left-to-right:

  • Forward mode pushes a tangent vector v\mathbf{v} through: Jv=J3(J2(J1v))J\mathbf{v} = J_3(J_2(J_1\mathbf{v})), a Jacobian-vector product (JVP). One pass gives one column-combination; the full Jacobian needs nn passes.
  • Reverse mode pulls a cotangent vector u\mathbf{u} back: uTJ=((uTJ3)J2)J1\mathbf{u}^TJ = ((\mathbf{u}^TJ_3)J_2)J_1, a vector-Jacobian product (VJP). One pass gives one row-combination; the full Jacobian needs mm passes.

A loss function has m=1m = 1 output and nn in the millions or billions, so reverse mode (backpropagation) wins by a factor of nn. Forward mode wins when there are few inputs and many outputs.

Forward mode with dual numbers

Forward mode can be implemented by dual numbers a+bεa + b\varepsilon with ε2=0\varepsilon^2 = 0. Then f(a+ε)=f(a)+f′(a)εf(a + \varepsilon) = f(a) + f'(a)\varepsilon: evaluating the program on a dual number carries the derivative along.

python · try it yourself
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 vˉ=∂L/∂v\bar{v} = \partial\mathcal{L}/\partial v. 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

python · try it yourself
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 n×nn \times n Hessian.

In software

  • JAX exposes both modes directly: jax.jvp, jax.vjp, jax.jacfwd, jax.jacrev, and jax.grad (reverse mode for scalar outputs).
  • PyTorch is reverse mode by default (backward, torch.autograd.grad); torch.func.jvp and torch.func.jacfwd add 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 10810^8 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 10810^8 passes, (b) 2 forward passes versus 1000 reverse passes.

Exercise 2: Dual number product

Compute (3+1ε)(3+1ε)(3 + 1\varepsilon)(3 + 1\varepsilon) and explain what it gives.

Answer

9+6ε9 + 6\varepsilon: the value of x2x^2 and its derivative 2x2x at x=3x = 3.

Solution

(3+ε)2=9+6ε+ε2=9+6ε(3 + \varepsilon)^2 = 9 + 6\varepsilon + \varepsilon^2 = 9 + 6\varepsilon since ε2=0\varepsilon^2 = 0.

Exercise 3: A dual-number gradient (code)

Use the Dual idea to get both partial derivatives of g(x,y)=xy+sin⁡xg(x, y) = xy + \sin x at (2,3)(2, 3) with two forward passes.

Answer

∂g/∂x=3+cos⁡2≈2.5839\partial g/\partial x = 3 + \cos 2 \approx 2.5839, ∂g/∂y=2\partial g/\partial y = 2.

Solution

Seed xx with derivative 1 and yy with 0 for the first pass, and the reverse for the second.

python · try it yourself
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…

  1. a Jacobian-vector product
  2. a vector-Jacobian product, e.g. the full gradient of a scalar
  3. the Hessian
  4. a finite difference

Dual numbers implement…

  1. reverse mode
  2. forward mode
  3. symbolic differentiation
  4. finite differences

Why does training need more memory than inference?

  1. Gradients are larger than weights
  2. Reverse mode stores intermediate values for the backward sweep
  3. Inference uses smaller batches
  4. It does not