Run forward-mode autodiff over a tiny instruction list
Why it matters JAX's jvp and PyTorch's forward-mode AD use this exact value-plus-tangent idea.
Forward-mode autodiff carries a value and its derivative together through every operation. It is the other half of autograd, used for Jacobian-vector products.
Write forward_mode(program, x, dx=1.0). Registers start as r[0] = (x, dx). program is a list of instructions, each appending one new register: ("const", c) gives (c, 0); ("add", i, j); ("mul", i, j); ("sin", i); ("exp", i); ("pow", i, k) for a fixed number k. Use the usual derivative rules on (value, derivative) pairs. Return the last register as a tuple (value, derivative) of floats.
def forward_mode(program, x, dx=1.0)Example
f(x) = x * x + sin(x) at x = 0 with program [("mul", 0, 0), ("sin", 0), ("add", 1, 2)] gives (0.0, 1.0).
Understand the idea
Forward mode pushes two numbers through the program at the same time: the value and how fast it changes when the input changes. Each operation updates both using a rule you learned in school calculus. It is like a car's odometer and speedometer updating together.
Tiny example: f(x) = x * x + sin(x) at x = 0, seed 1. Start (0, 1). x * x gives (0, 1 * 0 + 0 * 1) = (0, 0). sin(x) gives (0, cos(0) * 1) = (0, 1). Add: (0, 1). So f(0) = 0 and f'(0) = 1.
Rules: (a, da) + (b, db) = (a + b, da + db); (a, da) * (b, db) = (ab, da * b + a * db); sin: (sin a, cos a * da); exp: (e^a, e^a * da).
Forward mode is cheap when there are few inputs and many outputs, and it powers Hessian-vector products together with reverse mode.