Module contents
Lesson 14 of 26Core 90 min

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 (an if) and calling logsumexp;
  • 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 hh 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:

f(x1,x2)=ln⁡x1+x1x2−sin⁡x2.f(x_1, x_2) = \ln x_1 + x_1 x_2 - \sin x_2 .

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 (x1,x2)=(2,5)(x_1, x_2) = (2, 5):

VariableDefinitionValue
v−1v_{-1}x1x_122
v0v_0x2x_255
v1v_1ln⁡v−1\ln v_{-1}0.6931470.693147
v2v_2v−1⋅v0v_{-1} \cdot v_01010
v3v_3sin⁡v0\sin v_0−0.958924-0.958924
v4v_4v1+v2v_1 + v_210.69314710.693147
v5v_5v4−v3v_4 - v_311.65207111.652071

The output is y=v5≈11.652y = v_5 \approx 11.652. Three observations matter throughout:

  1. The trace depends on execution, not just program text. A 1,000-step loop appears unrolled into 1,000 instruction groups; if includes only the executed branch. A program without data-dependent branches or loops always has the same trace; otherwise it changes with input.
  2. Sharing is free. x1x_1 is used twice, in v1v_1 and v2v_2, but is one variable. If x1x2x_1 x_2 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.
  3. Each instruction is small. Its partial derivatives ∂φi/∂vj\partial\varphi_i/\partial v_j are one-line formulas evaluated numerically.

Forward mode by hand

Suppose you want the derivative of yy with respect to x1x_1. Associate each variable viv_i with its tangent v˙i=∂vi/∂x1\dot v_i = \partial v_i / \partial x_1. For inputs this is immediate: v˙−1=1\dot v_{-1} = 1 and v˙0=0\dot v_0 = 0. For each intermediate, applying the chain rule to one instruction gives

v˙i=∑j≺i∂φi∂vj v˙j,\dot v_i = \sum_{j \prec i} \frac{\partial \varphi_i}{\partial v_j}\,\dot v_j ,

and because j≺ij \prec i implies j<ij < i, all right-side tangents are computed by instruction ii. Traverse the trace in execution order, computing value and tangent at each instruction.

VariableTangentValue
v˙−1\dot v_{-1}x˙1\dot x_111
v˙0\dot v_0x˙2\dot x_200
v˙1\dot v_1v˙−1/v−1\dot v_{-1} / v_{-1}0.50.5
v˙2\dot v_2v˙−1v0+v−1v˙0\dot v_{-1} v_0 + v_{-1} \dot v_055
v˙3\dot v_3cos⁡(v0) v˙0\cos(v_0)\, \dot v_000
v˙4\dot v_4v˙1+v˙2\dot v_1 + \dot v_25.55.5
v˙5\dot v_5v˙4−v˙3\dot v_4 - \dot v_35.55.5

Thus ∂f/∂x1(2,5)=5.5\partial f/\partial x_1 (2, 5) = 5.5, matching analytic derivative 1/x1+x2=0.5+51/x_1 + x_2 = 0.5 + 5. Each instruction’s tangent needs only its arguments’ just-computed values (for example, v0v_0 in v˙2\dot v_2 or cos⁡v0\cos v_0 in v˙3\dot v_3) and their tangents. No row looks ahead or remembers old rows no longer used.

If instead of (x˙1,x˙2)=(1,0)(\dot x_1, \dot x_2) = (1, 0) you seed any direction (x˙1,x˙2)(\dot x_1, \dot x_2), the same recurrence computes y˙=∂f∂x1x˙1+∂f∂x2x˙2\dot y = \frac{\partial f}{\partial x_1}\dot x_1 + \frac{\partial f}{\partial x_2}\dot x_2, the directional derivative, because each row is linear in tangents. Seed (0,1)(0, 1) yields the other partial, x1−cos⁡x2=1.716338x_1 - \cos x_2 = 1.716338.

