---
title: Automatic differentiation
heading: Exact derivatives of any program, without a step size
eyebrow: A13 · Lesson 15 · Automatic differentiation
xp: 40
---

::: hook
Lesson 14's finite differences trade truncation against rounding and keep only about half the digits. Writing out derivatives by hand works for a formula but not for a 2000-line device model. Newton's method in a circuit simulator needs the Jacobian of that model at every step, and training a neural network needs the gradient of a loss with millions of inputs. **Automatic differentiation** gets these derivatives exactly, to rounding error, by running the program itself on numbers that carry their derivatives along. It's how simulators, optimizers and every machine-learning framework compute gradients.
:::

::: play
- The curve is the error of a central difference for the derivative of $x^2\sin x$ at $x = 1$, against the step $h$, on log axes. The flat dashed line is automatic differentiation's error: rounding only, about $10^{-16}$, with no step to choose.
- Even the best step leaves the difference formula around $10^{-11}$.
:::

```sim plot
view: graph
x: h = 1e-12..0.1 log
y: error = 1e-17..0.01 log
plot: abs(h^2*(6*cos(1) - 6*sin(1) - cos(1))/6) + 1.1e-16*0.84/h | label: central difference (truncation + rounding)
plot: 2e-16 + 0*h | dashed | color: ch3 | label: automatic differentiation
```

::: predict
## A number $a + b\varepsilon$ obeys ordinary arithmetic with one extra rule, $\varepsilon^2 = 0$. Square $2 + \varepsilon$. What do you get?

- [x] $4 + 4\varepsilon$
- [ ] $4 + \varepsilon$
- [ ] $4 + \varepsilon^2$, which is 4
- [ ] $4 + 2\varepsilon$

::: reveal
$4 + 4\varepsilon$: $(2 + \varepsilon)^2 = 4 + 4\varepsilon + \varepsilon^2$ and the last term vanishes. The $\varepsilon$ part, 4, is the derivative of $x^2$ at 2. That's not a coincidence: feeding $x + \varepsilon$ into any computation returns $f(x) + f'(x)\varepsilon$.
:::
:::

::: nameit
## Dual numbers

A **dual number** $a + b\varepsilon$ has $\varepsilon^2 = 0$. Arithmetic follows:

$$(a + b\varepsilon) \pm (c + d\varepsilon) = (a \pm c) + (b \pm d)\varepsilon$$
$$(a + b\varepsilon)(c + d\varepsilon) = ac + (ad + bc)\varepsilon$$
$$\frac{a + b\varepsilon}{c + d\varepsilon} = \frac{a}{c} + \frac{bc - ad}{c^2}\varepsilon$$

and an elementary function applies its derivative to the $\varepsilon$ part: $g(a + b\varepsilon) = g(a) + g'(a)\,b\,\varepsilon$, so $\sin(a + b\varepsilon) = \sin a + b\cos a\,\varepsilon$.

The product line is the product rule, the quotient line the quotient rule, and the function line the chain rule. Run any program on $x + 1\varepsilon$ and every intermediate value carries its own derivative; the result is $f(x) + f'(x)\varepsilon$, with no step size and no truncation error.

## Forward and reverse mode

- **Forward mode** (dual numbers) gives the derivative with respect to one input per run. For $f: \mathbb{R}^n \to \mathbb{R}^m$, $n$ runs give the full Jacobian, each costing a small multiple of one evaluation of $f$.
- **Reverse mode** records the computation, then sweeps backward through it, carrying the derivative of the output with respect to each intermediate value (its **adjoint**). One backward sweep gives the gradient of one output with respect to every input. For a loss with a million parameters that's the difference between a million runs and one: it's backpropagation.

## How it relates to the complex step

Lesson 14's complex step, $f'(x) \approx \text{Im}\,f(x + ih)/h$, works for the same reason: $i$ with a tiny $h$ behaves almost like $\varepsilon$. Dual numbers make the "almost" exact and work for any code, including code that isn't analytic.
:::

::: example
## Find the value and derivative of $f(x) = x^2\sin x$ at $x = 2$ with dual numbers.

::: solution
1. **Seed the input.** Start with $x = 2 + \varepsilon$.
2. **Square it.**
   $$x^2 = 4 + 4\varepsilon$$
3. **Take the sine.**
   $$\begin{aligned} \sin x &= \sin 2 + \cos 2\,\varepsilon \\ &= 0.9093 - 0.4161\varepsilon \end{aligned}$$
4. **Multiply.**
   $$\begin{aligned} f &= 4(0.9093) \\ &\quad + \left(4(-0.4161) + 4(0.9093)\right)\varepsilon \\ &= 3.6372 + 1.9726\varepsilon \end{aligned}$$
