TExcelTAD
Home › Calculus Essentials › Automatic Differentiation

Automatic Differentiation

Automatic differentiation (autodiff, AD) computes exact derivatives of a program, not of a formula, by applying the chain rule to each elementary operation as the program runs. It is neither symbolic algebra nor finite differences. This lesson compares the three approaches, then builds forward mode with dual numbers and reverse mode with a small Value class, the same idea that powers PyTorch and JAX.

Three ways to get a derivative

Approach How Weakness
Symbolic (SymPy) Rewrites the formula with differentiation rules Needs a formula; expressions can grow huge; loops and ifs are awkward
Numeric (finite differences) (f(x+h)−f(x))/h(f(x + h) - f(x)) / h Truncation error for big hh, rounding error for small hh; one extra run per input
Automatic Carries derivatives alongside values through every +, *, sin, … Needs operator overloading or a tracing framework

The numeric approach has an annoying sweet spot. For f(x)=sin⁡(x)⋅exf(x) = \sin(x) \cdot e^x at x=1x = 1:

python · try it yourself
import math

f = lambda x: math.sin(x) * math.exp(x)
exact = (math.cos(1) + math.sin(1)) * math.e     # product rule
print(f"exact f'(1) = {exact:.12f}")
for k in [1, 2, 4, 6, 8, 10, 12, 14]:
    h = 10.0 ** -k
    fd = (f(1 + h) - f(1)) / h
    print(f"h = 1e-{k:<2}  forward difference error {abs(fd - exact):.2e}")
exact f'(1) = 3.756049227095
h = 1e-1   forward difference error 1.44e-01
h = 1e-2   forward difference error 1.47e-02
h = 1e-4   forward difference error 1.47e-04
h = 1e-6   forward difference error 1.47e-06
h = 1e-8   forward difference error 2.21e-08
h = 1e-10  forward difference error 4.22e-07
h = 1e-12  forward difference error 5.01e-04
h = 1e-14  forward difference error 1.87e-02

The error first shrinks with hh (less truncation), then grows again (subtracting two almost equal floats loses digits). The best you get is about 8 correct digits. Autodiff gives all 16.

Forward mode: dual numbers

Extend numbers with a symbol ε\varepsilon that satisfies ε2=0\varepsilon^2 = 0 (but ε≠0\varepsilon \ne 0), and write a dual number as a+bεa + b\varepsilon. Then

(a+bε)+(c+dε)=(a+c)+(b+d)ε(a+bε)⋅(c+dε)=ac+(ad+bc)ε(the bd ε2 term vanishes)f(a+bε)=f(a)+f′(a) b ε(Taylor series stops after the linear term)\begin{aligned} (a + b\varepsilon) + (c + d\varepsilon) &= (a + c) + (b + d)\varepsilon \\ (a + b\varepsilon) \cdot (c + d\varepsilon) &= ac + (ad + bc)\varepsilon && \text{(the } bd\,\varepsilon^2 \text{ term vanishes)} \\ f(a + b\varepsilon) &= f(a) + f'(a)\,b\,\varepsilon && \text{(Taylor series stops after the linear term)} \end{aligned}

The ε\varepsilon part follows the sum rule, the product rule and the chain rule automatically. Evaluate any function at x+1⋅εx + 1 \cdot \varepsilon and read the derivative off the ε\varepsilon part.

python · try it yourself
import math

class Dual:
    def __init__(self, val, der=0.0):
        self.val, self.der = val, der
    def __add__(self, o):
        o = o if isinstance(o, Dual) else Dual(o)
        return Dual(self.val + o.val, self.der + o.der)
    __radd__ = __add__
    def __mul__(self, o):
        o = o if isinstance(o, Dual) else Dual(o)
        return Dual(self.val * o.val, self.der * o.val + self.val * o.der)
    __rmul__ = __mul__

def sin(d): return Dual(math.sin(d.val), math.cos(d.val) * d.der)
def exp(d): return Dual(math.exp(d.val), math.exp(d.val) * d.der)

x = Dual(1.0, 1.0)              # x = 1, dx/dx = 1
y = sin(x) * exp(x)
print(f"f(1)  = {y.val:.12f}")
print(f"f'(1) = {y.der:.12f}")

p = 3 * x * x + 2 * x + 5       # works on any code made of these operations
print("p(1) =", p.val, " p'(1) =", p.der)
f(1)  = 2.287355287179
f'(1) = 3.756049227095
p(1) = 10.0  p'(1) = 8.0