InteractiveThe forward Wengert tape
x₁v₋₁2.000 1.000x₂v₀5.000 0.000lnv₁×v₂sinv₃+v₄−v₅
VariablePrimal valueTangent
v−1v_{-1}=x1= x_12.0000v˙−1=x˙1\dot v_{-1} = \dot x_11.0000
v0v_{0}=x2= x_25.0000v˙0=x˙2\dot v_{0} = \dot x_20.0000
v1v_{1}=ln⁡v−1= \ln v_{-1}·v˙1=v˙−1/v−1\dot v_{1} = \dot v_{-1} / v_{-1}·
v2v_{2}=v−1⋅v0= v_{-1} \cdot v_{0}·v˙2=v˙−1 v0+v−1 v˙0\dot v_{2} = \dot v_{-1}\,v_{0} + v_{-1}\,\dot v_{0}·
v3v_{3}=sin⁡v0= \sin v_{0}·v˙3=cos⁡(v0) v˙0\dot v_{3} = \cos(v_{0})\,\dot v_{0}·
v4v_{4}=v1+v2= v_{1} + v_{2}·v˙4=v˙1+v˙2\dot v_{4} = \dot v_{1} + \dot v_{2}·
v5v_{5}=v4−v3= v_{4} - v_{3}·v˙5=v˙4−v˙3\dot v_{5} = \dot v_{4} - \dot v_{3}·
Output: y = v₅, ẏ = v̇₅.
Function
Point and direction
2.0
5.0
Seed (x˙1,x˙2)(\dot x_1, \dot x_2)
inputs
y=f(x1,x2)y = f(x_1, x_2)…
y˙=∇f⋅x˙\dot y = \nabla f \cdot \dot{\vb{x}} (forward mode)…
Central differences, h=10−5h = 10^{-5}5.5000000000
Difference between the two…
Above is the expression's computation graph, inputs at left and each column a depth; below each node are its value and, in orange, tangent. Below is the trace as a table. Each instruction computes value and tangent together using its operation's derivative rule; incoming edges to the current node light up as the only data needed. Initial state is halfway through Baydin et al.'s example. Continue to the end and compare y˙\dot y with central differences; then change the seed to (0,1)(0, 1) and replay: which column changes? Try the shared subexpression where x1x2x_1 x_2 is one node used twice, and write your own expressions.

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 10−1010^{-10} or 10−1110^{-11}, central-difference truncation and rounding error with h=10−5h = 10^{-5}, not AD error. In norm x12+x22\sqrt{x_1^2 + x_2^2} with expression sqrt(x1^2 + x2^2), the tangent of v3=v2v_3 = \sqrt{v_2} divides by 2v32v_3: when v3=0v_3 = 0, AD has a problem, discussed under nondifferentiable points.

Forward mode in general

Proof

For each ii, variable viv_i as a function of x\vb{x} in that neighborhood is the composition of φi\varphi_i with functions x↦vj\vb{x} \mapsto v_j, j≺ij \prec i. Induct on ii in trace (topological) order: inputs are differentiable coordinates with ∇vk−n=ek\nabla v_{k-n} = \vb{e}_k. If all vjv_j with j<ij < i are differentiable, viv_i is too by the chain rule, and

∇vi(x)=∑j≺i∂φi∂vj ∇vj(x).\nabla v_i(\vb{x}) = \sum_{j\prec i} \frac{\partial\varphi_i}{\partial v_j}\,\nabla v_j(\vb{x}).

Take the dot product with x˙\dot{\vb{x}}: ∇vi⋅x˙=∑j≺i∂φi∂vj (∇vj⋅x˙)\nabla v_i \cdot \dot{\vb{x}} = \sum_{j \prec i} \frac{\partial\varphi_i}{\partial v_j}\,(\nabla v_j\cdot\dot{\vb{x}}). This is the recurrence defining v˙i\dot v_i with the same initial condition ∇vk−n⋅x˙=x˙k\nabla v_{k-n}\cdot\dot{\vb{x}} = \dot x_k, so v˙i=∇vi(x)⋅x˙\dot v_i = \nabla v_i(\vb{x})\cdot\dot{\vb{x}} for every ii. Outputs are rows of FF, hence y˙r=∇Fr(x)⋅x˙\dot y_r = \nabla F_r(\vb{x})\cdot\dot{\vb{x}}, row rr of JFx˙\mat{J}_F\dot{\vb{x}}.