5. **Read off the result.** So $f(2) = 3.6372$ and $f'(2) = 1.9726$, matching $2x\sin x + x^2\cos x$ at 2.
6. **What the computer did.** It did exactly the arithmetic of the product rule, one operation at a time, without ever forming the formula.

**Answer:** $f(2) = 3.6372$ and $f'(2) = 1.9726$.
:::
:::

::: example
## A diode ($I_s = 10^{-14}$ A, $V_T$ = 25.85 mV) and resistor $R$ = 1 kΩ are in series across 5 V. Newton's method on the diode voltage needs $f'(v)$ for $f(v) = I_s(e^{v/V_T} - 1) - (5 - v)/R$. How does forward-mode differentiation supply it?

::: solution
1. **Evaluate on $v + \varepsilon$.** The exponential gives
   $$e^{v/V_T} + \frac{1}{V_T}e^{v/V_T}\varepsilon$$
2. **The resistor term.**
   $$-\frac{5 - v}{R} - \frac{-1}{R}\varepsilon$$
3. **Add the $\varepsilon$ parts.** The sum's $\varepsilon$ part is
   $$\frac{I_s}{V_T}e^{v/V_T} + \frac1R$$
   exactly $f'(v)$.
4. **The Newton step.** It is then the value part over the $\varepsilon$ part.
5. **Why simulators use it.** A simulator does this for every device model, so a new model needs only its current equation, never a hand-derived conductance.

**Answer:** evaluating $f$ on $v + \varepsilon$ carries $f'(v) = \frac{I_s}{V_T}e^{v/V_T} + \frac1R$ in the $\varepsilon$ part, and Newton's step is the value part over the $\varepsilon$ part.
:::
:::

::: example
## For $f(x, y) = xy + \sin x$ at $(1, 2)$, find both partial derivatives by reverse mode.

::: solution
1. **Forward sweep.**
   $$\begin{aligned} a &= xy \\ &= 2 \\ b &= \sin x \\ &= 0.8415 \\ f &= a + b \\ &= 2.8415 \end{aligned}$$
2. **Backward sweep.** Start with $\bar f = 1$, so $\bar a = \bar b = 1$; then
   $$\begin{aligned} \bar x &= \bar a\,y + \bar b\cos x \\ &= 2 + 0.5403 \\ &= 2.5403 \\ \bar y &= \bar a\,x \\ &= 1 \end{aligned}$$
3. **Compare with forward mode.** One backward pass gave both partials; forward mode would have needed two runs, one seeded on $x$ and one on $y$.

**Answer:** $\partial f/\partial x = 2.5403$ and $\partial f/\partial y = 1$, both from one backward pass.
:::
:::

::: check
given: a = 1 | 2 | 3; b = 1 | -2; c = 4 | 5; d = 3 | 7
answer: a*d + b*c
tolerance: 0.5%

## What is the $\varepsilon$ part of $(\given{a} + \given{b}\varepsilon)(\given{c} + \given{d}\varepsilon)$?

::: right
Right. $ad + bc$ = {answer}: the product rule, written as arithmetic.
:::

::: misses
- [b*d] That's the $\varepsilon^2$ term, which vanishes.
- [a*c] That's the real part.
- [any] Not yet. Expand and drop $\varepsilon^2$: the $\varepsilon$ part is $ad + bc$.
:::
:::

::: check
given: x = 0.5 | 1 | 2
answer: cos(x)*exp(sin(x))
tolerance: 0.5%

## Feeding $x + \varepsilon$ with $x$ = {x} into $f(x) = e^{\sin x}$, what is the $\varepsilon$ part of the result?

::: right
Right. $\sin(x + \varepsilon) = \sin x + \cos x\,\varepsilon$, and then $e^{(\cdot)}$ multiplies the $\varepsilon$ part by $e^{\sin x}$: {answer}, which is $f'(x)$.
:::

::: misses
- [exp(sin(x))] That's the value part.
- [exp(cos(x))] Apply the chain rule: the derivative of $e^{\sin x}$ is $\cos x\,e^{\sin x}$.
- [any] Not yet. Push $x + \varepsilon$ through $\sin$, then through $\exp$.
:::
:::

::: check
kind: python
given: x0 = 0.3 | 1 | 2.5

## Write a class `Dual(a, b)` with `+`, `-`, `*`, `/` (each also with a plain number on either side), and functions `dsin`, `dexp` that act on duals. Then set `val, der` to the value and derivative of $f(x) = \dfrac{x^2\sin x}{1 + e^{-x}}$ at `x0` = {x0}, by evaluating `f(Dual(x0, 1))`.

