Automatic Differentiation

File: Autograd.lean

Neural network libraries compute gradients with reverse-mode automatic differentiation. The forward pass computes a value and records each operation. The backward pass visits the operations in reverse order and applies the chain rule. For Code Test and a final output Code Test:

math

The Common Lisp version gives each node a mutable gradient field and a closure that updates the gradients of its inputs. The Lean version records the operations in an array and returns the gradients as a second array.

The demo builds this graph, with the node index in parentheses:

1 a(0)   b(1)        c(2)
2   \     /            |
3    mul(3)            |
4       \              /
5        add(4)
6          |
7        relu(5) = e

The Code

 1 -- lean --run Autograd.lean   (scalar automatic differentiation DAG)
 2 
 3 -- The graph is an array of nodes (a "tape"). A node names its inputs
 4 -- by index. New nodes go on the end, so every node comes after its
 5 -- inputs and one reverse pass visits each node before its inputs.
 6 
 7 inductive Op where
 8   | leaf
 9   | add (a b : Nat)
10   | mul (a b : Nat)
11   | relu (a : Nat)
12   deriving Inhabited
13 
14 structure Node where
15   data : Float
16   op : Op
17   deriving Inhabited
18 
19 abbrev Tape := StateM (Array Node)
20 
21 def push (n : Node) : Tape Nat :=
22   modifyGet fun tape => (tape.size, tape.push n)
23 
24 def data (i : Nat) : Tape Float := do
25   return (← get)[i]!.data
26 
27 def val (d : Float) : Tape Nat := push ⟨d, .leaf⟩
28 
29 def vadd (a b : Nat) : Tape Nat := do
30   push ⟨(← data a) + (← data b), .add a b⟩
31 
32 def vmul (a b : Nat) : Tape Nat := do
33   push ⟨(← data a) * (← data b), .mul a b⟩
34 
35 def vrelu (a : Nat) : Tape Nat := do
36   push ⟨max 0.0 (← data a), .relu a⟩
37 
38 -- Returns d(root)/d(node) for every node on the tape.
39 def backward (tape : Array Node) (root : Nat) : Array Float := Id.run do
40   let mut grad := (Array.replicate tape.size 0.0).set! root 1.0
41   for k in [0:root + 1] do
42     let i := root - k
43     let g := grad[i]!
44     match tape[i]!.op with
45     | .leaf => pure ()
46     | .add a b =>
47       grad := grad.modify a (· + g)
48       grad := grad.modify b (· + g)
49     | .mul a b =>
50       grad := grad.modify a (· + tape[b]!.data * g)
51       grad := grad.modify b (· + tape[a]!.data * g)
52     | .relu a =>
53       let passed := if tape[i]!.data > 0.0 then g else 0.0
54       grad := grad.modify a (· + passed)
55   return grad
56 
57 def fixed (x : Float) (d : Nat := 2) : String :=
58   let n := (x.abs * (10 ^ d).toFloat).round.toUInt64.toNat
59   let frac := toString (n % 10 ^ d)
60   let pad := "".pushn '0' (d - frac.length)
61   s!"{if x < 0 then "-" else ""}{n / 10 ^ d}.{pad}{frac}"
62 
63 -- Demo: d = (a * b) + c,  e = relu(d)
64 def main : IO Unit := do
65   let graph : Tape (Nat × Nat × Nat × Nat × Nat) := do
66     let a ← val 2.0
67     let b ← val (-3.0)
68     let c ← val 10.0
69     let d ← vadd (← vmul a b) c
70     let e ← vrelu d
71     return (a, b, c, d, e)
72   let ((a, b, c, d, e), tape) := graph.run #[]
73   let grad := backward tape e
74   let v (i : Nat) := fixed tape[i]!.data 1
75   let g (i : Nat) := fixed grad[i]!
76   IO.println s!"Forward:  d = (a * b) + c = ({v a} * {v b}) + {v c}"
77   IO.println s!"          d = {v d}"
78   IO.println s!"          e = relu(d) = {v e}"
79   IO.println "Gradients after backward:"
80   IO.println s!"  de/de = {g e}"
81   IO.println s!"  de/dd = {g d}"
82   IO.println s!"  de/dc = {g c}  (expected 1.0)"
83   IO.println s!"  de/da = {g a}  (expected b = -3.0)"
84   IO.println s!"  de/db = {g b}  (expected a = 2.0)"