∎

The stable-trace hypothesis matters. If the program has if x > 0, at x\vb{x} with x>0x > 0 the trace is locally unchanged and the theorem applies; at x=0x = 0 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 ε\eps: addition gives the sum rule and multiplication ad+bcad + bc gives the product rule; division gives the quotient rule. Algebra differentiates for you. D\mathbb{D} is not a field: ε⋅ε=0\eps \cdot \eps = 0 with ε≠0\eps \neq 0, so ε\eps is a zero divisor and bεb\eps has no inverse. Clifford introduced dual numbers in 1873; one concrete representation uses matrices:

a+bε  ⟷  [ab0a],ε  ⟷  [0100],a + b\eps \;\longleftrightarrow\; \begin{bmatrix} a & b \\ 0 & a \end{bmatrix}, \qquad \eps \;\longleftrightarrow\; \begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix},

where matrix multiplication exactly reproduces dual multiplication, and ε2=0\eps^2 = 0 says that nilpotent matrix squares to zero.

For non-polynomial functions we must define f(a+bε)f(a + b\eps). The definition that makes everything work is

f(a+bε)=f(a)+f′(a) b ε,f(a + b\eps) = f(a) + f'(a)\,b\,\eps ,

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 ε2=0\eps^2 = 0 eliminates all terms after the first derivative. It yields rules for elementary functions:

OperationPrimalTangent
eue^{u}w=eaw = e^{a}w bw\,b
ln⁡u\ln uln⁡a\ln ab/ab / a, if a>0a > 0
sin⁡u\sin u, cos⁡u\cos usin⁡a\sin a, cos⁡a\cos acos⁡(a) b\cos(a)\,b,   −sin⁡(a) b\;-\sin(a)\,b
tanh⁡u\tanh uw=tanh⁡aw = \tanh a(1−w2) b(1 - w^2)\,b
u\sqrt{u}w=aw = \sqrt{a}b/(2w)b / (2w), if a>0a > 0
upu^p, constant ppapa^pp ap−1 bp\,a^{p-1}\,b
uvu^v, both variableevln⁡ue^{v\ln u}differentiate as a composition, if a>0a > 0

The next theorem makes this a machine: composition behaves well.

Proof

g(f(a+bε))=g(f(a)+f′(a)bε)=g(f(a))+g′(f(a)) f′(a) b εg(f(a + b\eps)) = g\big(f(a) + f'(a)b\eps\big) = g(f(a)) + g'(f(a))\,f'(a)\,b\,\eps, applying the definition to gg at dual f(a)+[f′(a)b]εf(a) + [f'(a)b]\eps. By the chain rule, g′(f(a))f′(a)=(g∘f)′(a)g'(f(a))f'(a) = (g\circ f)'(a), the coefficient of ε\eps in (g∘f)(a+bε)(g\circ f)(a + b\eps). The claim for kk stages follows by induction.

∎

Another view: a+bεa + b\eps is a point with velocity. ff acts on the pair as its differential acts on tangent vectors: point aa goes to f(a)f(a) and velocity bb to f′(a)bf'(a)b. A composition chains these transformations; the dual carries them without explicitly writing the chain rule.

InteractiveA dual number as point and tangent
Stage 1: u1=sin⁡xu_1 = \sin x
1.000 + 1.000ε ↦ 0.841 + 0.540ε
slope g′(u) = 0.540
Stage 2: u2=eu1u_2 = e^{u_1}
0.841 + 0.540ε ↦ 2.320 + 1.253ε
slope g′(u) = 2.320
Stage 3: u3=u22u_3 = u_2^2
2.320 + 1.253ε ↦ 5.381 + 5.815ε
slope g′(u) = 4.640
Composition
Input dual
1.00
1.00
F(x)=(esin⁡x)2F(x) = (e^{\sin x})^2
F(a+bε)F(a + b\varepsilon)5.381 + 5.815 ε
Chain rule: b⋅∏kgk′(uk−1)b \cdot \prod_k g_k'(u_{k-1})5.815
Central differences of FF in direction bb5.815
Each panel is a stage of F=g3∘g2∘g1F = g_3\circ g_2\circ g_1. Incoming dual u+u˙ εu + \dot u\,\eps is drawn as point (u,g(u))(u, g(u)) and a slope triangle: horizontal leg is incoming tangent u˙\dot u, vertical leg is outgoing g′(u) u˙g'(u)\,\dot u. One stage's vertical leg reappears in the same color as the next horizontal leg. Drag aa or the orange leg tip: triangles change together and final tangent matches product b∏kgk′b\prod_k g_k' and central differences. Try g1=cos⁡g_1 = \cos at a=0a = 0: what happens to tangents in later stages?