The derivative matches the exact value to the last printed digit. Forward mode costs about one extra multiplication per operation, but it computes the derivative with respect to one input per run. For a function of a million inputs you would need a million runs.

Reverse mode: record, then walk backwards

Reverse mode first runs the program and records a graph of operations (each node remembers its inputs and how to pass a gradient to them). Then it starts at the output with gradient 1 and walks the graph in reverse topological order, adding each node's contribution to its inputs' .grad. That is backpropagation for arbitrary code.

python · try it yourself
import math

class Value:
    def __init__(self, data, parents=(), op=""):
        self.data, self.grad = data, 0.0
        self.parents, self.op = parents, op
        self.backward_step = lambda: None
    def __add__(self, other):
        out = Value(self.data + other.data, (self, other), "+")
        def step():
            self.grad += out.grad
            other.grad += out.grad
        out.backward_step = step
        return out
    def __mul__(self, other):
        out = Value(self.data * other.data, (self, other), "*")
        def step():
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out.backward_step = step
        return out
    def tanh(self):
        th = math.tanh(self.data)
        out = Value(th, (self,), "tanh")
        def step():
            self.grad += (1 - th * th) * out.grad
        out.backward_step = step
        return out
    def backward(self):
        order, seen = [], set()
        def visit(v):
            if id(v) not in seen:
                seen.add(id(v))
                for p in v.parents:
                    visit(p)
                order.append(v)
        visit(self)
        self.grad = 1.0
        for v in reversed(order):
            v.backward_step()

x, y = Value(0.5), Value(-1.5)
f = (x * y + x).tanh()            # f = tanh(x·y + x)
f.backward()
print(f"f = {f.data:.6f}   df/dx = {x.grad:.6f}   df/dy = {y.grad:.6f}")
f = -0.244919   df/dx = -0.470007   df/dy = 0.470007

One backward pass gave the derivative with respect to both inputs. Note the +=: xx is used twice (in x⋅yx \cdot y and in + x+\,x), and its two contributions add up, exactly the multivariable chain rule. Let's confirm with SymPy:

python · try it yourself
import sympy as sp

x, y = sp.symbols("x y")
f = sp.tanh(x * y + x)
vals = {x: 0.5, y: -1.5}
print("df/dx =", sp.diff(f, x))
print(f"df/dx = {float(sp.diff(f, x).subs(vals)):.6f}   df/dy = {float(sp.diff(f, y).subs(vals)):.6f}")
df/dx = (1 - tanh(x*y + x)**2)*(y + 1)
df/dx = -0.470007   df/dy = 0.470007

Forward or reverse?

Forward mode Reverse mode
One pass gives derivatives of all outputs w.r.t. one input derivatives of one output w.r.t. all inputs
Best when few inputs, many outputs (sensitivities, Jacobian columns) many inputs, one output: a loss with millions of weights
Memory small, nothing stored stores the whole graph of the forward pass
Implementation dual numbers, operator overloading tape or graph + topological sort

Training a neural network is the extreme "many inputs, one output" case, which is why deep learning uses reverse mode. The full Jacobian of a function Rn→Rm\mathbb{R}^n \to \mathbb{R}^m costs nn forward passes or mm reverse passes.

In software

  • PyTorch builds the graph as your Python code runs ("define by run"); loss.backward() is the backward() above, with each tensor operation knowing its local derivative.
  • JAX offers both modes: jax.jvp (forward) and jax.vjp/jax.grad (reverse), and composes them for Hessians.
  • Beyond ML: physics engines and robotics use AD for sensitivities and controller tuning; finance uses "adjoint AD" (reverse mode) to compute the price sensitivities ("Greeks") of a portfolio in one pass; differentiable renderers optimise 3D scenes from images.

Build a complete engine yourself, with more operations and a training loop, in the mini project.

Exercises

Exercise 1: Dual numbers by hand

Compute (2+ε)3(2 + \varepsilon)^3 using ε2=0\varepsilon^2 = 0. What derivative does it give?

Answer

(2+ε)3=8+12ε(2 + \varepsilon)^3 = 8 + 12\varepsilon, so ddxx3\frac{d}{dx} x^3 at x=2x = 2 is 12.

