Automatic Differentiation: Forward Mode and Reverse Mode Compared
Trace one function through both modes of automatic differentiation, compare their costs, and learn where each one fits.
Key takeaways
- Automatic differentiation is exact up to floating-point rounding, and it is neither symbolic algebra nor numerical approximation.
- One forward-mode pass gives a Jacobian-vector product, and one reverse-mode pass gives a vector-Jacobian product.
- Forward mode suits few inputs and many outputs, while reverse mode suits many inputs and few outputs.
- Reverse mode must keep intermediate values, so it trades memory for speed.
- The tool differentiates the code you wrote, including its branches and numerical weaknesses.
Automatic differentiation computes derivatives of a program by applying the chain rule to each elementary operation as the program runs. Forward mode carries derivatives along with the values, from inputs to outputs. Reverse mode records the computation first, then carries derivatives from outputs back to inputs.
Choose by shape. Forward mode costs about one extra pass per input you differentiate with respect to. Reverse mode costs about one backward pass per output. A training loss has one output and a huge number of inputs, so neural networks use reverse mode.
Three ways to get a derivative
| Method | How it works | Main weakness |
|---|---|---|
| Symbolic | Manipulates a formula into a new formula | Expressions can grow very large, and loops are awkward |
| Numerical | Perturbs an input and takes a difference | Approximate, and one or two evaluations per input |
| Automatic | Applies exact local rules to executed operations | Needs the program built from supported operations |
The numerical method has a built-in tension. A forward difference [f(x + h) − f(x)]/h has an error roughly proportional to h, and a central difference one roughly proportional to h². Making h tiny reduces that error but makes the subtraction of two nearly equal numbers lose precision. Numerical differences remain valuable as an independent test.
One function as a list of steps
Take f(x₁, x₂) = x₁x₂ + sin x₁, with the angle in radians, at x₁ = 2 and x₂ = 3. A computer evaluates it as a sequence of primitive operations.
v₁ = x₁ = 2
v₂ = x₂ = 3
v₃ = v₁ · v₂ = 6
v₄ = sin v₁ ≈ 0.909
v₅ = v₃ + v₄ ≈ 6.909 By hand, ∂f/∂x₁ = x₂ + cos x₁ ≈ 2.584 and ∂f/∂x₂ = x₁ = 2. Both modes must reproduce these.
Forward mode: carry a tangent
Pick a direction in input space and attach to every value its rate of change along that direction, called its tangent, written dv. To get ∂f/∂x₁, start with dv₁ = 1 and dv₂ = 0.
dv₃ = dv₁ · v₂ + v₁ · dv₂ = 3
dv₄ = cos(v₁) · dv₁ ≈ −0.416
dv₅ = dv₃ + dv₄ ≈ 2.584 For ∂f/∂x₂ you must run again with dv₁ = 0 and dv₂ = 1. Nothing has to be stored: once a value and its tangent have been used for the last time, they can be dropped.
One neat implementation uses dual numbers, written a + bε, with the rule ε² = 0. Multiplying (a + bε)(c + dε) gives ac + (ad + bc)ε, and the product rule appears for free.
import math
class Dual:
def __init__(self, val, tan=0.0):
self.val, self.tan = val, tan
def __add__(self, o):
return Dual(self.val + o.val, self.tan + o.tan)
def __mul__(self, o):
return Dual(self.val * o.val,
self.tan * o.val + self.val * o.tan)
def sin(d):
return Dual(math.sin(d.val), math.cos(d.val) * d.tan)
x1, x2 = Dual(2.0, 1.0), Dual(3.0, 0.0) # differentiate in x1
out = x1 * x2 + sin(x1)
print(out.val, out.tan) # about 6.909 and 2.584 Reverse mode: carry an adjoint
Reverse mode attaches to every value the derivative of the output with respect to it, called its adjoint, written v̄. First run the program and save the values. Then start with v̄₅ = 1 and walk backward.
from v₅ = v₃ + v₄ : v̄₃ = 1, v̄₄ = 1
from v₄ = sin v₁ : v̄₁ += v̄₄ · cos v₁ ≈ −0.416
from v₃ = v₁ · v₂ : v̄₁ += v̄₃ · v₂ = 3, total ≈ 2.584
v̄₂ += v̄₃ · v₁ = 2 One backward sweep delivered both partial derivatives. The += matters: v₁ was used twice, and its two contributions add. The chain rule on computation graphs builds a small reverse-mode class in the same spirit.
Counting the cost
Let f map n inputs to m outputs. The full Jacobian takes n forward passes, one column each, or m reverse passes, one row each. Each pass costs a small multiple of evaluating f.
| Situation | Inputs and outputs | Better choice |
|---|---|---|
| Gradient of a training loss | Millions in, 1 out | Reverse |
| Sensitivity of a whole simulated curve to 2 constants | 2 in, 1,000 out | Forward |
| Directional derivative along one vector | Any | Forward |
| Square Jacobian of a small system | Similar counts | Either, forward often simpler |
Memory is the catch in reverse mode. The backward rule for a product needs its inputs, and the rule for many activation functions needs inputs or outputs, so these stay alive. In a deep network the stored activations can exceed the size of the parameters. Activation checkpointing saves only some and recomputes the rest.
Combining the modes
The modes compose. To multiply the Hessian by a vector u, take the gradient with reverse mode and then differentiate that gradient along u with forward mode. The cost is a few times that of a gradient, with no Hessian formed. This is the workhorse behind curvature analysis in the Hessian and curvature.
In JAX the two primitives are exposed directly as jax.jvp and jax.vjp, as described in JAX transformations. PyTorch is best known for reverse mode through backward, and it also offers forward-mode tools. Interfaces change, so check the current documentation.
How tools capture your program
Two broad designs exist, and many systems blend them.
- Recording during execution. Each operation on a tracked value is logged as it happens. Ordinary loops and conditionals work naturally, and each run can build a different record.
- Transforming ahead of time. The system traces or analyzes the code into an intermediate form, derives a new program for the derivative and may compile it. This allows more optimization, with restrictions on how control flow can depend on data.
Either way, each primitive needs a registered derivative rule. If you call into code the tool cannot see, such as a compiled routine, you must supply the rule yourself or the gradient path is lost.
A decision example
Say you have built a small physical model with three constants, and it predicts a sensor reading at 10,000 time points. You want to fit the constants by least squares.
The answer depends on which derivative you need. For the gradient of the single squared-error number, reverse mode takes one sweep, but it must store the intermediate state at every time point. Forward mode takes three passes, one per constant, with almost no storage. Here forward mode is likely to be the practical choice, despite the scalar output.
Now suppose you want the full table of how each reading responds to each constant, perhaps for a Gauss-Newton fit or to estimate parameter uncertainty. That table has 10,000 rows and 3 columns. Forward mode builds it in three passes. Reverse mode would need 10,000 sweeps.
Replace the three constants with a neural network of a million weights inside the same model, and the balance flips. A million forward passes are out of reach, while one reverse sweep still delivers the whole gradient. You then manage the memory with checkpointing or an implicit method.
The rule of thumb about input and output counts is a good start. Memory, the length of any loop and which quantity you actually need settle the rest. Measure both on a reduced version when the answer is not obvious.
Where correct code gives surprising gradients
Branches. The tool differentiates the branch that ran. At a switch point, it returns the derivative of one side, even if the function has no derivative there.
Guarded operations. Suppose you compute both sqrt(x) and 0, then select by the condition x > 0. For negative x the unused square root yields an undefined value, and in reverse mode a zero upstream gradient multiplied by that undefined local derivative still gives an undefined result. Make the input safe before the risky operation, for example by substituting a harmless positive value wherever x ≤ 0 and then selecting the result as before.
Unstable formulas. Computing ln(1 + exp(z)) literally overflows for large z. The rearranged form max(z, 0) + ln(1 + exp(−|z|)) keeps both value and derivative well behaved.
Iterative solvers. Differentiating through hundreds of iterations stores all of them, and the derivative may converge at a different rate from the value. If the answer satisfies an equation, implicit differentiation can be far cheaper.
Discrete steps. Rounding, sorting indices and sampling a category give zero or undefined derivatives. You need a smooth surrogate or a different estimator.
Common questions
Is backpropagation a kind of automatic differentiation?
Yes. Backpropagation is reverse mode applied to a neural network and its loss.
How should I check a custom derivative rule?
Compare it with central differences in double precision at several random points, away from kinks. A random direction tests all entries at once.
Does automatic differentiation give second derivatives?
Usually, yes. If the derivative computation is itself made of supported operations, you can differentiate it again. Some libraries require you to ask for the backward pass to be recorded, and some custom or fused operations do not support a second derivative. Cost and memory grow with each level, so prefer products such as Hessian times vector over full higher-order tables.
Can automatic differentiation handle a Python loop?
Yes, when the tool records operations as they run, since the loop simply produces more recorded steps. Compiled or traced systems may need their own loop constructs when the number of iterations depends on data.