Initially, F(x)=(esin⁡x)2F(x) = (e^{\sin x})^2 at a=1a = 1, b=1b = 1: the first triangle’s vertical leg is cos⁡1=0.540\cos 1 = 0.540, the second multiplies it by esin⁡1=2.320e^{\sin 1} = 2.320 and the third by 2u2=4.6402u_2 = 4.640. Final tangent 5.8155.815 is F′(1)F'(1). With g1=cos⁡g_1 = \cos at a=0a = 0, 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 f(x+ih)f(x + ih) with i2=−1i^2 = -1 and took Im⁡f(x+ih)/h=f′(x)−f′′′(x)h2/6+⋯\operatorname{Im} f(x + ih)/h = f'(x) - f'''(x)h^2/6 + \cdots: the h2h^2 term survives because i2≠0i^2 \neq 0, requiring a small hh (without subtraction it could be 10−2010^{-20}). With ε2=0\eps^2 = 0 that term vanishes by construction: no hh, no truncation, only operation rounding. Duals also do not require ff to be holomorphic: ∣x∣\abs{x} or max⁡(x,0)\max(x, 0) are trivial to extend, while complex step requires manual adaptation.

JVP: cost, columns and vector tangents

The JVP theorem says one pass computes JF(x)x˙\mat{J}_F(\vb{x})\dot{\vb{x}}. 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 w=uvw = uv: w˙=u˙v+uv˙\dot w = \dot u v + u\dot v, 3 operations (two products and a sum);
  • quotient w=u/vw = u/v: w˙=(u˙−wv˙)/v\dot w = (\dot u - w\dot v)/v, 3 operations reusing ww;
  • elementary function w=φ(u)w = \varphi(u): w˙=φ′(u)u˙\dot w = \varphi'(u)\dot u, a product plus computing φ′(u)\varphi'(u), free for exp⁡\exp (it is ww), one operation for ln⁡\ln, two for tanh⁡\tanh and ⋅\sqrt{\cdot}, and another elementary function (cos⁡\cos) for sin⁡\sin.

If each operation, including elementary functions, counts as one unit, no instruction with tangent costs more than four times its primal cost, so

coste⁡(F,JFx˙)≤4 coste⁡(F)\operatorname{coste}\big(F, \mat{J}_F\dot{\vb{x}}\big) \le 4\,\operatorname{coste}(F)

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 x˙=ej\dot{\vb{x}} = \vb{e}_j the JVP is column jj of JF\mat{J}_F. Thus nn passes with seeds e1,…,en\vb{e}_1, \dots, \vb{e}_n give the full Jacobian at cost at most 4n coste⁡(F)4n\,\operatorname{coste}(F), regardless of mm. This is the same nn-column count as forward differences (n+1n + 1 evaluations), but every column is exact.

InteractiveJVP pushes vectors forward
Domain: p\vb{p} and direction v\vb{v}
Image: F(p)F(\vb{p}) and pushed-forward vector J(p)v\mat{J}(\vb{p})\vb{v}
  • v\vb{v} and its image Jv\mat{J}\vb{v}
  • line p+tv\vb{p} + t\vb{v} and curve F(p+tv)F(\vb{p} + t\vb{v}), ∣t∣≤1\abs{t} \le 1
  • secant with step hh
  • grid and its image
Map
Secant
1.00
Jacobian columns
F(x,y)=(x+0.5sin⁡y,  y+0.5 x2−0.5)F(x, y) = \big(x + 0.5\sin y,\; y + 0.5\,x^2 - 0.5\big)
v\vb{v}(0.900, 0.200)
J(p)v\mat{J}(\vb{p})\vb{v} (one dual pass)(0.9921, 0.9200)
Secant (F(p+hv)−F(p))/h(F(\vb{p} + h\vb{v}) - F(\vb{p}))/h(0.9876, 1.3250)
∥secant−Jv∥\norm{\text{secant} - \mat{J}\vb{v}}0.4050
J(p)=[????]\mat{J}(\vb{p}) = \begin{bmatrix} ? & ? \\ ? & ? \end{bmatrix}
columns recorded with seeds e₁ and e₂
At left, the domain grid, point p\vb{p} and direction v\vb{v}; at right, the grid deformed by FF, point F(p)F(\vb{p}) and dashed curve t↦F(p+tv)t\mapsto F(\vb{p} + t\vb{v}). The blue arrow at right is J(p)v\mat{J}(\vb{p})\vb{v}, computed with one evaluation of FF on duals: the image curve's velocity at t=0t = 0, tangent to it. The red arrow is the secant with step hh; lower hh and watch it approach blue. Select v=e1\vb{v} = \vb{e}_1 and v=e2\vb{v} = \vb{e}_2: each pass records one Jacobian column. In polar coordinates, which column depends on rr?

Initially, for swirl F(x,y)=(x+0.5sin⁡y, y+0.5x2−0.5)F(x, y) = (x + 0.5\sin y,\ y + 0.5x^2 - 0.5) with p=(0.8,0.4)\vb{p} = (0.8, 0.4) and v=(0.9,0.2)\vb{v} = (0.9, 0.2), the secant with h=1h = 1 is the chord to the dashed curve’s endpoint and differs from Jv=(0.992,0.920)\mat{J}\vb{v} = (0.992, 0.920) by 0.410.41 because the image curve bends. Reducing hh makes the separation fall as O(h)\bigO(h), the prior lesson’s forward-difference truncation error. The blue arrow lacks this error because there is no hh: 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 FF at p\vb{p}.

Vector tangents. A tangent need not be scalar. If each variable carries a vector of pp tangents, v˙i∈Rp\dot v_i \in \R^p, the same recurrence propagates pp directions together: seed matrix S=[x˙1⋯x˙p]∈Rn×p\mat{S} = [\dot{\vb{x}}_1 \cdots \dot{\vb{x}}_p] \in \R^{n\times p} yields JFS\mat{J}_F\mat{S} in one pass. With S=In\mat{S} = \mat{I}_n it yields the full Jacobian. Tangent operations remain the same (3p3p for a product instead of 3), but the primal value and φ′(u)\varphi'(u) are computed once instead of nn, 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 J\mat{J} is tridiagonal, as in the Bratu discretization in Newton for systems, columns 1,4,7,…1, 4, 7, \dots share no nonzero row: seed e1+e4+e7+⋯\vb{e}_1 + \vb{e}_4 + \vb{e}_7 + \cdots 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 > 0 with dual x compares x.val, so a program’s if follows the executed branch.
  • float(x) raises an error instead of returning x.val. An accidental call to math.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 whether x is dual; an object with its own _elemental method, like the later tracer, receives the call. This is the idea behind PyTorch __torch_function__ or JAX tracers.
[ ]A dual-number forward-mode engineBrowser
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 5.55.5 and other partial 2−cos⁡52 - \cos 5, and the Jacobian of R3\R^3 at R2\R^2 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 *.

[ ]Validation with lesson 13's gradient checkerBrowser
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 10−1710^{-17}, and the checker gives relative error of order 10−1010^{-10}: central-difference error, not AD error. Omitting regularization gives worst-component relative error 0.670.67: with λ=0.1\lambda = 0.1 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: nn scalar passes recompute primal values nn times and pay interpreter cost nn times per operation; one vector pass computes them once and handles tangents with NumPy operations on vectors of length nn.

[ ]Bratu Jacobian: n scalar passes, one vector pass or three colorsBrowser
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 a\sqrt{a}, xk+1=12(xk+a/xk)x_{k+1} = \tfrac12(x_k + a/x_k), iterated until unchanged, the final tangent is the derivative of the last iterate with respect to aa. 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 x2x^2 for every R\R (because 12=11^2 = 1), with f′(1)=2f'(1) = 2. AD at x=1x = 1 executes the first branch, a constant, and returns 0.

Nondifferentiable points. ∣x∣\abs{x}, max⁡(x,0)\max(x, 0) and x\sqrt{x} at x=0x = 0 have no derivative (or an infinite one). An implementation must return something: PyTorch and JAX give 0 for ∣x∣\abs{x} and ReLU at 0 (a subgradient), and infinity for x\sqrt{x}. Composition is dangerous: norm x12+x22\sqrt{x_1^2 + x_2^2} at the origin computes v=0v = 0 with tangent 0, then v\sqrt{v} multiplies ∞\infty by 00, which is NaN in IEEE 754.

[ ]Loops, branches and nondifferentiable pointsBrowser
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 a=2a = 2 and 8 for a=50a = 50, with tangents matching 1/(2a)1/(2\sqrt a) to every printed digit: variable loop length is no problem. Branch x == 1.0 gives tangent 0 at x=1x = 1 and 2.00000000000000042.0000000000000004 at the next floating-point number, 2x2x. 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 lim⁡t→0+∥tv∥/t=∥v∥\lim_{t\to 0^+}\norm{t\vb{v}}/t = \norm{\vb{v}} (no bilateral derivative because the left is −∥v∥-\norm{\vb{v}}, 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, ε1\eps_1 and ε2\eps_2, with ε12=ε22=0\eps_1^2 = \eps_2^2 = 0 but ε1ε2≠0\eps_1\eps_2 \neq 0. For a polynomial, expanding f(a+ε1+ε2)f(a + \eps_1 + \eps_2) gives

f(a+ε1+ε2)=f(a)+f′(a) ε1+f′(a) ε2+f′′(a) ε1ε2,f(a + \eps_1 + \eps_2) = f(a) + f'(a)\,\eps_1 + f'(a)\,\eps_2 + f''(a)\,\eps_1\eps_2 ,

because the 12f′′(a)(ε1+ε2)2=12f′′(a)⋅2ε1ε2\tfrac12 f''(a)(\eps_1 + \eps_2)^2 = \tfrac12 f''(a)\cdot 2\eps_1\eps_2 term survives and all terms of degree 3 or higher contain ε12\eps_1^2 or ε22\eps_2^2. The coefficient of ε1ε2\eps_1\eps_2 is the second derivative. In practice no new type is needed: a dual in ε2\eps_2 whose parts are duals in ε1\eps_1 is exactly R[ε1,ε2]/(ε12,ε22)\R[\eps_1, \eps_2]/(\eps_1^2, \eps_2^2), and differentiating with duals a function that already differentiates with duals computes f′′f''. This is nested forward mode: applying the derivative operator D\mathcal{D} to a function that uses D\mathcal{D} 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 ε\eps. 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

 ⁣d ⁣dx(x⋅ ⁣d ⁣dy(x+y)∣y=1)∣x=1.\frac{\dd}{\dd x}\left( x \cdot \left.\frac{\dd}{\dd y}(x + y)\right|_{y = 1} \right)\Bigg|_{x = 1} .

The inner derivative is 1 for any xx, so the outer one is  ⁣d ⁣dx(x⋅1)=1\frac{\dd}{\dd x}(x \cdot 1) = 1. With a single ε\eps, the outer derivative sets x=1+εx = 1 + \eps; the inner sets y=1+εy = 1 + \eps, with the same ε\eps; then x+y=2+2εx + y = 2 + 2\eps and the inner derivative comes out as 2 instead of 1, because it has counted the perturbation of xx 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, x=1+ε1x = 1 + \eps_1, y=1+ε2y = 1 + \eps_2, x+y=2+ε1+ε2x + y = 2 + \eps_1 + \eps_2, the inner derivative extracts the coefficient of ε2\eps_2, which is 1, and everything works.

[ ]Perturbation confusion and its solution with tagsBrowser
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 D\mathcal{D} gives derivatives of any order: f′′(2)=12f''(2) = 12 and f′′′(2)=6f'''(2) = 6 for x3x^3, and the first four derivatives of sin⁡\sin at 0.70.7 agree with the exact values to every printed digit. The price is cost: kk nested levels carry 2k2^k 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) and jax.jit compiles it with XLA (Frostig, Johnson and Leary, 2018). It combines both advantages, but when tracing is abstract, as in jit, tracers carry no values and Python control flow is resolved during tracing: an if on a traced value cannot be evaluated, which is why JAX has primitives such as lax.cond and lax.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.

