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.

Signaturedef 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.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleforward_mode([('mul', 0, 0), ('sin', 0), ('add', 1, 2)], 0.0)
  • Sample 2: exp times xforward_mode([('exp', 0), ('mul', 0, 1), ('const', 3.0), ('mul', 2, 3)], 1.0)
  • Test 3: pow and seedforward_mode([('pow', 0, 3), ('const', -2.0), ('mul', 0, 2), ('add', 1, 3)], 2.0, 0.5)
  • Test 4: nested sinforward_mode([('sin', 0), ('sin', 1), ('mul', 2, 0)], 0.7)