Automatic Differentiation

Automatic differentiation (AD) is a family of techniques for evaluating exact derivatives of functions specified as computer programs, by systematically applying the chain rule to elementary operations recorded during program execution. It is the computational engine behind virtually every modern deep learning framework — without it, training neural networks with millions or billions of parameters would be computationally intractable. The remarkable fact is that AD computes exact gradients (not numerical approximations) with a cost proportional to a small constant multiple of the forward pass, regardless of the number of parameters.

The core insight

The "aha moment" is this: any computer program that computes a function is, implicitly, a sequence of elementary operations — additions, multiplications, activations — each of which has a trivially known derivative. AD threads the chain rule through this sequence automatically, producing exact gradients without ever writing a symbolic derivative by hand. In reverse mode (backpropagation), the cost of computing the gradient of a scalar loss with respect to all parameters is only about 2–3× the cost of the forward pass — completely independent of the number of parameters. This asymmetry is what makes training a 100-billion-parameter model feasible.

How It Works

The Computation Graph

Every differentiable program can be unrolled into a Wengert list (also called a tape): a directed acyclic graph (DAG) where nodes are intermediate values and edges represent elementary operations. Given a function f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^m, AD exploits the chain rule in one of two traversal orders.

Forward Mode (Tangent Linear) Forward mode propagates tangent vectors (directional derivatives) alongside primal values. For a single input perturbation x˙=∂x∂t\dot{x} = \frac{\partial x}{\partial t}, each intermediate variable viv_i carries a "dot" value v˙i=∂vi∂t\dot{v}_i = \frac{\partial v_i}{\partial t}.

1
v˙i=∑j∈parents(i)∂vi∂vjv˙j\quad \dot{v}_i = \sum_{j \in \text{parents}(i)} \frac{\partial v_i}{\partial v_j} \dot{v}_j

Explanation: The tangent of each node is the sum of its parents' tangents weighted by local Jacobian factors — a single forward sweep computes one directional derivative of the output with respect to a chosen input direction. Forward mode requires nn sweeps to compute the full Jacobian J∈Rm×nJ \in \mathbb{R}^{m \times n}, making it efficient when n≪mn \ll m (few inputs, many outputs).

Reverse Mode (Adjoint / Backpropagation) Reverse mode propagates adjoint values (also called cotangents or bars) backward through the tape. Define the adjoint of node viv_i as the sensitivity of the scalar output LL to viv_i:

2
vˉi=∂L∂vi\quad \bar{v}_i = \frac{\partial L}{\partial v_i}

Explanation: The adjoint vˉi\bar{v}_i measures how much a small perturbation in intermediate value viv_i changes the final loss LL — it is the fundamental quantity backpropagation accumulates. The reverse sweep applies the chain rule to accumulate adjoints from outputs back to inputs:

3
vˉj+=vˉi⋅∂vi∂vj\quad \bar{v}_j \mathrel{+}= \bar{v}_i \cdot \frac{\partial v_i}{\partial v_j}

Explanation: Each parent node vjv_j receives a contribution to its adjoint from every child viv_i, scaled by the local partial derivative — this accumulation over all children implements the multivariate chain rule exactly. A single reverse sweep computes ∇xL∈Rn\nabla_x L \in \mathbb{R}^n — all nn parameter gradients simultaneously — at cost O(forward pass)O(\text{forward pass}). This is the fundamental asymmetry that makes deep learning feasible.

Jacobian Cost Comparison For f:Rn→Rmf: \mathbb{R}^n \to \mathbb{R}^m with WW operations in the forward pass:

4
Costforward-mode full Jacobian=O(n⋅W),Costreverse-mode full Jacobian=O(m⋅W)\quad \text{Cost}_{\text{forward-mode full Jacobian}} = O(n \cdot W), \qquad \text{Cost}_{\text{reverse-mode full Jacobian}} = O(m \cdot W)

Explanation: When m=1m=1 (scalar loss, as in training), reverse mode computes the entire gradient in O(W)O(W) — independent of nn — while forward mode would require nn passes, one per parameter.

Operator Overloading in PyTorch