[ ]Trace a function and generate its tangent programBrowser
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 ln⁡x1+x1x2\ln x_1 + x_1x_2 before sin⁡x2\sin x_2, so the sum is v3v_3 and the sine v4v_4. 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 (11.652…,5.5)(11.652\ldots, 5.5). 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 (n+1n + 1 evaluations of FF per iteration and errors of 10−810^{-8} in its entries), and Broyden’s method. With the dual-number engine, the exact Jacobian comes from FF itself, without writing a single derivative:

[ ]Newton for systems with the jacfwd JacobianBrowser
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 max⁡u=0.640005\max u = 0.640005 for λ=3\lambda = 3), 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 FF. 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,

x˙=αx−βxy,y˙=δxy−γy,\dot x = \alpha x - \beta x y, \qquad \dot y = \delta x y - \gamma y ,

with xx the prey and yy the predators, has four parameters θ=(α,β,γ,δ)\vb{\theta} = (\alpha, \beta, \gamma, \delta). The typical question in an ODE sensitivity analysis is how much the state at time TT changes when each parameter is varied: the matrix S(T)=∂(x(T),y(T))/∂θ∈R2×4\mat{S}(T) = \partial(x(T), y(T))/\partial\vb{\theta} \in \R^{2\times 4}.

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 I4\mat{I}_4. Every number in the integrator then carries its four derivatives, and the final state carries S(T)\mat{S}(T) in its tangents. The cost is one vector pass with 4 tangents: forward mode in its element, with few inputs and a long program.

