Foundations to Frontier
Tests
A. Mathematical Foundations › A8 Numerical Methods and Scientific Computing

Automatic Differentiation: Forward Mode, Reverse Mode, Computation Graphs

Automatic differentiation computes exact derivatives of any program by applying the chain rule to every elementary operation in its evaluation trace. Forward mode propagates tangents and gives Jacobian-vector products; reverse mode propagates adjoints backwards and gives vector-Jacobian products, so one sweep yields the whole gradient of a scalar loss. You will trace both modes by hand, build a small reverse-mode autograd engine, verify JVPs and VJPs with the dot-product test, and see why reverse mode (backpropagation) wins for neural networks while forward mode wins for tall Jacobians.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

A recipe that remembers how it changes

A program is a long recipe of tiny steps: multiply, add, take a sine. Each tiny step has a simple, known rate of change. Automatic differentiation follows the recipe and, at every step, also tracks how a small nudge to the inputs would change that step’s result. Chaining these tiny rates together, via the chain rule, gives the exact derivative of the whole program.

Inside autodiff: f(x₁, x₂) = ln x₁ + x₁x₂ − sin x₂
v₋₁ = 2.000v̄ = 5.500v₀ = 5.000v̄ = 1.716v₁ = 0.693v̄ = 1.000v₂ = 10.000v̄ = 1.000v₃ = -0.959v̄ = -1.000v₄ = 10.693v̄ = 1.000v₅ = 11.652v̄ = 1.000
One reverse sweep gives the full gradient: ∂f/∂x₁ = 5.500, ∂f/∂x₂ = 1.716
Forward mode pushes a tangent v̇ = ∂v/∂xᵢ along with each value: one pass per input. Reverse mode records the trace, then propagates adjoints v̄ = ∂f/∂v from the output back, accumulating contributions where a value is used twice (v₋₁ feeds v₁ and v₂). One reverse pass yields every partial derivative of a scalar output, which is why backpropagation trains networks with millions of parameters at the cost of a few forward passes.
Why engineers care

Backpropagation, which trains every neural network, is reverse-mode AD. Trajectory optimizers, differentiable simulators and system-identification tools for spacecraft and robots rely on AD for exact gradients and Jacobians at little more than the cost of running the model.

📝 Quick check (Level 0)
0/3 answered
  1. 1. AD computes derivatives by…
  2. 2. Backpropagation is which AD mode?
  3. 3. AD derivatives are…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Evaluation traces and computation graphs

Write the program as a sequence of elementary operations vi=φi(vparents(i))v_i = \varphi_i(v_{\text{parents}(i)}). This forms a directed acyclic graph from inputs to outputs.

Forward mode (tangents)

Carry v˙i=∂vi/∂xj\dot v_i = \partial v_i/\partial x_j alongside each value:

v˙i=∑k∈pa(i)∂φi∂vkv˙k\dot v_i = \sum_{k\in\text{pa}(i)}\frac{\partial\varphi_i}{\partial v_k}\dot v_k

Seeding x˙=v\dot x = v gives the Jacobian-vector product JvJv in one pass.

Reverse mode (adjoints)

Run the primal pass and store intermediate values. Then set yˉ=1\bar y = 1 and sweep backwards:

vˉk=∑i: k∈pa(i)vˉi∂φi∂vk\bar v_k = \sum_{i:\,k\in\text{pa}(i)}\bar v_i\frac{\partial\varphi_i}{\partial v_k}

This gives the vector-Jacobian product u⊤Ju^\top J, and so the full gradient of a scalar output in one sweep.

📝 Quick check (Level 1)
0/3 answered
  1. 1. Forward mode computes…
  2. 2. Reverse mode needs to store…
  3. 3. When a variable is used twice, its adjoint is…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

Cost: which mode when?

For f:Rn→Rmf:\mathbb R^n\to\mathbb R^m, the full Jacobian costs

  • forward mode: nn JVP passes;
  • reverse mode: mm VJP passes.

Each pass costs a small constant times one evaluation of ff (the “cheap gradient principle”: a gradient costs at most about 4–5 function evaluations; Griewank and Walther, 2008). Neural-network losses have n∼109n\sim10^9 and m=1m = 1, so reverse mode wins. Sensitivities of a long state trajectory to a few parameters have small nn, so forward mode wins.

Memory and checkpointing

Reverse mode stores the trace, so memory grows with program length. Checkpointing stores only some states and recomputes the rest. This trades compute for memory (Griewank’s revolve; gradient checkpointing in deep learning).

Engines

  • Operator overloading (tape): PyTorch, autograd, JAX tracing.
  • Source transformation: Tapenade, Enzyme.
  • Higher order: forward-over-reverse gives Hessian-vector products.
