Scalar automatic differentiation

File: autograd.lisp

The core algorithm of every neural-network library, in about sixty lines: build a computation graph of scalar operations, then traverse it in reverse, accumulating gradients with the chain rule.

Each node records its value, its parents, and a closure that computes the local gradient of its operation. Reverse-mode differentiation sets the output’s gradient to Code Test and propagates backward: for Code Test the local rules are Code Test and Code Test; for addition both partials are Code Test; for Code Test the gradient passes only where the output is positive.

The code

 1 ;; sbcl --script autograd.lisp   (scalar automatic differentiation DAG)
 2 
 3 (defstruct (val (:constructor %val (data &optional prev op backward)))
 4   data (grad 0.0) prev op backward)
 5 
 6 (defun val (d) (if (val-p d) d (%val (float d 1.0))))
 7 
 8 (defun v+ (a b)
 9   (let* ((a (val a))
10          (b (val b))
11          (out (%val (+ (val-data a) (val-data b)) (list a b) '+)))
12     (setf (val-backward out)
13           (lambda ()
14             (incf (val-grad a) (val-grad out))
15             (incf (val-grad b) (val-grad out))))
16     out))
17 
18 (defun v* (a b)
19   (let* ((a (val a))
20          (b (val b))
21          (out (%val (* (val-data a) (val-data b)) (list a b) '*)))
22     (setf (val-backward out)
23           (lambda ()
24             (incf (val-grad a) (* (val-data b) (val-grad out)))
25             (incf (val-grad b) (* (val-data a) (val-grad out)))))
26     out))
27 
28 (defun v-relu (a)
29   (let* ((a (val a))
30          (out (%val (max 0.0 (val-data a)) (list a) 'relu)))
31     (setf (val-backward out)
32           (lambda ()
33             (incf (val-grad a)
34                   (if (> (val-data out) 0.0) (val-grad out) 0.0))))
35     out))
36 
37 (defun backward (root)
38   (let ((topo nil) (visited (make-hash-table :test 'eq)))
39     (labels ((build (v)
40                (unless (gethash v visited)
41                   (setf (gethash v visited) t)
42                   (dolist (p (val-prev v)) (build p))
43                   (push v topo))))
44       (build root))
45     (setf (val-grad root) 1.0)
46     (dolist (v topo)
47       (when (val-backward v) (funcall (val-backward v))))))
48 
49 ;; Demo: d = (a * b) + c,  e = relu(d)
50 (let* ((a (val 2.0))
51        (b (val -3.0))
52        (c (val 10.0))
53        (d (v+ (v* a b) c))
54        (e (v-relu d)))
55   (backward e)
56   (format t "Forward:  d = (a * b) + c = (~a * ~a) + ~a = ~a~%"
57           (val-data a) (val-data b) (val-data c) (val-data d))
58   (format t "          e = relu(d) = ~a~%" (val-data e))
59   (format t "Gradients after (backward e):~%")
60   (format t "  de/de = ~4,2f~%" (val-grad e))
61   (format t "  de/dd = ~4,2f~%" (val-grad d))
62   (format t "  de/dc = ~4,2f  (expected 1.0)~%" (val-grad c))
63   (format t "  de/da = ~4,2f  (expected b = -3.0)~%" (val-grad a))
64   (format t "  de/db = ~4,2f  (expected a = 2.0)~%" (val-grad b)))

How it works

  • defstruct with a renamed internal constructor %val is a common Lisp pattern: the public function val then acts as a smart constructor that coerces numbers to floats and returns existing nodes unchanged. That lets v+ accept (v+ 2 x) as easily as (v+ x y).
  • Each operation builds its output node, then installs a backward closure that captures the inputs. The closure adds (incf) to parent gradients rather than assigning them, which correctness requires when a value appears in the graph more than once: (v* x x) must give x a gradient of 2x, one term from each use.
  • backward sorts the graph topologically with a depth-first search (labels defines the local recursive build; an eq hash table tracks visited nodes), sets the root’s gradient to 1.0, and runs the closures in reverse topological order (root first), so each node’s gradient is final before its own closure runs.
  • op exists only for inspection and debugging; the closures do all the computation.

Running it

1 $ sbcl --script autograd.lisp

Actual output:

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

By hand, the forward pass is:

math

and since Code Test here (the relu is in its linear region), the chain rule gives:

math

This matches the program’s output exactly.

Using it

This is Andrej Karpathy’s micrograd idea, ported to Lisp. To turn it into a trainable neuron: add v-tanh or v-exp (each needs only its local gradient), build a dot product from v* and v+, and write a training loop that calls backward on a loss node and moves each leaf value by -lr * grad. One caveat: gradients accumulate in val-grad, so reset them to zero between training steps with a one-line zero-grad loop over the topo list.