[ ]Lotka–Volterra sensitivities: duals through RK4Browser
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: ∂x(T)/∂γ=−0.097\partial x(T)/\partial\gamma = -0.097 and ∂y(T)/∂δ=−237.5\partial y(T)/\partial\delta = -237.5. 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 h=10−2h = 10^{-2} truncation dominates and the relative error is 1.7%; it falls as h2h^2 (a factor 10410^4 when going to h=10−4h = 10^{-4}) to a minimum of 1.2×10−71.2\times 10^{-7} with h=10−6h = 10^{-6}, and rises again to 3×10−63\times 10^{-6} with h=10−8h = 10^{-8}, when rounding wins. AD does not have to choose hh.

Differentiating the simulation versus ODE sensitivity

There is a subtlety. AD computes the derivative of the program: of the state produced by RK4 with NN 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 z˙=f(z,θ)\dot{\vb{z}} = \vb{f}(\vb{z}, \vb{\theta}), differentiation with respect to θ\vb{\theta} gives

S˙=∂f∂z S+∂f∂θ,S(0)=0,\dot{\mat{S}} = \frac{\partial\vb{f}}{\partial\vb{z}}\,\mat{S} + \frac{\partial\vb{f}}{\partial\vb{\theta}}, \qquad \mat{S}(0) = \mat{0},