```python starter
import math

class Dual:
    def __init__(self, a, b=0.0):
        self.a, self.b = a, b

def f(x):
    return x

r = f(Dual(x0, 1.0))
val, der = r.a, r.b
print(val, der)
```

```python solution
import math

class Dual:
    def __init__(self, a, b=0.0):
        self.a, self.b = a, b
    def _d(o):
        return o if isinstance(o, Dual) else Dual(o)
    def __add__(s, o):
        o = Dual._d(o); return Dual(s.a + o.a, s.b + o.b)
    __radd__ = __add__
    def __sub__(s, o):
        o = Dual._d(o); return Dual(s.a - o.a, s.b - o.b)
    def __rsub__(s, o):
        return Dual._d(o) - s
    def __mul__(s, o):
        o = Dual._d(o); return Dual(s.a * o.a, s.a * o.b + s.b * o.a)
    __rmul__ = __mul__
    def __truediv__(s, o):
        o = Dual._d(o); return Dual(s.a / o.a, (s.b * o.a - s.a * o.b) / o.a**2)
    def __rtruediv__(s, o):
        return Dual._d(o) / s

def dsin(x):
    return Dual(math.sin(x.a), math.cos(x.a) * x.b)

def dexp(x):
    return Dual(math.exp(x.a), math.exp(x.a) * x.b)

def f(x):
    return x * x * dsin(x) / (1 + dexp(-1 * x))

r = f(Dual(x0, 1.0))
val, der = r.a, r.b
print(val, der)
```

```python tests
import math
g = lambda x: x * x * math.sin(x) / (1 + math.exp(-x))
dg = lambda x: ((2 * x * math.sin(x) + x * x * math.cos(x)) * (1 + math.exp(-x)) + x * x * math.sin(x) * math.exp(-x)) / (1 + math.exp(-x))**2
assert abs(val - g(x0)) < 1e-14, "The value part should be f(x0)."
assert abs(der - dg(x0)) < 1e-13, f"The derivative should be {dg(x0):.15f}, exact to rounding."
d = Dual(3.0, 1.0)
assert abs((2 / d).b + 2 / 9) < 1e-15 and abs((1 - d).b + 1) < 1e-15, "Plain numbers on the left must work too: 2 / x and 1 - x."
```

::: right
Right. The derivative agrees with the hand-derived formula to the last digit or two, with no step size anywhere. Every rule you wrote is one line of calculus; the class applies them in whatever order the program runs.
:::
:::

::: check
kind: python
given: Vs = 3 | 5 | 12; R = 220 | 1000 | 4700

## Solve $I_s(e^{v/V_T} - 1) = (V_s - v)/R$ for the diode voltage with Newton's method, getting $f'(v)$ by evaluating $f$ on a dual number instead of by hand ($I_s = 10^{-14}$ A, $V_T$ = 0.02585 V, `Vs` = {Vs} V, `R` = {R} Ω). Start from $v = 0.6$ and limit each step to $2V_T$. Set `v` to the result and `I` to the current.

```python starter
import math
v = 0.6
I = (Vs - v) / R
print(v, I)
```

```python solution
import math
Is, VT = 1e-14, 0.02585
def f(v, dv):
    e = math.exp(v / VT)
    return Is * (e - 1) - (Vs - v) / R, Is * e / VT * dv + dv / R
v = 0.6
for _ in range(200):
    fv, fd = f(v, 1.0)
    step = fv / fd
    step = max(-2 * VT, min(2 * VT, step))
    v -= step
    if abs(step) < 1e-13:
        break
I = (Vs - v) / R
print(v, I)
```

```python tests
import math
lo, hi = 0.0, Vs
for _ in range(200):
    m = (lo + hi) / 2
    if 1e-14 * (math.exp(m / 0.02585) - 1) > (Vs - m) / R: hi = m
    else: lo = m
vd = (lo + hi) / 2
assert abs(v - vd) < 1e-9, f"The diode voltage is {vd:.6f} V (checked by bisection)."
assert abs(I - (Vs - vd) / R) < 1e-12, "I is (Vs - v)/R."
```

::: right
Right. The dual number's derivative part is exactly the slope Newton needs, so the code never states the diode's conductance. That's how simulators let you add a device by writing only its current equation.
:::
:::

::: check
given: n = 3 | 100 | 1000000; m = 2 | 5
answer: n
tolerance: 0.1

## A function maps {n} inputs to {m} output(s). How many forward-mode passes does its full Jacobian need?