Solution
(2+ε)2=4+4ε+ε2=4+4ε(2+ε)3=(4+4ε)(2+ε)=8+4ε+8ε+4ε2=8+12εcheck: 3x2 at x=2 is 12 ✓\begin{aligned} (2 + \varepsilon)^2 &= 4 + 4\varepsilon + \varepsilon^2 = 4 + 4\varepsilon \\ (2 + \varepsilon)^3 &= (4 + 4\varepsilon)(2 + \varepsilon) = 8 + 4\varepsilon + 8\varepsilon + 4\varepsilon^2 = 8 + 12\varepsilon \\ &\text{check: } 3x^2 \text{ at } x = 2 \text{ is } 12 \ \checkmark \end{aligned}

Exercise 2: Division for duals

Derive the rule for (a+bε)/(c+dε)(a + b\varepsilon) / (c + d\varepsilon). Hint: multiply top and bottom by (c−dε)(c - d\varepsilon).

Answer

(a+bε)/(c+dε)=a/c+((bc−ad)/c2) ε(a + b\varepsilon)/(c + d\varepsilon) = a/c + ((bc - ad)/c^2)\,\varepsilon, the quotient rule.

Solution
(a+bε)(c−dε)(c+dε)(c−dε)=ac+(bc−ad)ε−bdε2c2−d2ε2=ac+(bc−ad)εc2=ac+bc−adc2 ε\begin{aligned} &\frac{(a + b\varepsilon)(c - d\varepsilon)}{(c + d\varepsilon)(c - d\varepsilon)} \\ &= \frac{ac + (bc - ad)\varepsilon - bd\varepsilon^2}{c^2 - d^2\varepsilon^2} \\ &= \frac{ac + (bc - ad)\varepsilon}{c^2} \\ &= \frac{a}{c} + \frac{bc - ad}{c^2}\,\varepsilon \end{aligned}

With b=f′b = f', d=g′d = g' this is (f/g)′=(f′g−fg′)/g2(f/g)' = (f'g - fg')/g^2.

Exercise 3: Reverse mode by hand

For f=(x+y)⋅xf = (x + y) \cdot x at x=3x = 3, y=2y = 2, draw the graph (u=x+yu = x + y, f=u⋅xf = u \cdot x) and push the gradient backwards to get ∂f/∂x\partial f/\partial x and ∂f/∂y\partial f/\partial y.

Answer

∂f/∂x=8\partial f/\partial x = 8, ∂f/∂y=3\partial f/\partial y = 3.

Solution
text
forward:  u = 5,  f = 15
f.grad = 1
f = u·x:  u.grad += x·1 = 3,   x.grad += u·1 = 5
u = x+y:  x.grad += u.grad = 3 → x.grad = 8,   y.grad += 3 → y.grad = 3
check: f = x² + xy, ∂f/∂x = 2x + y = 8, ∂f/∂y = x = 3 ✓

Exercise 4: Add exp to forward mode

Using the Dual class idea, compute the derivative of g(x)=ex⋅xg(x) = e^{x \cdot x} at x=0.5x = 0.5 and compare with the exact 2xex22x e^{x^2}.

Answer

g′(0.5)=e0.25≈1.284025g'(0.5) = e^{0.25} \approx 1.284025.

Solution
python · try it yourself
import math

class Dual:
    def __init__(self, val, der=0.0):
        self.val, self.der = val, der
    def __mul__(self, o):
        return Dual(self.val * o.val, self.der * o.val + self.val * o.der)

def exp(d):
    return Dual(math.exp(d.val), math.exp(d.val) * d.der)   # chain rule

x = Dual(0.5, 1.0)
g = exp(x * x)
print(f"dual  {g.der:.6f}")
print(f"exact {2 * 0.5 * math.exp(0.25):.6f}")
dual  1.284025
exact 1.284025

Test yourself

What is (3+ε)⋅(3+ε)(3 + \varepsilon) \cdot (3 + \varepsilon) with ε2=0\varepsilon^2 = 0?

  1. 9
  2. 9+6ε9 + 6\varepsilon
  3. 9+3ε9 + 3\varepsilon
  4. 9+ε29 + \varepsilon^2

A loss depends on 10 million weights. Which mode gives all gradients in about one extra pass?

  1. Forward mode
  2. Reverse mode
  3. Finite differences
  4. Symbolic differentiation

Why does the reverse-mode Value class use grad += instead of grad =?

  1. For speed
  2. A value used in several places gets one contribution per use, and they must be summed
  3. To avoid negative gradients
  4. Python requires it