a linear system of 8 additional equations, which we solve with solve_ivp at a very fine tolerance as a reference.

[ ]Program derivative versus ODE sensitivityBrowser
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 NN doubles, the relative difference between the program derivative and the exact sensitivity is divided by a factor close to 16: it is O(h4)\bigO(h^4), the order of RK4. This is no coincidence. RK4 applied to the ODE is a smooth function of θ\vb{\theta}, 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.

[ ]torch.func.jvp, forward_ad y jacfwdLocal GPU
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())
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

PyTorch reproduces the example’s 5.55.5 and 1.7161.716 and the Bratu Jacobian. The tangents at 0 match those of the custom engine except for absolute value: PyTorch gives 0 for ∣x∣\abs{x} (it uses sign⁡(0)=0\operatorname{sign}(0) = 0) and for ReLU, infinity for x\sqrt{x} 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

NumericA pass by hand
Write the trace of f(x)=xsin⁡(x2)f(x) = x\sin(x^2) with v1=v02v_1 = v_0^2, v2=sin⁡v1v_2 = \sin v_1, v3=v0v2v_3 = v_0 v_2, and propagate tangents with v˙0=1\dot v_0 = 1 at x=1.5x = 1.5. What is v˙3\dot v_3?
NumericHow many passes?
F:R3→R1000F: \R^3 \to \R^{1000} is a dense function (each output depends on all three inputs). What is the minimum number of forward-mode passes with scalar tangents needed to obtain its full Jacobian?
NumericColors of a banded Jacobian
F:R1000→R1000F: \R^{1000} \to \R^{1000} with FiF_i depending only on xi−2,xi−1,xi,xi+1,xi+2x_{i-2}, x_{i-1}, x_i, x_{i+1}, x_{i+2} (whichever exist). What is the minimum number of seeds in Curtis, Powell and Reid column compression that recovers the entire Jacobian?
NumericThe coefficient of ε₁ε₂
Evaluate f(x)=ex2f(x) = e^{x^2} at the nested dual 1+ε1+ε21 + \eps_1 + \eps_2, with ε12=ε22=0\eps_1^2 = \eps_2^2 = 0 and ε1ε2≠0\eps_1\eps_2 \neq 0. What is the coefficient of ε1ε2\eps_1\eps_2? Give four digits.
QuizA network's gradient with forward mode
You want the gradient of a scalar loss L:R106→RL: \R^{10^6} \to \R (the parameters of a network). Why is forward mode not the right tool?
QuizPerturbation confusion
You implement the derivative as Df(x)=\mathcal{D}f(x) = the coefficient of ε\eps in f(x+ε)f(x + \eps), with a single ε\eps. When computing  ⁣d ⁣dx(x⋅ ⁣d ⁣dy(x+y)∣y=1)\frac{\dd}{\dd x}\big(x\cdot\frac{\dd}{\dd y}(x + y)|_{y=1}\big) at x=1x = 1 you get 2 instead of 1. What happened and how can it be avoided?
QuizWhat AD differentiates
A colleague writes 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 x=1x = 1 and at x=1+2−52x = 1 + 2^{-52}?
QuizWhich strategy?
You have a Python function with a while loop whose condition depends on an intermediate value (for example, iterating until a residual falls below a tolerance). Which statement is correct?
ProofWhy f(a + bε) = f(a) + f′(a)bε
Prove: For every polynomial pp with real coefficients and all a,b∈Ra, b \in \R, p(a+bε)=p(a)+p′(a) b εp(a + b\eps) = p(a) + p'(a)\,b\,\eps in D\mathbb{D}. If f(x)=∑k≥0ckxkf(x) = \sum_{k\ge 0} c_kx^k has radius of convergence R>∣a∣R > \abs{a}, the definition f(a+bε):=∑kck(a+bε)kf(a + b\eps) := \sum_k c_k(a + b\eps)^k gives f(a)+f′(a) b εf(a) + f'(a)\,b\,\eps.
0
You work in D=R[ε]/(ε2)\mathbb{D} = \R[\eps]/(\eps^2), where addition and multiplication are those of polynomials in ε\eps with ε2=0\eps^2 = 0.

Step 1 of 4. How do you begin for a polynomial?

CodeYour Dual class
Implement a 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)
Shift+Enter to run

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

Key idea
Automatic differentiation applies the chain rule to a program’s evaluation trace, operation by operation and using numbers. In forward mode, each variable carries a value and a tangent, packed in a dual number a+bεa + b\eps with ε2=0\eps^2 = 0, and one pass computes exact F(x)F(\vb{x}) and product JF(x)x˙\mat{J}_F(\vb{x})\dot{\vb{x}} at the cost of a few evaluations of FF.
  • 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: f(a+bε)=f(a)+f′(a)bεf(a + b\eps) = f(a) + f'(a)b\eps, consistent with polynomials, series and compositions.
  • One pass gives a JVP for at most about 4 times the cost of FF and without storing the trace. The full Jacobian costs nn 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.