Automatic Differentiation
Dive into Deep Learning · §34.5
Automatic Differentiation
dual numbers & forward mode · reverse mode & the tape · parameter gradients · checkpointing · HVPs · implicit differentiation
12 Days vs. 30 Milliseconds: The 10⁸-Parameter Gap
Motivation
- Finite Differences (10^8 Passes): Nudging 10^8 parameters one by one at 10 ms/pass takes ~11.6 days per step.
- Reverse-Mode Autodiff (1 Sweep): Returns all 10^8 exact partial derivatives in ~3 forward-pass times (~30 ms).
- Columns vs. Rows of \mathbf{J} = \mathbf{J}_K \cdots \mathbf{J}_1: Forward mode propagates 1 input column per pass; reverse mode propagates 1 output row.
Dual Numbers: Truncating Taylor Series Algebraically
Forward-Mode Algebra
- Dual Arithmetic (a + b\varepsilon with \varepsilon^2 = 0): (a + b\varepsilon)(c + d\varepsilon) = ac + (ad + bc)\varepsilon encodes the product rule automatically.
- Exact Powers at x = 3: (3 + \varepsilon)^2 = 9 + 6\varepsilon and (3 + \varepsilon)^3 = 27 + 27\varepsilon with zero step-size error.
- 2 \times 2 Matrix Isomorphism: a + b\varepsilon \leftrightarrow \left(\begin{smallmatrix}a & b \\ 0 & a\end{smallmatrix}\right).
Proving Dual Evaluation Returns Exact Derivatives
Structural Induction
- Overloaded Primitives: Defining \varphi(a + b\varepsilon) = \varphi(a) + \varphi'(a)b\varepsilon ensures f(x + 1\varepsilon) = f(x) + f'(x)\varepsilon for any composed program.
- Proof by Structural Induction: Base cases (c + 0\varepsilon, x + 1\varepsilon) and inductive steps (+, \times, \varphi \circ g) preserve exact derivatives of the executed path, through loops and branches.
Implementing Dual Numbers via Operator Overloading
Forward-Mode Engine
In Python, a short Dual(a, b) class overloads +, *, sin, exp, and log to propagate the value a and tangent b (\dot{v}) side by side. Evaluating f(x) = \sin(x^2) + e^x on Dual(1.3, 1.0) returns f(1.3) and f'(1.3) = 2x\cos(x^2) + e^x in one call:
dual result : 4.6622 + 3.360101 eps
value f(x) : 4.662200318713363
derivative : dual 3.360101 vs exact 3.360101
Both the function value 4.6622 and the derivative 3.360101 match the analytic formula to every printed digit, with no step size to tune.
Jacobian-Vector Products (JVPs) and Vector Tangents
Columns vs. Arithmetic
- Directional JVP: Seeding inputs with \mathbf{x} + \mathbf{v}\varepsilon evaluates \mathbf{f}(\mathbf{x}) + (\mathbf{J}\mathbf{v})\varepsilon in one pass.
- Vector Tangent Illusion: Passing length-n array tangents \mathbf{I}_n runs in one Python call but performs the same O(n) vector arithmetic at every primitive op.
one-pass J:
[[1. 0.877583]
[0.5 1. ]]
matches the analytic Jacobian: True
Two Association Orders: JVP (Right) vs. VJP (Left)
Complexity Rule
- Never materialize intermediate Jacobians: Autodiff engines multiply a seed vector through \mathbf{J} = \mathbf{J}_K \mathbf{J}_{K-1} \cdots \mathbf{J}_1 one step at a time, either forward (\mathbf{J}\mathbf{v} = \mathbf{J}_K(\cdots(\mathbf{J}_1\mathbf{v}))) or reverse: \mathbf{u}^\top\mathbf{J} = \bigl((\mathbf{u}^\top\mathbf{J}_K)\mathbf{J}_{K-1}\cdots\bigr)\mathbf{J}_1
- Match the shorter dimension of \mathbf{J} \in \mathbb{R}^{m \times n}:
- Forward mode: 1 sweep per input direction (n sweeps for full \mathbf{J}; ideal when n \ll m).
- Reverse mode: 1 sweep per output direction (m sweeps for full \mathbf{J}; for a scalar loss m = 1, one sweep gives the entire gradient).
Why Reverse Mode Needs a Tape (Wengert List)
Execution Asymmetry
- Tangents (\dot{v}) vs. Adjoints (\bar{v}):
- Tangent \dot{v} = \frac{\mathrm{d}v}{\mathrm{d}x} depends only on operations before v and flows forward alongside values without storing history.
- Adjoint \bar{v} = \frac{\mathrm{d}\ell}{\mathrm{d}v} depends on every consumer after v (\bar{v} = \sum_c \bar{c}\frac{\partial c}{\partial v}) and flows backward against execution.
- Two-phase execution (Wengert, 1964; Linnainmaa, 1970): Reverse mode must first run the program forward while recording every operation and intermediate value onto a tape, then replay that tape in reverse topological order from \bar{\ell} = 1.
Anatomy of a 40-Line Reverse-Mode Tape Engine
Reverse-Mode Engine
- 1. DAG Node (
Var): Stores .value, .grad (initialized to 0.0), ._parents, and ._backward(g).
- 2. Local VJP Closures: Addition adds
g to both parents; multiplication multiplies g by the other parent’s forward .value.
- 3. Post-Order Topological Sort: Replaying
reversed(order) from node.grad = 1.0 ensures every child adjoint is accumulated before v._backward(v.grad) runs.
Hand-Tracing a Diamond Tape: Why += Is Mandatory
Multi-Consumer Nodes
- Forward tape of y = (uv + u)^2 at (2, -3): Records t = uv = -6, r = t + u = -4, and y = r \cdot r = 16.
- Reverse sweep from \bar{y} = 1:
- Node r feeds both factors of y = r \cdot r, so \bar{r} = \bar{y}r + \bar{y}r = -4 + (-4) = -8, and \bar{t} = \bar{r}(1) = -8.
- Input u feeds both r = t+u and t = uv, so \bar{u} = \bar{r}(1) + \bar{t}(v) = -8 + (-8)(-3) = 16, while \bar{v} = \bar{t}(u) = -16.
- Why
+= is essential: Overwriting with = at fan-out nodes r and u drops parallel paths.
Toy Tape vs. Production Framework Autograd
Code Verification
Both our 40-line Var tape and production framework autograd (which scales Var to tensor VJPs) return \partial y/\partial u = 16 and \partial y/\partial v = -16:
our tape : dy/du = 16.0000 dy/dv = -16.0000
torch : dy/du = 16.0000 dy/dv = -16.0000
Why Parameter Gradients Cost ~3 Forward Passes
Arithmetic Budget
- Three Matrix Products per Layer (\mathbf{h}_k = \mathbf{W}_k\mathbf{h}_{k-1}):
- Forward pass: \mathbf{h}_k = \mathbf{W}_k\mathbf{h}_{k-1} (d_k d_{k-1} mults, saves \mathbf{h}_{k-1}).
- Weight gradient: \nabla_{\mathbf{W}_k}\ell = \bar{\mathbf{h}}_k\mathbf{h}_{k-1}^\top (d_k d_{k-1} mults).
- Adjoint pushdown: \bar{\mathbf{h}}_{k-1} = \mathbf{W}_k^\top\bar{\mathbf{h}}_k (d_k d_{k-1} mults).
- Total Cost: 3\times one forward pass (within the Baur–Strassen 3\text{--}5\times bound).
Measuring the Operation Count Gap: 80,200 vs. 802
Empirical Benchmark
- Benchmark f(\mathbf{x}) = (\sum_{j=1}^{200} x_j^2)^2 (2n+1 = 401 Ops): Forward mode takes 200 \times 401 = 80{,}200 ops; reverse mode takes 2 \times 401 = 802 ops (100\times speedup).
forward mode: 80,200 operations (200 passes of 401)
reverse mode: 802 operations (one recorded pass, one sweep)
ratio 100.0, largest gradient difference 0.0e+00
The Memory Bottleneck and Activation Checkpointing
Memory-Compute Trade-off
- Why reverse mode is memory-bound: A T-step computation stores all T intermediate activations on the tape until the backward sweep consumes them.
- Checkpointing every s-th step (Chen et al., 2016): Save only T/s checkpoints during the forward pass; during the backward sweep, recompute each length-s segment from its checkpoint onto a local tape of size s.
- Optimal segment length s^\star = \sqrt{T}: Peak memory is M(s) = \frac{T}{s} + s \ge 2\sqrt{T} At T = 400 (s^\star = 20), peak memory drops 10\times (401 \to 40) for just one extra forward pass.
Composable Primitives: JVP and VJP in Frameworks
Framework APIs
Modern frameworks expose both linear operators, forward-mode jvp (\mathbf{J}\mathbf{v}) and reverse-mode vjp (\mathbf{u}^\top\mathbf{J}), as composable higher-order transformations. On \mathbf{f}(x, y) = (x + \sin y,\ y + x^2/2)^\top at (0.5, 0.5)^\top with \mathbf{v} = \mathbf{u} = (1, 2)^\top:
J v = [2.7552 2.5 ]
u^T J = [2. 2.8776]
J = [[1.0, 0.8776], [0.5, 1.0]]
Both \mathbf{J}\mathbf{v} = (2.7552, 2.5)^\top and \mathbf{u}^\top\mathbf{J} = (2.0, 2.8776) require only a single sweep and never allocate an m \times n matrix. Materialize the dense Jacobian \mathbf{J} only when \min(m, n) is small or when \det \mathbf{J} is needed (e.g., normalizing flows).
Verifying Forward-Over-Reverse HVP on Log-Sum-Exp
Closed-Form Check
For log-sum-exp \ell(\mathbf{x}) = \log\sum_j e^{x_j}, the gradient is \mathbf{p} = \operatorname{softmax}(\mathbf{x}) and the Hessian is \mathbf{H} = \operatorname{diag}(\mathbf{p}) - \mathbf{p}\mathbf{p}^\top, so \mathbf{H}\mathbf{v} = \mathbf{p} \odot \mathbf{v} - \mathbf{p}(\mathbf{p}^\top\mathbf{v}) in 3n scalar multiplications:
forward over reverse : [ 0.3571 0.0514 -0.4085]
p*v - p (p.v) : [ 0.3571 0.0514 -0.4085]
At \mathbf{x} = (1, -0.5, 2)^\top and \mathbf{v} = (1, 0.5, -1)^\top, forward-over-reverse returns (0.3571, 0.0514, -0.4085)^\top, matching \mathbf{p}\odot\mathbf{v} - \mathbf{p}(\mathbf{p}^\top\mathbf{v}) to every digit without building a 3 \times 3 matrix.
Implicit Differentiation Through Iterative Solvers
Implicit Function Theorem
- Equilibrium Layers (\mathbf{g}(\mathbf{x}^\star, \boldsymbol{\theta}) = \mathbf{0}): Differentiating at the root gives \frac{\partial\mathbf{x}^\star}{\partial\boldsymbol{\theta}} = -\bigl(\frac{\partial\mathbf{g}}{\partial\mathbf{x}}\bigr)^{-1}\frac{\partial\mathbf{g}}{\partial\boldsymbol{\theta}} with O(1) memory (no unrolled solver tape).
- One Adjoint Linear Solve: Solve \bigl(\frac{\partial\mathbf{g}}{\partial\mathbf{x}}\bigr)^\top\mathbf{a} = \mathbf{u} once for \mathbf{a} \in \mathbb{R}^d, then form \mathbf{u}^\top\frac{\partial\mathbf{x}^\star}{\partial\boldsymbol{\theta}} = -\mathbf{a}^\top\frac{\partial\mathbf{g}}{\partial\boldsymbol{\theta}}.
Implicit Gradient vs. Unrolling 20 Newton Steps
Solver-Independent Gradients
On the nonlinear 2 \times 2 system g_1(x, \theta) = x_1^2 + \theta x_2 - 2 = 0, g_2(x, \theta) = x_1 x_2 + \theta - 1 = 0 at \theta = 0.3, solving -\bigl(\frac{\partial \mathbf{g}}{\partial \mathbf{x}}\bigr)^{-1}\frac{\partial \mathbf{g}}{\partial \theta} once at the converged root \mathbf{x}^\star matches central differences of the 20-step Newton solver to 8 digits:
implicit-function gradient: [-0.11311451 -0.69322129]
finite-difference check : [-0.11311451 -0.69322129]
Memory cost is O(1) in the number of solver steps K, and any solver (Newton, Anderson acceleration, fixed-point iteration) that reaches \mathbf{x}^\star yields the exact same implicit gradient.
Two Failure Modes of Implicit Differentiation
Boundary Conditions
- 1. Singular Jacobian (\partial g/\partial x = 0): At \theta = 0 on x^2 - \theta = 0, 1/(2x^\star) divides by zero.
- 2. Unconverged Solver (\tilde{x}_k \not\to x^\star): At k = 1 on \theta = 4, both implicit (0.20) and unrolled (0.50) miss 0.25 until k \ge 3.
k=1: x = 2.50000, formula 0.2000, unrolled 0.5000, exact 0.25
k=2: x = 2.05000, formula 0.2439, unrolled 0.2900, exact 0.25
k=3: x = 2.00061, formula 0.2499, unrolled 0.2509, exact 0.25
What Autodiff Cannot Fix: Ill-Conditioned Products
Architectural Outlook
- Exact Evaluation of a Vanishing Number: If 50 layers each shrink activations by 0.5\times, reverse-mode AD computes 0.5^{50} \approx 8.9 \times 10^{-16} rapidly and accurately, yet training stalls.
- Architectural Remedies: Keeping singular values of \mathbf{J}_K \cdots \mathbf{J}_1 near 1 requires Xavier/He initialization, LayerNorm/BatchNorm, and residual skip connections.
Concept Check: Automatic Differentiation
Review & Practice
Test your grasp of forward vs. reverse mode, checkpointing, and implicit differentiation:
- Choosing the cheaper mode: Suppose an encoder \mathbf{f} : \mathbb{R}^{3} \to \mathbb{R}^{1000} maps 3 camera pose parameters to a 1000-pixel rendered column, and we need its full 1000 \times 3 Jacobian \mathbf{J}. How many sweeps does forward mode need vs. reverse mode?
- Activation checkpointing budget: A deep recurrent network unrolls for T = 10{,}000 time steps. How many intermediate states must plain reverse mode store, and what is the minimum peak memory 2\sqrt{T} achieved by optimal single-level checkpointing?
- Adjoint implicit solve: In ridge regression \mathbf{w}^\star(\boldsymbol{\lambda}) with d = 5000 regularization penalties \lambda_j, computing \partial\mathbf{w}^\star/\partial\boldsymbol{\lambda} directly requires 5000 linear solves. How many linear solves does the VJP adjoint route require to compute the gradient of scalar validation loss V(\mathbf{w}^\star(\boldsymbol{\lambda})) with respect to all 5000 penalties?
Concept Check: Automatic Differentiation (cont.)
Review & Practice
Answers:
- Here n = 3 \ll m = 1000: forward mode needs only 3 JVP sweeps (one per input column \mathbf{e}_1, \mathbf{e}_2, \mathbf{e}_3 with zero tape memory), whereas reverse mode would require 1000 VJP sweeps.
- Plain reverse mode stores all 10{,}000 states; checkpointing every s^\star = \sqrt{10{,}000} = 100 steps holds at most T/s + s = 100 + 100 = 200 states in memory (a 50\times memory reduction for one extra forward pass).
- Just 1 linear solve: solving (\partial\mathbf{g}/\partial\mathbf{w})^\top \mathbf{a} = \nabla_{\mathbf{w}} V once for the adjoint vector \mathbf{a} \in \mathbb{R}^{5000} yields all 5000 hyperparameter derivatives via -\mathbf{a}^\top(\partial\mathbf{g}/\partial\boldsymbol{\lambda}).
Summary: Automatic Differentiation Modes & Costs
Key Takeaways
| Forward Mode (JVP) |
Dual numbers f(\mathbf{x}+\mathbf{v}\varepsilon) = f(\mathbf{x}) + (\mathbf{J}\mathbf{v})\varepsilon (\varepsilon^2=0) |
1 pass per input seed (n passes for \mathbb{R}^n \to \mathbb{R}^m); O(1) extra memory |
| Reverse Mode (VJP) |
Forward tape + reverse sweep \bar{n} = \sum_c \bar{c}\frac{\partial c}{\partial n} |
1 sweep per output seed (1 sweep for scalar loss, \sim 3\times fwd FLOPs); O(T) tape memory |
| Layer Weight Gradient |
\nabla_{\mathbf{W}_k}\ell = \bar{\mathbf{h}}_k \mathbf{h}_{k-1}^\top, \bar{\mathbf{h}}_{k-1} = \mathbf{W}_k^\top \bar{\mathbf{h}}_k |
2 d_k d_{k-1} backward mults vs. 1 d_k d_{k-1} forward mults |
| Gradient Checkpointing |
Save every s-th step; recompute length-s segments |
Cuts tape memory from T to T/s + s = 2\sqrt{T} at s = \sqrt{T} (+1 fwd pass) |
| Forward-Over-Reverse HVP |
\mathbf{H}\mathbf{v} = \mathbf{J}_{\nabla\ell}\mathbf{v} = \frac{d}{dt}\nabla\ell(\mathbf{x}+t\mathbf{v})\big|_{t=0} |
Exact Hessian–vector product in O(1) sweeps without O(n^2) Hessian storage |
| Implicit Differentiation |
\mathbf{g}(\mathbf{x}^\star, \boldsymbol{\theta})=\mathbf{0} \Rightarrow (\frac{\partial\mathbf{g}}{\partial\mathbf{x}})^\top\mathbf{a} = \mathbf{u}, \nabla_{\boldsymbol{\theta}}\ell = -\mathbf{a}^\top\frac{\partial\mathbf{g}}{\partial\boldsymbol{\theta}} |
Differentiates converged roots in 1 linear solve & O(1) memory |