🐍 Exercise 1: a reverse-mode autograd engine
Implement a Value class that records parents and local derivatives for +, −, ×, ÷, powers, exp, log and tanh. Implement backward() with a topological sort. Check the gradients against central differences, and check that a reused variable accumulates its adjoint.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Full Jacobian of f: ℝ¹⁰⁰⁰ → ℝ² is cheapest with…
  2. 2. Gradient checkpointing trades…
  3. 3. Hessian-vector products are obtained by…

Level 3: Advanced

★★★★☆ Advanced⏱ 40 minGraduate level, with full derivations and proofs.

Correctness of reverse mode

Define vˉk=∂y/∂vk\bar v_k = \partial y/\partial v_k, holding the other independent paths fixed. By the multivariable chain rule, yy depends on vkv_k only through its children, so vˉk=∑i∈ch(k)vˉi ∂φi/∂vk\bar v_k = \sum_{i\in\text{ch}(k)}\bar v_i\,\partial\varphi_i/\partial v_k. Processing nodes in reverse topological order guarantees every child adjoint is final before it’s used. ∎

The dot-product test

For any u,vu, v: u⊤(Jv)=(J⊤u)⊤vu^\top(Jv) = (J^\top u)^\top v. Evaluating both sides with independently coded JVP and VJP routines is a sharp test that the adjoint code is the true transpose. It’s standard practice in adjoint-based data assimilation and seismic imaging.

Matrix-calculus building blocks

For y=Wxy = Wx: JVP y˙=Wx˙+W˙x\dot y = W\dot x + \dot Wx, VJP xˉ=W⊤yˉ\bar x = W^\top\bar y, Wˉ=yˉx⊤\bar W = \bar yx^\top. For an elementwise h=tanh⁡(a)h = \tanh(a): aˉ=(1−h2)⊙hˉ\bar a = (1 - h^2)\odot\bar h. Backprop is these rules applied layer by layer.

Exercise 3.1: adjoints for f = ln x₁ + x₁x₂ − sin x₂ at (2, 5)

xˉ1=x2+1/x1=5.5\bar x_1 = x_2 + 1/x_1 = 5.5, and xˉ2=x1−cos⁡x2=2−0.2837=1.7163\bar x_2 = x_1 - \cos x_2 = 2 - 0.2837 = 1.7163.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Reverse topological order ensures…
  2. 2. VJP of y = Wx with respect to x:
  3. 3. ∂f/∂x₁ for ln x₁ + x₁x₂ − sin x₂ at (2, 5):

Level 4: Expert

★★★★★ Expert⏱ 35 minResearchers: original papers and open problems.

Jacobians of a learned controller

A small policy network maps a 200-beam range scan to a 3-dimensional velocity command. Its input–output Jacobian ∂u/∂z\partial u/\partial z is used for sensitivity analysis, adversarial-robustness checks and Lipschitz estimates. Building it with forward mode takes 200 JVPs; reverse mode takes 3 VJPs. The two agree to 1e−16, and the dot-product test confirms the VJP is the exact transpose of the JVP.

🐍 Exercise 2 (research): JVPs, VJPs and the cost of Jacobians
Implement a JVP and a VJP for a 2-layer tanh MLP by hand. Pass the dot-product test. Build the 3×200 Jacobian in forward and reverse mode and compare the number of passes.

AD in AI, robotics and aerospace

  • Deep learning: backpropagation (Rumelhart, Hinton and Williams, 1986) is reverse-mode AD (Linnainmaa, 1970). JAX offers jvp, vjp, jacfwd and jacrev.
  • Optimal control and trajectory optimization: CasADi uses AD for exact Jacobians and Hessians. Adjoint methods give sensitivities of long trajectories.
  • Differentiable simulators: MuJoCo MJX, Brax and Warp provide gradients through contact dynamics for policy learning.
  • Earth and space science: 4D-Var data assimilation and adjoint CFD rely on reverse-mode sensitivities; the dot-product test is a standard QA step.

References

  1. A. Griewank, A. Walther (2008). Evaluating Derivatives, 2nd ed. SIAM.
  2. A. Baydin, B. Pearlmutter, A. Radul, J. Siskind (2018). “Automatic differentiation in machine learning: a survey.” JMLR, 18(153).
  3. S. Linnainmaa (1970). “The representation of the cumulative rounding error of an algorithm as a Taylor expansion of the local rounding errors.” Master’s thesis, University of Helsinki.
  4. D. Rumelhart, G. Hinton, R. Williams (1986). “Learning representations by back-propagating errors.” Nature, 323.
  5. J. Bradbury et al. (2018). JAX: composable transformations of Python+NumPy programs. github.com/google/jax.
  6. A. Paszke et al. (2019). “PyTorch: an imperative style, high-performance deep learning library.” NeurIPS.
  7. T. Chen et al. (2016). “Training deep nets with sublinear memory cost.” arXiv:1604.06174.
  8. W. Moses, V. Churavy (2020). “Instead of rewriting foreign code for machine learning, automatically synthesize fast gradients.” NeurIPS (Enzyme).
  9. J. Andersson et al. (2019). “CasADi.” Mathematical Programming Computation, 11.