PyTorch implements reverse-mode AD via operator overloading: every `torch.Tensor` with `requires_grad=True` records operations into a dynamic tape. ```python import torch

# Define inputs x = torch.tensor([2.0, 3.0], requires_grad=True) W = torch.tensor([[1.0, 2.0], [3.0, 4.0]], requires_grad=True)

# Forward pass — tape is recorded automatically h = torch.tanh(W @ x) # shape: [2] L = h.sum() # scalar loss

# Reverse pass — adjoints flow backward through the tape L.backward() print(x.grad) # dL/dx — exact, not approximate print(W.grad) # dL/dW — computed in a single backward sweep ``` PyTorch's autograd engine stores a `grad_fn` on every non-leaf tensor, forming a linked list of `Function` objects. Each `Function` implements both `forward()` (primal computation) and `backward()` (local Jacobian-vector product). During `loss.backward()`, the engine performs a topological sort of this graph and calls `backward()` in reverse order, accumulating `.grad` on leaf tensors.

Custom Backward Passes You can register custom primitives with explicitly specified derivatives: ```python class MySigmoid(torch.autograd.Function): @staticmethod def forward(ctx, x): s = torch.sigmoid(x) ctx.save_for_backward(s) # save primal for use in backward return s @staticmethod def backward(ctx, grad_output): (s,) = ctx.saved_tensors

# dL/dx = dL/ds ds/dx = grad_output s(1-s) return grad_output s * (1 - s) sigmoid = MySigmoid.apply ```

5
∂L∂x=sˉ⋅σ(x)(1−σ(x)),sˉ=∂L∂σ(x)\quad \frac{\partial L}{\partial x} = \bar{s} \cdot \sigma(x)\bigl(1 - \sigma(x)\bigr), \quad \bar{s} = \frac{\partial L}{\partial \sigma(x)}

Explanation: The custom backward multiplies the incoming adjoint sˉ\bar{s} by the local derivative of sigmoid — a Jacobian-vector product — demonstrating the modular, chain-rule composition that all AD systems exploit.

researcher · Andreas Griewank | b. 1950 | Systematic Theory of Automatic Differentiation

Andreas Griewank, a German applied mathematician, developed much of the rigorous theoretical foundation for automatic differentiation, including complexity results, the treatment of higher-order derivatives, and the concept of "checkpointing" to trade memory for recomputation in reverse mode. His 2000 textbook Evaluating Derivatives remains the canonical reference for AD theory and is arguably the most cited work in the field. Remarkably, Griewank proved the "cheap gradient principle" — that reverse-mode AD computes gradients at cost no greater than 4–6× the forward pass — well before neural networks made this result famous to the broader computing community.

researcher · Seppo Linnainmaa | b. 1945 | Original Inventor of Reverse-Mode AD

Seppo Linnainmaa, a Finnish mathematician, first described the reverse accumulation of derivatives in his 1970 master's thesis at the University of Helsinki, and published the result in English in 1976 — more than a decade before backpropagation was popularized in neural networks. His algorithm applied to floating-point arithmetic rounding errors, not neural networks, making his contribution essentially invisible to the AI community for years. The connection between Linnainmaa's algorithm and neural network training was not widely recognized until historians of science traced the lineage in the 2000s, leaving him one of the most consequential uncredited inventors in modern computing.

Figure
Computation Graph and Reverse-Mode Sweep
Computation Graph: f(x,w) = tanh(w·x) → L x input w param × v₁=w·x tanh v₂=tanh(v₁) L loss → forward pass ← backward pass (adjoints) v̄₂=1 v̄₁=(1-v₂²)v̄₂ x̄=w·v̄₁ w̄=x·v̄₁ forward (primal) backward (adjoint)
Figure
Forward vs Reverse Mode Cost
Forward vs Reverse Mode: When to Use Each n inputs m outputs FORWARD MODE Cost: O(n · W) One pass per input Best when: n ≪ m e.g. PDEs, few params REVERSE MODE Cost: O(m · W) One pass per output Best when: m ≪ n e.g. neural nets (m=1) VS Deep Learning: n = 10⁸ params, m = 1 (scalar loss) → Reverse mode wins by 10⁸×

Intuition

The Mental Model

Imagine you are a quality inspector on a factory assembly line. The line transforms raw materials (inputs) through a series of workstations (operations) into a final product (output). Your boss asks: "If we tweak every dial and lever in this factory, how much does each one affect the final quality score?" The naive approach (numerical differentiation) would be to walk back to each of the thousands of levers, nudge it slightly, run the whole line again, and observe the change — an enormous task repeated for every single lever. Reverse-mode AD is smarter: you start at the final quality inspector and ask them, "What were you most sensitive to?" They tell you which upstream station mattered most. You walk to that station, ask the same question, and so on — tracing blame backward through the line in one pass. Each worker only needs to know their own local inputs and outputs, and the "blame signal" naturally accumulates as it travels back. By the time you've walked from the end to the start of the line once, you know every lever's influence. The key "feel" of reverse-mode AD: you record the factory's operations during the forward run (building the tape), then play the tape in reverse, passing sensitivity signals backward like water flowing upstream. No global analysis needed — just local, modular, chain-rule accounting at each node.