How It Works

  • An Op records which operation made a node and the positions of its input nodes. A Node holds a value and an Op.
  • Tape is StateM (Array Node): a computation that can read and replace an array of nodes. StateM passes the array from step to step, so the code does not pass it by hand.
  • push appends a node and returns its position. modifyGet does both in one step: its function takes the old state and returns a result with the new state.
  • ⟨d, .leaf⟩ builds a Node from its fields in order. Lean knows the type from the context.
  • (← data a) runs a step inside a larger expression. vadd reads two values, adds them, and pushes a new node.
  • backward needs no state type. It takes the finished array and loops from the root down to position 0. Each node adds its part to the gradients of its inputs. grad.modify a (· + g) adds g to element a. A node that is an input to two later nodes receives two additions, which is the chain rule for a shared value.
  • The order is correct because a node can only refer to nodes pushed before it. When the loop reaches a node, every node that uses it has already added its part.
  • In main, graph.run #[] runs the forward pass from an empty array and returns the node positions with the final array.

Checking the Gradients

Node Value Gradient
e 4.0 1.0
d 4.0 1.0
c 10.0 1.0
mul -6.0 1.0
a 2.0 -3.0
b -3.0 2.0

The relu passes because d is positive. The add sends its gradient to both inputs. The mul sends b times the gradient to a and a times the gradient to b, which gives -3 and 2. The printed values match the table.

The loop runs from the root down to index 0, so it visits only nodes at or before the root. A node pushed after the root keeps a zero gradient; that is correct for an unused branch but wrong if the root is not the last node on the tape. The gradient array holds one Float per node, so memory grows with the graph.

Lean 4 Notes

State without mutation. StateM σ α is a function from a state of type σ to a pair: a result of type α and a new state. A do block in StateM joins such functions and passes the state from each to the next. Three operations use the state:

1 def step : StateM Nat Nat := do
2   let n ← get
3   set (n + 10)
4   return n * 2
5 
6 #eval step.run 5   -- (10, 15)

get reads the state and set replaces it. run supplies the first state and returns the result with the last state. modifyGet, which push uses, reads and replaces in one call.

The same syntax, another meaning. do, ←, and return look the same in Option, Except, StateM, and IO. Each of those types is a monad: it defines what “run this step, then the next” means. For Option it means stop at none. For StateM it means pass the state along. The type of the function tells you which one applies.

Steps inside expressions. push ⟨(← data a) + (← data b), .add a b⟩ runs data a and data b first, in that order, and then builds the node. (← e) saves you two let lines.

Anonymous constructors. ⟨d, .leaf⟩ builds a value of a structure type from its fields in order. It works only where Lean already knows the type. Here the parameter of push is a Node.

Why deriving Inhabited. tape[i]! must have a value to return if the index is out of range. Lean takes that value from the Inhabited instance of Node, and Node contains an Op, so both need one.

Statements in a do block. match in backward picks one branch of statements. A branch must do something, so the .leaf case uses pure (), a step with no effect. grad := grad.modify a f replaces element a with f applied to it.

Taking results apart. let ((a, b, c, d, e), tape) := graph.run #[] names all six parts of the result in one line.

Running It

 1 $ lean --run Autograd.lean
 2 Forward:  d = (a * b) + c = (2.0 * -3.0) + 10.0
 3           d = 4.0
 4           e = relu(d) = 4.0
 5 Gradients after backward:
 6   de/de = 1.00
 7   de/dd = 1.00
 8   de/dc = 1.00  (expected 1.0)
 9   de/da = -3.00  (expected b = -3.0)
10   de/db = 2.00  (expected a = 2.0)

Using It

Add operations such as sub, div, and tanh: add a constructor to Op, a function that pushes the node, and a case in backward. Lean reports Missing cases in backward until you add the case. With vadd, vmul, and an activation function you can build one neuron, compute the gradient of a loss, and write a small training loop.