::: right
Right. Each forward pass seeds one input with $\varepsilon$ and gives one column of the Jacobian, so {n} passes: {answer}.
:::

::: misses
- [m] That's how many reverse-mode passes it would need, one per output.
- [n*m] Each forward pass gives a whole column, all {m} outputs at once.
- [any] Not yet. One forward pass per input.
:::
:::

::: check
kind: parts
given: x = 0.5 | 1 | 2; y = 3 | 5

## Run reverse mode on $f = xy + \sin x$ at $x$ = {x}, $y$ = {y}, with intermediates $a = xy$ and $b = \sin x$.

::: part
answer: y + cos(x)
tolerance: 0.5%

### What is $\partial f/\partial x$, collecting the adjoints that flow into $x$ from $a$ and from $b$?

::: misses
- [y] That's only the path through $a$. $x$ also feeds $b = \sin x$.
- [cos(x)] That's only the path through $b$.
- [any] Not yet. $\bar x = \bar a\,y + \bar b\cos x$ with $\bar a = \bar b = 1$.
:::
:::

::: part
answer: x
tolerance: 0.5%

### What is $\partial f/\partial y$?

::: misses
- [y] Through $a = xy$, the adjoint picks up the other factor, $x$.
- [any] Not yet. $\bar y = \bar a\,x$.
:::
:::

::: right
Right. An input used twice collects an adjoint along each path, which is the multivariable chain rule, and one backward sweep gave every partial at once.
:::
:::

::: check
kind: derivation
vars: a = -2..2, b = -2..2, c = 0.5..3, d = -2..2

## Show that dual-number division gives the quotient rule. Multiply top and bottom of $\frac{a + b\varepsilon}{c + d\varepsilon}$ by $c - d\varepsilon$.

::: step
answer: c^2

### What does the denominator become?
:::

::: step
answer: (b*c - a*d)/c^2

### What is the $\varepsilon$ part of the quotient?
:::

::: right
Right. With $a = u$, $b = u'$, $c = v$, $d = v'$ that's $(u'v - uv')/v^2$, the quotient rule. Multiplying by the "conjugate" works for duals just as it does for complex numbers.
:::
:::

::: check
kind: choice

## Why does automatic differentiation have no truncation error, unlike a finite difference?

- [x] It applies the exact derivative rules to each operation, so nothing is approximated; only rounding remains
- [ ] It uses a very small step
- [ ] It works symbolically, building a formula for the derivative
- [ ] It does have truncation error, just smaller

::: right
Right. There's no step at all: each elementary operation's exact derivative is applied as the program runs. AD doesn't build a formula either; it computes numbers, which is why it scales to huge programs.
:::

::: misses
- [2] There's no step to make small; the derivative rules are applied exactly.
- [3] AD never builds a formula. It propagates numbers, which avoids symbolic differentiation's blow-up in size.
- [4] Its only error is floating-point rounding in the same operations the function itself uses.
:::
:::

::: explain
## Training a network with a million weights needs the gradient of one loss with respect to all of them. Why is reverse mode the right choice, and what does it cost?

::: model
Forward mode gives the derivative with respect to one input per run, so a million inputs would take a million runs. Reverse mode runs the computation once forward, storing the intermediate values, then sweeps backward once, passing each intermediate's sensitivity of the single output to everything that fed it; at the end every input has its partial derivative. The cost is a small multiple of one evaluation of the loss, whatever the number of weights, plus the memory to store the forward pass. For one output and many inputs that's an enormous saving, which is why backpropagation is reverse mode.
:::
:::

::: practice

::: check
given: x = 1 | 3; b = 2 | 3
answer: 3*x^2*b
tolerance: 0.5%

## What is the $\varepsilon$ part of $(\given{x} + \given{b}\varepsilon)^3$?

::: misses
- [3*x^2] Multiply by the $\varepsilon$ part you started with, {b}.
- [any] $(x + b\varepsilon)^3 = x^3 + 3x^2b\,\varepsilon$.
:::
:::

::: check
given: x = 0.3 | 0.5 | 0.8 | 1.5 | 2 | 2.5
answer: -sin(x^2)*2*x
tolerance: 0.5%

## Feeding $x + \varepsilon$ into $\cos(x^2)$ with $x$ = {x}, what is the $\varepsilon$ part?

::: misses
- [-sin(x)*2*x] Evaluate the sine at $x^2$, the inner function's value, not at $x$.
- [any] $x^2 \to x^2 + 2x\varepsilon$, then $\cos$ multiplies the $\varepsilon$ part by $-\sin(x^2)$.
:::
:::
:::
