Automatic differentiation
自动微分
Carry derivatives through an executed program, implement forward mode with dual numbers, and choose between input directions and output sensitivities.
automatic-differentiationRun the program with an extra number
Suppose a program computes . At , its value is zero. How quickly does it change if only moves? You could derive the formula by hand, or run the program at nearby inputs and estimate a slope. Automatic differentiation (AD) offers another route: each primitive operation computes its value and applies a local derivative rule. The chain rule combines those rules through the executed program.
This is not a small-step approximation. It does not require expanding the entire program into a symbolic formula either. It still uses finite-precision arithmetic in most implementations, and it needs valid differentiation rules for the operations encountered. Baydin et al., Sections 2–3
Follow an input direction or an output sensitivity
In forward mode, attach a tangent to each value . The tangent represents change along a chosen input direction. For addition, multiplication, and sine:
For and input seed , one forward sweep computes the Jacobian–vector product . Setting one seed coordinate to 1 and the others to 0 gives one Jacobian column. A general dense Jacobian therefore takes such directions, though implementations may batch directions or exploit structure.
In reverse mode, first evaluate and retain the needed computation history, then propagate an output seed backward. A seed produces . A scalar loss has just one output seed, making reverse mode attractive for many-parameter training. A general dense Jacobian takes reverse seed directions. This comparison counts sweeps, not a universal wall-clock speedup: memory, tensor operations, batching, and sparsity matter. Baydin et al., Sections 3.1–3.2
Dual numbers provide a compact way to implement forward mode. Use a formal symbol with , storing . Multiplication then gives:
The symbol is algebraic, not a very small floating-point step. For a differentiable primitive, its dual-number rule records the value and first-order coefficient. This representation explains why the product rule appears directly in overloaded multiplication.
A small forward-mode engine
This complete Python program supports real scalars, addition, multiplication, and sine. It computes two partial derivatives and one combined direction without using finite differences.
from dataclasses import dataclass
import math
@dataclass(frozen=True)
class Dual:
value: float
tangent: float = 0.0
def __add__(self, other):
other = other if isinstance(other, Dual) else Dual(other)
return Dual(self.value + other.value, self.tangent + other.tangent)
__radd__ = __add__
def __mul__(self, other):
other = other if isinstance(other, Dual) else Dual(other)
return Dual(self.value * other.value,
self.tangent * other.value + self.value * other.tangent)
__rmul__ = __mul__
def sin(a):
return Dual(math.sin(a.value), math.cos(a.value) * a.tangent)
def f(x, y):
return x * x * y + sin(x)
x, y = 0.4, 3.0
dx = f(Dual(x, 1), Dual(y, 0))
dy = f(Dual(x, 0), Dual(y, 1))
direction = f(Dual(x, 1), Dual(y, 2))
expected_x, expected_y = 2*x*y + math.cos(x), x*x
assert math.isclose(dx.value, x*x*y + math.sin(x))
assert math.isclose(dx.tangent, expected_x)
assert math.isclose(dy.tangent, expected_y)
assert math.isclose(direction.tangent, expected_x + 2*expected_y)
assert f(Dual(0, 1), Dual(3, 0)).tangent == 1
assert f(Dual(x), Dual(y)).tangent == 0
assert (2 * Dual(3, 1) + 4).tangent == 2
For these bounded-size scalar primitives, one tangent direction adds constant work per executed operation. It carries local tangents alongside live values without requiring a reverse tape. Asking for every input partial by rerunning this scalar-seed implementation multiplies the work by the input dimension.
A gradient follows the program you wrote
An incorrect loss still gets differentiated. Extracting an ordinary number from a tracked value can sever its derivative path. Our small engine does not implement subtraction, division, comparisons, arrays, or arbitrary library functions; each supported primitive needs a corresponding rule. Calling math.sin directly on a Dual will not silently extend the engine.
Branches deserve care. Differentiating the branch taken at a particular input can describe local behavior when that branch stays unchanged nearby. At a switching boundary, the full function may be nondifferentiable. Framework conventions at a kink are useful computational choices, not proof that an ordinary derivative exists there. Discrete indexing and sampled decisions also need separate treatment.
Reverse mode may retain many intermediates; checkpointing reduces storage by recomputing some values. Frameworks may also accumulate gradients across calls unless buffers are cleared. These are execution and storage policies, distinct from the mathematical derivative. D2L, Section 2.5
Choose the seed before the mode
- What does seed compute? Answer: zero directional change, even when individual partial derivatives are nonzero.
- Does seed return the full gradient? Answer: no; it returns the single scalar .
- For a differentiable scalar loss with a million inputs, which mode usually needs fewer seed sweeps for all input partials? Answer: reverse mode, with one output seed. This does not eliminate forward evaluation or storage costs.
- Would changing the dual-number symbol to a tiny decimal improve accuracy? Answer: no. Dual arithmetic enforces algebraically; substituting a numerical step changes the method.
Keep differentiation and optimization separate
AD supplies derivatives. An optimizer decides how to use them, and an experiment determines whether the model improves on the task. The next useful step is to compare this forward-mode engine with the reverse accumulation in the computational-graphs article. Both implement the chain rule; their different traversal and seed choices explain the main time–memory tradeoff. Higher-order derivatives require differentiating the derivative computation with additional support; repeatedly calling this first-order example does not provide them automatically.
Make a prediction, then check
For scalar f(x,y), what does forward seed (1,2) produce?
Learning objectives
- Implement a forward-mode engine with dual numbers to compute partial and directional derivatives.
- Compare forward and reverse modes using seeds, Jacobian products, and storage needs.
Prerequisites & connections
Explore related knowledge →References
- Automatic Differentiation in Machine Learning: a Survey
Atilim Gunes Baydin; Barak A. Pearlmutter; Alexey Andreyevich Radul; Jeffrey Mark Siskind · 2018 - Dive into Deep Learning — Automatic Differentiation
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023 - Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Derived dual multiplication from ε²=0; checked forward J r, reverse Jᵀ s, and the assumptions behind n/m seed-sweep comparisons.
- Ran the dual-number engine and 20 additional input/seed combinations against analytic derivatives; checked zero seeds, scalar promotion, supported-operation boundaries, branches, and higher-order limitations.
- Compared arguments, numbers, examples, limitations, and exercise answers across languages; structural validation separately compares display formulas, code, sources, and sections. No independent human peer review.
Source locations checked:
- Automatic Differentiation in Machine Learning: a Survey · §2, §3.1, §3.1.1, §3.2: finite differences, forward mode, dual numbers, and reverse mode
- Dive into Deep Learning — Automatic Differentiation · §2.5: recorded operations, gradients, and accumulation
Related topics