Historical Development

Origins · 1 minhow this was discovered
History
1964
Robert Edwin Wengert publishes the first explicit description of automatic differentiation via what becomes known as the "Wengert list" — a sequential tape of elementary operations enabling systematic derivative computation.
1970
Seppo Linnainmaa describes reverse accumulation of derivatives in his University of Helsinki master's thesis, implementing the algorithm in ALGOL and establishing the computational complexity of reverse-mode AD — predating neural network backpropagation by 16 years.
1981
Philip Wolfe's working paper circulates Linnainmaa's reverse-mode ideas in the mathematical programming community, connecting AD to optimization, though still without connection to neural networks.
1986
Rumelhart, Hinton, and Williams publish "Learning representations by back-propagating errors" in Nature, popularizing reverse-mode AD as "backpropagation" for training multi-layer neural networks — independently rediscovered and algorithmically equivalent to Linnainmaa's 1970 formulation.
1988
The Tapenade and ADIFOR projects begin formalizing AD tools for Fortran scientific computing, establishing the software engineering patterns — operator overloading vs. source transformation — that modern frameworks inherit.
1992
Andreas Griewank, together with colleagues, proves the "cheap gradient theorem" rigorously and introduces checkpointing (gradient checkpointing), enabling reverse-mode AD on programs too large to store the full tape in memory.
2001
The Theano project at Université de Montréal pioneers symbolic differentiation on computational graphs with GPU acceleration, directly foreshadowing TensorFlow's static-graph design.
2015
TensorFlow 1.0 and PyTorch (originally Torch Autograd) launch, making dynamic and static reverse-mode AD accessible to practitioners via define-by-run and define-and-run paradigms respectively — triggering the deep learning explosion.
2018
JAX is released by Google Brain, combining reverse-mode AD with functional transformations (`jit`, `vmap`, `grad`) and enabling higher-order derivatives, forward-over-reverse mixed mode, and vectorized Jacobians — representing the state-of-the-art in composable AD systems.

Why It Matters

Real-World Impact
GPT-4 / Large Language ModelsEvery training step of a transformer-based LLM applies reverse-mode AD to compute gradients of the cross-entropy loss with respect to hundreds of billions of parameters. Without the O(W) cost guarantee of reverse mode, a single gradient step would cost orders of magnitude more than the forward pass, making LLM training economically and physically impossible.
AlphaFold 2DeepMind's protein structure predictor uses AD not only to train the network but to differentiate through iterative geometric refinement algorithms (Evoformer + structure module), treating physical simulations as differentiable components of the computation graph.
Physics-Informed Neural Networks (PINNs)AD differentiates neural network outputs with respect to input coordinates (not parameters) to compute spatial and temporal derivatives, allowing PDEs like Navier-Stokes to be enforced as soft constraints — a use case where forward-mode AD is often preferred since there are few inputs (coordinates) and many "output" PDE residuals.
Neural Radiance Fields (NeRF)The rendering pipeline — ray marching through a volumetric scene representation — is made end-to-end differentiable via AD, enabling pixel-level reconstruction loss to flow gradients back to 3D scene parameters without any hand-derived rendering derivatives.
Differentiable Robotics / MuJoCoSimulation environments are implemented as differentiable programs using AD, allowing robot controllers to be trained by backpropagating physical reward signals through entire simulated trajectories, bypassing the need for policy-gradient variance reduction.
Gradient Checkpointing in Billion-Parameter ModelsGriewank's checkpointing strategy, now standard in Hugging Face Transformers as `gradient_checkpointing_enable()`, trades the O(n)O(n) memory cost of storing all activations for O(n)O(\sqrt{n}) memory by selectively recomputing forward-pass values during the backward sweep — making models like LLaMA 65B trainable on practical GPU memory budgets.
Neural ODEsChen et al. (2018) showed that ODE solvers can be treated as black-box operations and differentiated via the adjoint method — mathematically equivalent to reverse-mode AD applied to an infinite-depth computation — enabling continuous-depth models and memory-efficient training of dynamic systems.

Prerequisites

What This Leads To

See Also

Backpropagation · Computational Graphs · JAX and Functional Transformations · Higher-Order Derivatives · Differentiable Programming

Where this leads