Automatic differentiation I: forward mode and dual numbers
Automatic differentiation applies the chain rule to a program's evaluation trace and computes derivatives to machine precision. Build forward mode with dual numbers, formalize Jacobian–vector products and use Jacobians for Newton and simulation sensitivities.
After this lesson you can
- Decompose a program into its evaluation trace (Wengert list) and graph.
- Implement dual numbers with overloaded arithmetic and elementary functions.
- Formalize forward mode as JVP computation and reason about input and output costs.
- Obtain a full Jacobian with n passes or vectorized tangents.
- Compare operator overloading, tracing and code transformation.
- Nest forward derivatives with tagged perturbations to avoid perturbation confusion.
Before you start
Motivation: differentiating programs, not formulas
The preceding lesson covered three classic computer differentiation methods and their failures. Finite differences lose half or a third of digits to cancellation and require choosing a step. Symbolic differentiation is exact but needs a closed expression and, without sharing, a seven-iteration logistic-map derivative exceeded 2,000 operations. Complex step is exact to machine precision, but only for holomorphic functions and one directional derivative per complex evaluation.
Usually what you need is a program’s derivative:
- a loss looping through a batch with
for, applying ReLU (anif) and callinglogsumexp; - a Runge–Kutta integrator advancing a thousand steps, where you want the final state’s sensitivity to a parameter;
- Newton’s method with data-dependent iteration count inside a function you want to differentiate.
Writing those derivatives by hand is slow and a leading source of bugs caught by the gradient checker. Automatic differentiation (AD) solves the problem with an idea that seems obvious once seen: any numerical program, however complex, executes as elementary operations (sums, products, exp, sin…), each with a known derivative. Apply the chain rule to that concrete sequence using numbers rather than symbols.
The result is not an approximation: apart from rounding in the operations, AD gives the exact derivative of the executed program without step or growing intermediate expressions. Two traversal directions exist. This lesson builds forward mode, propagating derivatives in execution order; the next covers reverse mode, propagating backward and underpinning backpropagation. You will write a dual-number forward engine, validate it with lesson 13’s checker, use it to supply Newton an exact Jacobian without writing it by hand, and compute simulation sensitivity to parameters.
The evaluation trace
Use the function from Baydin, Pearlmutter, Radul and Siskind’s 2018 review as a running example:
A computer does not evaluate it all at once. Python decomposes it into elementary operations with intermediate results. Number them to obtain a list of assignments.
This notation, with inputs at nonpositive indices, is due to Griewank and Walther and also used by Baydin et al. For the example at :
| Variable | Definition | Value |
|---|---|---|
The output is . Three observations matter throughout:
- The trace depends on execution, not just program text. A 1,000-step loop appears unrolled into 1,000 instruction groups;
ifincludes only the executed branch. A program without data-dependent branches or loops always has the same trace; otherwise it changes with input. - Sharing is free. is used twice, in and , but is one variable. If appeared twice in an expression, a program computing it once and reusing it has one variable. This is the prior lesson’s tree-versus-graph distinction: the trace is a graph with shared subexpressions.
- Each instruction is small. Its partial derivatives are one-line formulas evaluated numerically.
Forward mode by hand
Suppose you want the derivative of with respect to . Associate each variable with its tangent . For inputs this is immediate: and . For each intermediate, applying the chain rule to one instruction gives
and because implies , all right-side tangents are computed by instruction . Traverse the trace in execution order, computing value and tangent at each instruction.
| Variable | Tangent | Value |
|---|---|---|
Thus , matching analytic derivative . Each instruction’s tangent needs only its arguments’ just-computed values (for example, in or in ) and their tangents. No row looks ahead or remembers old rows no longer used.
If instead of you seed any direction , the same recurrence computes , the directional derivative, because each row is linear in tangents. Seed yields the other partial, .
The figure illustrates three facts developed into theorems below. Primal values do not depend on the seed: only tangents change. Difference from central differences is around or , central-difference truncation and rounding error with , not AD error. In norm with expression sqrt(x1^2 + x2^2), the tangent of divides by : when , AD has a problem, discussed under nondifferentiable points.
Forward mode in general
Proof
For each , variable as a function of in that neighborhood is the composition of with functions , . Induct on in trace (topological) order: inputs are differentiable coordinates with . If all with are differentiable, is too by the chain rule, and
Take the dot product with : . This is the recurrence defining with the same initial condition , so for every . Outputs are rows of , hence , row of .
∎The stable-trace hypothesis matters. If the program has if x > 0, at with the trace is locally unchanged and the theorem applies; at it does not, and AD’s result may not be a derivative. We will return to this.
Dual numbers: the chain rule as algebra
Two handwritten columns work, but a beautiful algebraic trick lets the computer manage them: package value and tangent into one number.
Look at coefficients of : addition gives the sum rule and multiplication gives the product rule; division gives the quotient rule. Algebra differentiates for you. is not a field: with , so is a zero divisor and has no inverse. Clifford introduced dual numbers in 1873; one concrete representation uses matrices:
where matrix multiplication exactly reproduces dual multiplication, and says that nilpotent matrix squares to zero.
For non-polynomial functions we must define . The definition that makes everything work is
The final proof exercise asks you to check that this is not arbitrary: for polynomials algebra gives it, and for analytic functions their Taylor series gives it because eliminates all terms after the first derivative. It yields rules for elementary functions:
| Operation | Primal | Tangent |
|---|---|---|
| , if | ||
| , | , | , |
| , if | ||
| , constant | ||
| , both variable | differentiate as a composition, if |
The next theorem makes this a machine: composition behaves well.
Proof
, applying the definition to at dual . By the chain rule, , the coefficient of in . The claim for stages follows by induction.
∎Another view: is a point with velocity. acts on the pair as its differential acts on tangent vectors: point goes to and velocity to . A composition chains these transformations; the dual carries them without explicitly writing the chain rule.
Initially, at , : the first triangle’s vertical leg is , the second multiplies it by and the third by . Final tangent is . With at , slope is 0: the first vertical leg vanishes along with all later tangents, since each stage can only multiply what it receives.
Dual numbers and complex step
Compare the prior lesson’s complex step. It evaluated with and took : the term survives because , requiring a small (without subtraction it could be ). With that term vanishes by construction: no , no truncation, only operation rounding. Duals also do not require to be holomorphic: or are trivial to extend, while complex step requires manual adaptation.
JVP: cost, columns and vector tangents
The JVP theorem says one pass computes . In practice, cost and how to obtain more matter.
Cost of one pass. Count floating-point operations per instruction with the primal value already computed:
- sum or subtraction: 1 extra tangent operation;
- product : , 3 operations (two products and a sum);
- quotient : , 3 operations reusing ;
- elementary function : , a product plus computing , free for (it is ), one operation for , two for and , and another elementary function () for .
If each operation, including elementary functions, counts as one unit, no instruction with tangent costs more than four times its primal cost, so
in this model. In memory, each live variable stores two numbers rather than one, and can be forgotten once no later instruction uses it, as in ordinary evaluation. This is forward mode’s major advantage over reverse, which must retain the entire trace.
Jacobian by columns. With seed the JVP is column of . Thus passes with seeds give the full Jacobian at cost at most , regardless of . This is the same -column count as forward differences ( evaluations), but every column is exact.
Initially, for swirl with and , the secant with is the chord to the dashed curve’s endpoint and differs from by because the image curve bends. Reducing makes the separation fall as , the prior lesson’s forward-difference truncation error. The blue arrow lacks this error because there is no : it is the curve’s derivative, computed with dual algebra. Geometrically, the JVP maps domain tangent vectors to image tangent vectors; differential geometry calls it the pushforward or differential of at .
Vector tangents. A tangent need not be scalar. If each variable carries a vector of tangents, , the same recurrence propagates directions together: seed matrix yields in one pass. With it yields the full Jacobian. Tangent operations remain the same ( for a product instead of 3), but the primal value and are computed once instead of , and vector operations exploit vectorization. jax.jacfwd and torch.func.jacfwd do this by vectorizing JVP over identity columns.
Sparse Jacobians. If each output depends on few inputs, combine columns in one seed. When is tridiagonal, as in the Bratu discretization in Newton for systems, columns share no nonzero row: seed gives their sum in one pass, and without overlap each entry is recovered unambiguously. Three seeds suffice for any-size tridiagonal Jacobian. This is Curtis, Powell and Reid’s (1974) idea; selecting groups is a graph-coloring problem discussed under Jacobian computation strategies. Check it in the lab.
Lab 1: a dual-number forward-mode engine
An operator-overloading implementation fits in one cell. Each Dual stores val and tan; tangents can be scalars or NumPy arrays, so the same class propagates one or several directions. Three design decisions matter:
- Comparisons inspect the primal value.
x > 0with dualxcomparesx.val, so a program’siffollows the executed branch. float(x)raises an error instead of returningx.val. An accidental call tomath.sin(x)stops the program rather than silently discarding the tangent, the most treacherous operator-overloading AD bug.- Elementary functions dispatch by type.
sin(x)checks whetherxis dual; an object with its own_elementalmethod, like the later tracer, receives the call. This is the idea behind PyTorch__torch_function__or JAX tracers.
import math
import numpy as np
class Dual:
"""a + b·ε con ε² = 0. La tangente b es un float o un array de NumPy (varias direcciones a la vez)."""
__slots__ = ("val", "tan")
def __init__(self, val, tan=0.0):
self.val = val
self.tan = tan
# aritmética: el coeficiente de ε es la regla de derivación de cada operación
def __add__(self, o):
if isinstance(o, Dual):
return Dual(self.val + o.val, self.tan + o.tan)
return Dual(self.val + o, self.tan)
__radd__ = __add__
def __sub__(self, o):
if isinstance(o, Dual):
return Dual(self.val - o.val, self.tan - o.tan)
return Dual(self.val - o, self.tan)
def __rsub__(self, o):
return Dual(o - self.val, -self.tan)
def __neg__(self):
return Dual(-self.val, -self.tan)
def __mul__(self, o):
if isinstance(o, Dual):
return Dual(self.val * o.val, self.tan * o.val + self.val * o.tan)
return Dual(self.val * o, self.tan * o)
__rmul__ = __mul__
def __truediv__(self, o):
if isinstance(o, Dual):
w = self.val / o.val
return Dual(w, (self.tan - w * o.tan) / o.val)
return Dual(self.val / o, self.tan / o)
def __rtruediv__(self, o): # c / x
w = o / self.val
return Dual(w, -w * self.tan / self.val)
def __pow__(self, p):
if isinstance(p, Dual): # u^v = exp(v ln u), solo para u > 0
return exp(p * log(self))
if p == 0:
return Dual(1.0, 0.0 * self.tan)
return Dual(self.val ** p, p * self.val ** (p - 1) * self.tan)
def __rpow__(self, c): # c^x = exp(x ln c)
return exp(self * math.log(c))
# las ramas siguen la ejecución: se compara el valor primal
def _v(o):
return o.val if isinstance(o, Dual) else o
def __lt__(self, o): return self.val < Dual._v(o)
def __le__(self, o): return self.val <= Dual._v(o)
def __gt__(self, o): return self.val > Dual._v(o)
def __ge__(self, o): return self.val >= Dual._v(o)
def __eq__(self, o): return self.val == Dual._v(o)
__hash__ = None
def __float__(self):
raise TypeError("float() de un Dual perdería la tangente: usa x.val si de verdad la quieres tirar")
def __repr__(self):
return f"Dual({self.val!r}, {self.tan!r})"
def _elemental(nombre, f, df):
"""Extiende f a duales con f(a + bε) = f(a) + f'(a) b ε; acepta también arrays de objetos."""
def g(x):
if isinstance(x, Dual):
return Dual(f(x.val), df(x.val) * x.tan)
if isinstance(x, np.ndarray):
return np.array([g(xi) for xi in x.ravel()], dtype=object).reshape(x.shape)
if hasattr(x, "_elemental"): # otros tipos (el trazador) interceptan la llamada
return x._elemental(nombre)
return f(x)
g.__name__ = nombre
return g
exp = _elemental("exp", math.exp, math.exp)
log = _elemental("log", math.log, lambda a: 1.0 / a)
sin = _elemental("sin", math.sin, math.cos)
cos = _elemental("cos", math.cos, lambda a: -math.sin(a))
tanh = _elemental("tanh", math.tanh, lambda a: 1.0 - math.tanh(a) ** 2)
sqrt = _elemental("sqrt", math.sqrt, lambda a: 0.5 / math.sqrt(a) if a > 0 else math.inf)
def _partes(y, n=None):
"""Valores y tangentes de una salida escalar o vectorial (las constantes tienen tangente 0)."""
ys = list(y) if isinstance(y, (list, tuple, np.ndarray)) else [y]
val = np.array([yi.val if isinstance(yi, Dual) else float(yi) for yi in ys])
cero = 0.0 if n is None else np.zeros(n)
tan = np.array([yi.tan if isinstance(yi, Dual) else cero for yi in ys], dtype=float)
if not isinstance(y, (list, tuple, np.ndarray)):
return float(val[0]), (tan[0] if n is not None else float(tan[0]))
return val, tan
def jvp(f, x, v):
"""(f(x), J_f(x) v) con una sola evaluación de f sobre duales."""
x = np.asarray(x, dtype=float)
v = np.asarray(v, dtype=float)
xd = np.array([Dual(xi, vi) for xi, vi in zip(x, v)], dtype=object)
return _partes(f(xd))
def jacfwd(f):
"""Jacobiano completo en una pasada con tangentes vectoriales: semillas = columnas de I."""
def J(x):
x = np.asarray(x, dtype=float)
n = x.size
I = np.eye(n)
xd = np.array([Dual(x[j], I[j]) for j in range(n)], dtype=object)
_, T = _partes(f(xd), n)
return T # escalar: gradiente (n,); vectorial: jacobiano (m, n)
return J
# 1) el ejemplo de Baydin et al.
f = lambda x: log(x[0]) + x[0] * x[1] - sin(x[1])
print("f(2, 5) y df/dx1:", jvp(f, [2.0, 5.0], [1.0, 0.0]))
print("gradiente con jacfwd:", jacfwd(f)([2.0, 5.0]), " analítico:", [1 / 2 + 5, 2 - math.cos(5)])
# 2) un jacobiano R^3 -> R^2 frente al analítico
G = lambda x: [x[0] * x[1] * x[2], sin(x[0]) + x[1] ** 2 / x[2]]
x0 = np.array([0.7, -1.2, 2.0])
J_ana = np.array([[x0[1] * x0[2], x0[0] * x0[2], x0[0] * x0[1]],
[math.cos(x0[0]), 2 * x0[1] / x0[2], -x0[1] ** 2 / x0[2] ** 2]])
print("error del jacobiano 2x3:", np.max(np.abs(jacfwd(G)(x0) - J_ana)))The engine reproduces the table’s and other partial , and the Jacobian of at matches the analytic one to rounding. Now a real test: a structured function, parameter vector and lesson 13’s gradient checker (grad_check, its coding exercise solution copied here) as independent judge. The function is regularized logistic loss for 20 examples with 8 features, written with NumPy operations on object arrays: X @ w with w an array of duals calls overloaded + and *.
import numpy as np
def grad_check(f, grad_f, x, eps=None):
"""El verificador de la lección 13: máximo error relativo frente a diferencias centradas."""
x = np.asarray(x, dtype=float)
if eps is None:
eps = (3 * 2.0**-53) ** (1 / 3)
g = np.asarray(grad_f(x.copy()), dtype=float)
peor = 0.0
for j in range(x.size):
h = eps * max(1.0, abs(x[j]))
xp, xm = x.copy(), x.copy()
xp[j] += h
xm[j] -= h
num = (f(xp) - f(xm)) / (xp[j] - xm[j])
den = max(abs(g[j]), abs(num))
peor = max(peor, 0.0 if den == 0 else abs(g[j] - num) / den)
return peor
rng = np.random.default_rng(14)
X = rng.normal(size=(20, 8))
yb = np.where(rng.random(20) < 0.5, -1.0, 1.0)
LAM = 0.1
def perdida(w):
"""Logística regularizada; funciona igual con floats que con duales."""
z = X @ w # con duales: productos y sumas sobrecargados
terminos = [log(1 + exp(-yi * zi)) for yi, zi in zip(yb.tolist(), z)]
return sum(terminos) / len(yb) + 0.5 * LAM * (w @ w)
def grad_analitico(w):
z = X @ w
s = 1 / (1 + np.exp(yb * z)) # sigma(-y z)
return -(X.T @ (yb * s)) / len(yb) + LAM * w
w0 = rng.normal(size=8)
g_ad = jacfwd(perdida)(w0)
print("AD frente a la fórmula analítica:", np.max(np.abs(g_ad - grad_analitico(w0))))
print("verificador sobre el gradiente AD: ", f"{grad_check(perdida, jacfwd(perdida), w0):.1e}")
def grad_con_fallo(w): # olvida la regularización, como en la lección 13
return jacfwd(perdida)(w) - LAM * w
print("verificador sobre un gradiente roto:", f"{grad_check(perdida, grad_con_fallo, w0):.1e}")
# el error típico: math.sin en lugar del sin dual
try:
math.sin(Dual(0.3, 1.0))
except TypeError as e:
print("\nmath.sin(Dual):", e)The AD gradient matches the analytic formula to differences of order , and the checker gives relative error of order : central-difference error, not AD error. Omitting regularization gives worst-component relative error : with the missing term is comparable to the rest. math.sin on a dual stops with a message because __float__ raises, rather than returning a number without tangent.
Columns one at a time or all together
Both Jacobian methods perform the same tangent operations. The difference is elsewhere: scalar passes recompute primal values times and pay interpreter cost times per operation; one vector pass computes them once and handles tangents with NumPy operations on vectors of length .
import time
import numpy as np
def bratu_F(lam, n):
h = 1 / (n + 1)
def F(u):
up = np.concatenate([[0.0], u, [0.0]]) # con duales: array de objetos
return (-up[:-2] + 2 * up[1:-1] - up[2:]) / h**2 - lam * exp(u)
return F
def bratu_J(lam, n, u):
h = 1 / (n + 1)
return (np.diag(np.full(n, 2 / h**2)) - np.diag(np.full(n - 1, 1 / h**2), 1)
- np.diag(np.full(n - 1, 1 / h**2), -1) - lam * np.diag(np.exp(u)))
n = 40
F = bratu_F(3.0, n)
u = 0.3 * np.sin(np.pi * np.arange(1, n + 1) / (n + 1))
J_ref = bratu_J(3.0, n, u)
t0 = time.perf_counter()
J_cols = np.column_stack([jvp(F, u, np.eye(n)[j])[1] for j in range(n)])
t1 = time.perf_counter()
J_vec = jacfwd(F)(u)
t2 = time.perf_counter()
# compresión de Curtis, Powell y Reid: la columna j entra en la semilla j mod 3
S = np.zeros((n, 3))
S[np.arange(n), np.arange(n) % 3] = 1.0
ud = np.array([Dual(u[j], S[j]) for j in range(n)], dtype=object)
_, C = _partes(F(ud), 3) # n x 3: J S
J_col = np.zeros((n, n))
for i in range(n):
for j in range(max(0, i - 1), min(n, i + 2)):
J_col[i, j] = C[i, j % 3]
t3 = time.perf_counter()
print(f"n = {n}")
print(f"{n} pasadas escalares: error {np.max(np.abs(J_cols - J_ref)):.1e} {1e3 * (t1 - t0):6.1f} ms")
print(f"1 pasada vectorial: error {np.max(np.abs(J_vec - J_ref)):.1e} {1e3 * (t2 - t1):6.1f} ms")
print(f"3 colores: error {np.max(np.abs(J_col - J_ref)):.1e} {1e3 * (t3 - t2):6.1f} ms")
print(f"cociente escalares / vectorial: {(t1 - t0) / (t2 - t1):.1f}")All three give the exact tridiagonal Jacobian: error 0, not even rounding, because entries use sums and products of the same numbers as the analytic formula. The vector pass was 8–18 times faster than 40 scalar passes in two Pyodide checks (the cell prints your ratio; such short timings vary). The difference is Python interpreter work, not tangent operations: scalar passes execute each instruction 40 times including its primal value. Three colors obtain 118 nonzero entries with tangent length 3 instead of 40.
Branches, loops and nondifferentiable points
AD differentiates the executed trace. This handles programs symbolic tools cannot, but has consequences.
Loops. A loop unrolls in the trace, so AD traverses it without special handling even if iteration count depends on data. For Heron’s method for , , iterated until unchanged, the final tangent is the derivative of the last iterate with respect to . For contractive iterations such as this, iterate derivatives converge to the solution derivative (Gilbert, 1992 proved this for fixed-point iterations under contraction assumptions); when to differentiate the loop versus its defining equation is covered in the third AD lesson.
Branches. if on an intermediate selects a branch and the trace contains only that branch. Inside the region where a branch executes, the trace is locally unchanged and the JVP theorem applies. At the boundary it does not. An extreme example is
def f(x):
if x == 1.0:
return 1.0 # caso especial "optimizado"
return x * x
which as a mathematical function is for every (because ), with . AD at executes the first branch, a constant, and returns 0.
Nondifferentiable points. , and at have no derivative (or an infinite one). An implementation must return something: PyTorch and JAX give 0 for and ReLU at 0 (a subgradient), and infinity for . Composition is dangerous: norm at the origin computes with tangent 0, then multiplies by , which is NaN in IEEE 754.
import math
import numpy as np
# bucle con número de iteraciones que depende de los datos: Herón para sqrt(a)
def primal(z):
return z.val if isinstance(z, Dual) else z
def raiz(a, tol=1e-15):
x = a if a > 1 else 1.0 # comparación de un dual: usa su valor
for k in range(1, 100):
nuevo = 0.5 * (x + a / x)
if abs(primal(nuevo) - primal(x)) <= tol * primal(nuevo):
return nuevo, k
x = nuevo
return x, k
for a in [2.0, 50.0]:
r, it = raiz(Dual(a, 1.0))
print(f"a = {a:4}: {it} iteraciones d sqrt(a)/da por AD = {r.tan:.16f} exacta = {0.5 / math.sqrt(a):.16f}")
# una rama sobre un valor intermedio
def f_rama(x):
if x == 1.0:
return 1.0
return x * x
for x in [1.0, 1.0 + 2**-52]:
y = f_rama(Dual(x, 1.0))
print(f"x = {x!r}: tangente {y.tan if isinstance(y, Dual) else 0.0}")
# puntos no derivables
relu = lambda x: x if x > 0 else 0.0 * x
absd = lambda x: x if x >= 0 else -x
print("\nrelu'(0) por AD:", relu(Dual(0.0, 1.0)).tan, " |x|'(0) por AD:", absd(Dual(0.0, 1.0)).tan)
print("sqrt'(0) por AD:", sqrt(Dual(0.0, 1.0)).tan)
norma = lambda x: sqrt(x[0] * x[0] + x[1] * x[1])
print("norma en el origen, dirección e1:", jvp(norma, [0.0, 0.0], [1.0, 0.0]))
print("norma en (3, 4), dirección e1: ", jvp(norma, [3.0, 4.0], [1.0, 0.0]))Heron converges in 6 iterations for and 8 for , with tangents matching to every printed digit: variable loop length is no problem. Branch x == 1.0 gives tangent 0 at and at the next floating-point number, . The ReLU written with x > 0 gives 0 at the origin; absolute value with x >= 0 gives 1: branch authors decide behavior at nondifferentiable points and reasonable implementations disagree. Square root at 0 gives infinity and the norm at the origin NaN, although the norm has right directional derivative (no bilateral derivative because the left is , and no Jacobian). Libraries address this with custom rules: torch.linalg.norm defines its derivative at 0 as 0, as the PyTorch cell shows.
Nesting derivatives: duals of duals and perturbation confusion
If a dual carries a derivative, what happens if its primal and tangent are themselves duals? Take two distinct perturbations, and , with but . For a polynomial, expanding gives
because the term survives and all terms of degree 3 or higher contain or . The coefficient of is the second derivative. In practice no new type is needed: a dual in whose parts are duals in is exactly , and differentiating with duals a function that already differentiates with duals computes . This is nested forward mode: applying the derivative operator to a function that uses internally. Fike and Alonso’s hyperdual numbers (2011) are the same construction, presented as a type with four components.
For this to work, there is a condition hidden by the notation: each differentiation level needs its own . If there is only one, perturbations from different levels are added where they should not be. Siskind and Pearlmutter (2005) called this phenomenon perturbation confusion. A minimal example is
The inner derivative is 1 for any , so the outer one is . With a single , the outer derivative sets ; the inner sets , with the same ; then and the inner derivative comes out as 2 instead of 1, because it has counted the perturbation of as its own. The final result is 2.
The solution is to tag perturbations: each call to the derivative operator creates a new tag, each dual knows which tag its tangent belongs to, and the derivative at a level extracts only the tangent for its tag, treating the others as constants. With tags, , , , the inner derivative extracts the coefficient of , which is 1, and everything works.
import itertools
import math
# 1) la versión ingenua: una única ε para todos los niveles
def D_ingenua(f):
return lambda x: f(x + Dual(0.0, 1.0)).tan # x + ε, la misma ε siempre
print("ingenua: d/dx [x · d/dy (x + y)] =", D_ingenua(lambda x: x * D_ingenua(lambda y: x + y)(1.0))(1.0))
# 2) perturbaciones etiquetadas: val + tan·ε_etiqueta, con val y tan de etiquetas menores
_etiquetas = itertools.count(1)
class P:
__slots__ = ("val", "tan", "tag")
def __init__(self, val, tan, tag):
self.val, self.tan, self.tag = val, tan, tag
def __add__(self, o): return suma(self, o)
__radd__ = __add__
def __mul__(self, o): return producto(self, o)
__rmul__ = __mul__
def __sub__(self, o): return suma(self, producto(-1.0, o))
def __rsub__(self, o): return suma(o, producto(-1.0, self))
def _tag(a):
return a.tag if isinstance(a, P) else 0
def _respecto(a, t):
"""(primal, tangente) de a respecto a la perturbación t; si a no la contiene, es constante."""
if isinstance(a, P) and a.tag == t:
return a.val, a.tan
return a, 0.0
def suma(a, b):
t = max(_tag(a), _tag(b)) # la perturbación más reciente es la exterior
if t == 0:
return a + b
(a0, a1), (b0, b1) = _respecto(a, t), _respecto(b, t)
return P(suma(a0, b0), suma(a1, b1), t)
def producto(a, b):
t = max(_tag(a), _tag(b))
if t == 0:
return a * b
(a0, a1), (b0, b1) = _respecto(a, t), _respecto(b, t)
return P(producto(a0, b0), suma(producto(a1, b0), producto(a0, b1)), t)
def seno(a):
if not isinstance(a, P):
return math.sin(a)
return P(seno(a.val), producto(coseno(a.val), a.tan), a.tag)
def coseno(a):
if not isinstance(a, P):
return math.cos(a)
return P(coseno(a.val), producto(-1.0, producto(seno(a.val), a.tan)), a.tag)
def tangente(y, t):
if isinstance(y, P):
if y.tag == t:
return y.tan
if y.tag > t: # contiene perturbaciones más recientes: recorre sus partes
return P(tangente(y.val, t), tangente(y.tan, t), y.tag)
return 0.0
def D(f):
def df(x):
t = next(_etiquetas) # una etiqueta nueva por llamada
return tangente(f(P(x, 1.0, t)), t)
return df
print("etiquetada: d/dx [x · d/dy (x + y)] =", D(lambda x: x * D(lambda y: x + y)(1.0))(1.0))
# 3) derivadas de orden superior anidando D
cubo = lambda x: x * x * x
print("\nf(x) = x³ en 2: f'' =", D(D(cubo))(2.0), " f''' =", D(D(D(cubo)))(2.0))
for k, nombre in [(1, "sin'"), (2, "sin''"), (3, "sin'''"), (4, "sin''''")]:
g = seno
for _ in range(k):
g = D(g)
exacta = [math.cos, lambda z: -math.sin(z), lambda z: -math.cos(z), math.sin][k - 1](0.7)
print(f"{nombre:8s}(0.7) = {g(0.7): .16f} exacta {exacta: .16f}")The naive version gives 2 and the tagged version 1. With tags, nesting gives derivatives of any order: and for , and the first four derivatives of at agree with the exact values to every printed digit. The price is cost: nested levels carry components per number, because each level doubles them. For high derivatives of one variable there are better methods (truncated Taylor arithmetic, with quadratic cost in the order), and for Hessians of many variables forward and reverse are combined, as you will see in the third AD lesson.
Implementation strategies
The engine you wrote belongs to one of three families of AD tools. All three compute the same derivatives; they differ in when and to what the rules are applied, and those differences determine their speed, what they can differentiate and how easy they are to use. Together they are the AD implementation strategies.
- Operator overloading. A new type (
Dual) redefines operations, and the original program runs unchanged on it. The trace never exists as an object: it is traversed during execution. This is the simplest to write and differentiates any program that accepts the new type, including Python branches and loops. Its cost is that each operation pays for dynamic dispatch, and the derivative program cannot be optimized as a whole. PyTorch’s forward mode (torch.autograd.forward_ad), Python autograd and ForwardDiff.jl work this way. - Code transformation. A tool reads source code and writes another program in the same language that computes values and tangents. The result is compiled with the usual optimizer and runs almost as fast as handwritten code. This is the approach of Fortran and C tools such as ADIFOR and Tapenade (Hascoët and Pascual, 2013), widely used in computational fluid dynamics. The price is that the tool must understand the entire language: pointers, dynamic memory and library calls.
- Tracing to an intermediate representation. The program runs once with special objects (tracers) that, instead of computing, record each operation in a list: the Wengert trace as a data structure. The list is then transformed (to differentiate, vectorize or compile) and executed. This is what JAX does: its transformations (
jvp,vmap,grad) apply to the primitive operations recorded by the traced execution,jax.make_jaxpr(f)shows that trace (a jaxpr) andjax.jitcompiles it with XLA (Frostig, Johnson and Leary, 2018). It combines both advantages, but when tracing is abstract, as injit, tracers carry no values and Python control flow is resolved during tracing: anifon a traced value cannot be evaluated, which is why JAX has primitives such aslax.condandlax.while_loop.
The next cell does the latter two things in miniature. A tracer runs the function from Baydin et al. and records the Wengert list; a code generator transforms it into the text of a new Python function that computes value and tangent with floating-point statements, without duals.
import math
import time
class Traza:
def __init__(self):
self.instr = [] # (nombre, operación, argumentos)
def nueva(self, op, *args):
nombre = f"v{len(self.instr) + 1}"
self.instr.append((nombre, op, args))
return Var(self, nombre)
def _nom(o):
return o.nombre if isinstance(o, Var) else repr(float(o))
class Var:
"""Un tracer: no calcula nada, registra la operación en la traza."""
def __init__(self, traza, nombre):
self.traza, self.nombre = traza, nombre
def __add__(self, o): return self.traza.nueva("add", self.nombre, _nom(o))
def __radd__(self, o): return self.traza.nueva("add", _nom(o), self.nombre)
def __sub__(self, o): return self.traza.nueva("sub", self.nombre, _nom(o))
def __rsub__(self, o): return self.traza.nueva("sub", _nom(o), self.nombre)
def __mul__(self, o): return self.traza.nueva("mul", self.nombre, _nom(o))
def __rmul__(self, o): return self.traza.nueva("mul", _nom(o), self.nombre)
def __truediv__(self, o): return self.traza.nueva("div", self.nombre, _nom(o))
def _elemental(self, nombre): return self.traza.nueva(nombre, self.nombre)
def traza_de(f, nargs):
t = Traza()
entradas = [Var(t, f"x{i + 1}") for i in range(nargs)]
salida = f(*entradas) # las funciones exp, log, sin... despachan al tracer
return t, [e.nombre for e in entradas], salida.nombre
PRIMAL = {"add": "{0} + {1}", "sub": "{0} - {1}", "mul": "{0} * {1}", "div": "{0} / {1}",
"log": "math.log({0})", "exp": "math.exp({0})", "sin": "math.sin({0})", "cos": "math.cos({0})"}
def programa_tangente(traza, entradas, salida, nombre="f_jvp"):
"""Transformación de código: cada instrucción da una línea primal y otra tangente."""
d = lambda a: f"d{a}" if a[0] in "vx" else None # las constantes tienen tangente 0
lineas = [f"def {nombre}({', '.join(entradas + ['d' + e for e in entradas])}):"]
for v, op, args in traza.instr:
a, b = (args + (None,))[:2]
lineas.append(f" {v} = {PRIMAL[op].format(a, b)}")
da, db = d(a), (d(b) if b else None)
if op in ("add", "sub"):
s = "+" if op == "add" else "-"
partes = [p for p in [da, (f"{s} {db}" if db else None)] if p]
tan = " ".join(partes) if da else (f"-{db}" if op == "sub" else db)
elif op == "mul":
partes = [f"{da} * {b}" if da else None, f"{a} * {db}" if db else None]
tan = " + ".join(p for p in partes if p)
elif op == "div":
tan = f"({da or '0.0'} - {v} * {db}) / {b}" if db else f"{da} / {b}"
elif op == "log":
tan = f"{da} / {a}"
elif op == "exp":
tan = f"{v} * {da}"
elif op == "sin":
tan = f"math.cos({a}) * {da}"
elif op == "cos":
tan = f"-math.sin({a}) * {da}"
lineas.append(f" d{v} = {tan}")
lineas.append(f" return {salida}, d{salida}")
return "\n".join(lineas)
def f_baydin(x1, x2):
return log(x1) + x1 * x2 - sin(x2)
traza, entradas, salida = traza_de(f_baydin, 2)
print("traza registrada (lista de Wengert):")
for v, op, args in traza.instr:
print(f" {v} = {op}({', '.join(args)})")
codigo = programa_tangente(traza, entradas, salida)
print("\nprograma tangente generado:\n" + codigo)
espacio = {"math": math}
exec(codigo, espacio)
f_jvp = espacio["f_jvp"]
print("\nf_jvp(2, 5, 1, 0) =", f_jvp(2.0, 5.0, 1.0, 0.0))
# misma derivada, distinto coste por evaluación
N = 20000
t0 = time.perf_counter()
for _ in range(N):
f_jvp(2.0, 5.0, 1.0, 0.0)
t1 = time.perf_counter()
for _ in range(N):
f_baydin(Dual(2.0, 1.0), Dual(5.0, 0.0))
t2 = time.perf_counter()
print(f"código generado: {1e6 * (t1 - t0) / N:.2f} µs por JVP sobrecarga: {1e6 * (t2 - t1) / N:.2f} µs cociente {(t2 - t1) / (t1 - t0):.1f}")The tracer records five instructions, the same operations as in the table, because log(x1) and sin(x2) delegate the call to it and the operators of Var record theirs. The order is different: Python computes the sum before , so the sum is and the sine . It is another equally valid topological order of the same graph. The generated program is a Python function with ten floating-point statements that returns . In the Pyodide check it was about four times faster per JVP than the overloaded version (the cell prints the ratio for yours), because it creates no objects and dispatches no methods: the same advantage, at another scale, that Tapenade has over a C++ dual-number library. What the tracer cannot do is an if on x1: Var has no value, and comparing it makes no sense. This is JAX’s limitation with Python control flow, now seen from the inside.
Lab 2: automatic Newton and ODE sensitivities
Newton with an exact Jacobian without writing it
In the lesson on Newton for systems you solved the Bratu problem with the analytic Jacobian, the finite-difference Jacobian ( evaluations of per iteration and errors of in its entries), and Broyden’s method. With the dual-number engine, the exact Jacobian comes from itself, without writing a single derivative:
import numpy as np
from scipy.linalg import lu_factor, lu_solve
def newton_ad(F, x0, tol=1e-10, maxiter=50):
"""Newton para F(x) = 0 con el jacobiano exacto de la AD en modo forward."""
x = np.array(x0, dtype=float)
JF = jacfwd(F)
Fx = np.asarray(F(x), dtype=float)
hist = [np.linalg.norm(Fx)]
while hist[-1] > tol and len(hist) <= maxiter:
x = x + lu_solve(lu_factor(JF(x)), -Fx) # el jacobiano lo da la AD
Fx = np.asarray(F(x), dtype=float)
hist.append(np.linalg.norm(Fx))
return x, hist
n = 40
for lam in (1.0, 3.0, 3.5):
F = bratu_F(lam, n)
u, hist = newton_ad(F, np.zeros(n))
print(f"lambda = {lam}: {len(hist) - 1} iteraciones max u = {u.max():.6f} "
f"|F|: {' '.join(f'{v:.0e}' for v in hist)}")
# el jacobiano de la AD en la solución frente al analítico
print("error del jacobiano en la solución:", np.max(np.abs(jacfwd(F)(u) - bratu_J(3.5, n, u))))The iterations (3, 5 and 7) and residuals match Newton with the analytic Jacobian in lesson 8: the same solution (with for ), the same signature of quadratic convergence in which the residual’s exponent doubles at each step, and a Jacobian that exactly matches the analytic one. What has changed is what you had to write: only . The cost is that of the Jacobian by columns: with tangents of length 40, one vector pass per iteration; with three colors, one pass with tangents of length 3.
Sensitivity of a simulation to its parameters
The Lotka–Volterra predator–prey model,
with the prey and the predators, has four parameters . The typical question in an ODE sensitivity analysis is how much the state at time changes when each parameter is varied: the matrix .
With forward mode nothing needs to be derived: run the Runge–Kutta integrator from lesson 12 without changing a line, with the parameters converted to duals whose tangents are the columns of . Every number in the integrator then carries its four derivatives, and the final state carries in its tangents. The cost is one vector pass with 4 tangents: forward mode in its element, with few inputs and a long program.
import numpy as np
def lotka_volterra(t, z, th):
x, y = z
a, b, c, d = th
return [a * x - b * x * y, d * x * y - c * y]
def rk4(f, z0, th, T, N):
"""RK4 clásico con listas: funciona igual con floats que con duales."""
h = T / N
z = list(z0)
t = 0.0
for _ in range(N):
k1 = f(t, z, th)
k2 = f(t + h / 2, [zi + h / 2 * ki for zi, ki in zip(z, k1)], th)
k3 = f(t + h / 2, [zi + h / 2 * ki for zi, ki in zip(z, k2)], th)
k4 = f(t + h, [zi + h * ki for zi, ki in zip(z, k3)], th)
z = [zi + h / 6 * (p + 2 * q + 2 * r + s) for zi, p, q, r, s in zip(z, k1, k2, k3, k4)]
t += h
return z
th0 = np.array([1.0, 0.1, 1.5, 0.075]) # alfa, beta, gamma, delta
z0, T, N = [10.0, 5.0], 10.0, 1000
thd = [Dual(th0[j], np.eye(4)[j]) for j in range(4)]
zT = rk4(lotka_volterra, z0, thd, T, N)
S_ad = np.array([zi.tan for zi in zT])
print("estado en T = 10:", [round(float(zi.val), 6) for zi in zT])
print("S(T) = d(x, y)/d(alfa, beta, gamma, delta):")
print(np.array2string(S_ad, precision=4, suppress_small=False))
print("\ndiferencias centradas sobre el mismo integrador (h relativo a cada parámetro):")
for hfd in [1e-2, 1e-4, 1e-6, 1e-8]:
S_fd = np.zeros((2, 4))
for j in range(4):
e = np.zeros(4)
e[j] = hfd * th0[j]
zp = rk4(lotka_volterra, z0, th0 + e, T, N)
zm = rk4(lotka_volterra, z0, th0 - e, T, N)
S_fd[:, j] = (np.array(zp) - np.array(zm)) / (2 * e[j])
print(f" h = {hfd:.0e}: máximo error relativo {np.max(np.abs(S_fd - S_ad) / np.abs(S_ad)):.1e}")The sensitivity matrix comes from one run of the integrator. Its entries vary by more than three orders of magnitude: and . Some are so large because this is an oscillating system: changing a parameter generally changes the orbit’s period, the phase difference between the original and perturbed orbits grows over time, and the state at a fixed time is increasingly affected. Centered differences repeat the story of lesson 13: with truncation dominates and the relative error is 1.7%; it falls as (a factor when going to ) to a minimum of with , and rises again to with , when rounding wins. AD does not have to choose .
Differentiating the simulation versus ODE sensitivity
There is a subtlety. AD computes the derivative of the program: of the state produced by RK4 with steps, not of the exact ODE solution. The two differ, solely because of discretization. To check this, the exact ODE sensitivity satisfies the variational equations: if , differentiation with respect to gives
a linear system of 8 additional equations, which we solve with solve_ivp at a very fine tolerance as a reference.
import numpy as np
from scipy.integrate import solve_ivp
def aumentado(t, w, th):
x, y = w[:2]
a, b, c, d = th
S = w[2:].reshape(2, 4)
fz = np.array([[a - b * y, -b * x], [d * y, d * x - c]])
fth = np.array([[x, -x * y, 0.0, 0.0], [0.0, 0.0, -y, x * y]])
return np.concatenate([[a * x - b * x * y, d * x * y - c * y], (fz @ S + fth).ravel()])
ref = solve_ivp(aumentado, (0, T), np.concatenate([z0, np.zeros(8)]), args=(th0,),
method="DOP853", rtol=1e-13, atol=1e-13)
S_ode = ref.y[2:, -1].reshape(2, 4)
errores = []
for NN in [125, 250, 500, 1000]:
zN = rk4(lotka_volterra, z0, [Dual(th0[j], np.eye(4)[j]) for j in range(4)], T, NN)
S_N = np.array([zi.tan for zi in zN])
errores.append(np.max(np.abs(S_N - S_ode)) / np.max(np.abs(S_ode)))
cociente = "" if len(errores) == 1 else f" cociente con el anterior: {errores[-2] / errores[-1]:.1f}"
print(f"N = {NN:5d}: |S_AD - S_EDO| / |S_EDO| = {errores[-1]:.1e}{cociente}")When doubles, the relative difference between the program derivative and the exact sensitivity is divided by a factor close to 16: it is , the order of RK4. This is no coincidence. RK4 applied to the ODE is a smooth function of , and its derivative agrees with what would be obtained by applying the same RK4 scheme to the system augmented with the variational equations (Runge–Kutta methods commute with linearization), which converges at the same order. The practical lesson: AD gives the exact derivative of the approximation, exactly what you need to optimize the program you actually run, and it approaches the ODE’s derivative as fast as the solution itself. When differentiating the discrete method and discretizing the continuous derivative equation give different things, and which is preferable, is the subject of discrete and continuous adjoints.
In libraries
PyTorch has two interfaces for forward mode. torch.func.jvp(f, primals, tangents) is the functional one, in the style of JAX: it returns the value and the JVP. torch.autograd.forward_ad is the low-level one, with explicit duals: inside an dual_level, make_dual(x, t) creates a dual tensor and unpack_dual(y) splits it into primal and tangent. torch.func.jacfwd(f) vectorizes the JVP over the columns of the identity. The cell runs locally on the CPU because Pyodide does not have PyTorch.
import math
import torch
import torch.autograd.forward_ad as fwAD
from torch.func import jvp, jacfwd
torch.set_default_dtype(torch.float64)
def f(x):
return torch.log(x[0]) + x[0] * x[1] - torch.sin(x[1])
x = torch.tensor([2.0, 5.0])
y, dy = jvp(f, (x,), (torch.tensor([1.0, 0.0]),))
print("torch.func.jvp:", y.item(), dy.item())
print("torch.func.jacfwd:", jacfwd(f)(x).tolist(), " analítico:", [0.5 + 5, 2 - math.cos(5)])
with fwAD.dual_level():
xd = fwAD.make_dual(x, torch.tensor([0.0, 1.0]))
yd = f(xd)
print("forward_ad, semilla e2:", fwAD.unpack_dual(yd).tangent.item())
# Bratu: jacobiano con jacfwd frente al analítico
n, lam = 40, 3.0
h = 1 / (n + 1)
def F(u):
up = torch.cat([torch.zeros(1), u, torch.zeros(1)])
return (-up[:-2] + 2 * up[1:-1] - up[2:]) / h**2 - lam * torch.exp(u)
u = 0.3 * torch.sin(math.pi * torch.arange(1, n + 1) / (n + 1))
J = jacfwd(F)(u)
J_ref = (torch.diag(torch.full((n,), 2 / h**2)) - torch.diag(torch.full((n - 1,), 1 / h**2), 1)
- torch.diag(torch.full((n - 1,), 1 / h**2), -1) - lam * torch.diag(torch.exp(u)))
print("Bratu, error de jacfwd:", (J - J_ref).abs().max().item())
# puntos no derivables: lo que deciden las reglas de PyTorch
cero, uno = torch.tensor(0.0), torch.tensor(1.0)
for g in (torch.abs, torch.relu, torch.sqrt):
print(f"{g.__name__:5s}: tangente en 0 = {jvp(g, (cero,), (uno,))[1].item()}")
e1 = torch.tensor([1.0, 0.0])
print("sqrt(x1² + x2²) en el origen:", jvp(lambda v: torch.sqrt((v * v).sum()), (torch.zeros(2),), (e1,))[1].item())
print("torch.linalg.norm en el origen:", jvp(torch.linalg.norm, (torch.zeros(2),), (e1,))[1].item())npm run lab and open the connection link.PyTorch reproduces the example’s and and the Bratu Jacobian. The tangents at 0 match those of the custom engine except for absolute value: PyTorch gives 0 for (it uses ) and for ReLU, infinity for and NaN for the handwritten norm, while torch.linalg.norm has its own rule and returns 0. In JAX, the reference for this functional style, the equivalent call is jax.jvp(f, (x,), (v,)), and jax.jacfwd is built with vmap over jvp:
import jax, jax.numpy as jnp
f = lambda x: jnp.log(x[0]) + x[0] * x[1] - jnp.sin(x[1])
y, dy = jax.jvp(f, (jnp.array([2.0, 5.0]),), (jnp.array([1.0, 0.0]),))
J = jax.jacfwd(f)(jnp.array([2.0, 5.0]))
print(jax.make_jaxpr(f)(jnp.array([2.0, 5.0]))) # la traza registrada
Common mistakes
Exercises
def f(x): return 1.0 if x == 1.0 else x * x to save a product. What does forward mode with seed 1 return at and at ?while loop whose condition depends on an intermediate value (for example, iterating until a residual falls below a tolerance). Which statement is correct?Step 1 of 4. How do you begin for a polynomial?
Dual(val, tan) class with +, -, *, / (with duals and numbers on either side), unary minus and the power x ** p with p a number, and the functions exp, log, sin, cos that accept duals or numbers. The tests differentiate compositions with random seeds and compare them with analytic derivatives.import math
class Dual:
def __init__(self, val, tan=0.0):
self.val = val
self.tan = tan
def __add__(self, o):
o = o if isinstance(o, Dual) else Dual(o)
return Dual(self.val + o.val, self.tan + o.tan)
__radd__ = __add__
# tu código: __sub__, __rsub__, __neg__, __mul__, __rmul__,
# __truediv__, __rtruediv__, __pow__
def exp(x):
return math.exp(x) # tu código: que acepte duales
def log(x):
return math.log(x)
def sin(x):
return math.sin(x)
def cos(x):
return math.cos(x)Connections and reading
For further reading: section 3 of Baydin et al. (2018) presents both modes with the same example; chapters 2 to 4 of Griewank and Walther (2008) formalize the trace, tangent mode and its cost analysis; Blondel and Roulet (2024) explain it from the standpoint of differentiable programming; and Siskind and Pearlmutter (2005) explain perturbation confusion and why tags must be dynamic.
Summary
- The evaluation trace (Wengert list) is the sequence of elementary operations executed by the program; it forms an acyclic graph with shared subexpressions and depends on the particular execution.
- Duals perform the chain rule automatically: , consistent with polynomials, series and compositions.
- One pass gives a JVP for at most about 4 times the cost of and without storing the trace. The full Jacobian costs passes (one with vector tangents), and fewer if it is sparse. Hence forward is for few inputs and reverse for few outputs.
- AD differentiates the executed program: it traverses loops, follows the branch taken and, at nondifferentiable points, returns whatever the rule specifies (0, infinity or NaN).
- Nesting derivatives requires a distinct perturbation per level; without tags, perturbation confusion arises.
- Operator overloading, code transformation and tracing compute the same thing and differ in speed, supported control flow and what must be rewritten.