Building a Tiny Autodiff Engine
The best way to understand backpropagation is to implement it. In about 40 lines of Python we build a scalar reverse-mode autodiff engine: a Value class that records the operations performed on it, and a backward method that sorts the graph topologically and applies the chain rule node by node. Then we train a small neural network with it. The design follows the familiar "micrograd" idea; the code here is written from scratch.
The Value class
Each Value stores its data, its gradient, its parent nodes and a closure _backward that knows how to send its gradient to the parents.
import math
class Value:
def __init__(self, data, parents=()):
self.data, self.grad = data, 0.0
self._parents, self._backward = parents, lambda: None
def __add__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data + other.data, (self, other))
def _backward():
self.grad += out.grad; other.grad += out.grad
out._backward = _backward; return out
def __mul__(self, other):
other = other if isinstance(other, Value) else Value(other)
out = Value(self.data * other.data, (self, other))
def _backward():
self.grad += other.data * out.grad; other.grad += self.data * out.grad
out._backward = _backward; return out
def tanh(self):
t = math.tanh(self.data); out = Value(t, (self,))
def _backward(): self.grad += (1 - t * t) * out.grad
out._backward = _backward; return out
__radd__ = __add__; __rmul__ = __mul__
def __neg__(self): return self * -1
def __sub__(self, other): return self + (-other)
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()
x, y = Value(2.0), Value(-3.0)
f = (x * y + x * x).tanh()
f.backward()
print(f"f = {f.data:.6f}, df/dx = {x.grad:.6f}, df/dy = {y.grad:.6f}")
t = math.tanh(2 * -3 + 4)
print(f"by hand: df/dx = {(1 - t * t) * (-3 + 4):.6f}, df/dy = {(1 - t * t) * 2:.6f}")f = -0.964028, df/dx = 0.070651, df/dy = 0.141302
by hand: df/dx = 0.070651, df/dy = 0.141302
Three details carry the whole algorithm:
- Gradients accumulate with
+=, implementing the fan-out rule ( is used three times above). backwardprocesses nodes in reverse topological order, so a node's gradient is complete before it is passed on.- The closures capture the forward values (
t,other.data) they need: this is the "tape".
Training a neuron layer with it
The same engine trains a tiny network. Each training step: zero the gradients, build the graph by running the forward pass, call backward, update.
import math, random
class Value:
def __init__(s, d, p=()): s.data, s.grad, s._p, s._b = d, 0.0, p, lambda: None
def __add__(s, o):
o = o if isinstance(o, Value) else Value(o); out = Value(s.data + o.data, (s, o))
def b(): s.grad += out.grad; o.grad += out.grad
out._b = b; return out
def __mul__(s, o):
o = o if isinstance(o, Value) else Value(o); out = Value(s.data * o.data, (s, o))
def b(): s.grad += o.data * out.grad; o.grad += s.data * out.grad
out._b = b; return out
def tanh(s):
t = math.tanh(s.data); out = Value(t, (s,))
def b(): s.grad += (1 - t * t) * out.grad
out._b = b; return out
__radd__ = __add__; __rmul__ = __mul__
def backward(s):
order, seen = [], set()
def visit(v):
if id(v) not in seen:
seen.add(id(v)); [visit(p) for p in v._p]; order.append(v)
visit(s); s.grad = 1.0
for v in reversed(order): v._b()
random.seed(0)
H = 4
W1 = [[Value(random.uniform(-1, 1)) for _ in range(2)] for _ in range(H)]; b1 = [Value(0.0) for _ in range(H)]
W2 = [Value(random.uniform(-1, 1)) for _ in range(H)]; b2 = Value(0.0)
params = [w for row in W1 for w in row] + b1 + W2 + [b2]
data = [((0, 0), -1), ((0, 1), 1), ((1, 0), 1), ((1, 1), -1)] # XOR with labels -1/+1
def model(x):
h = [(W1[j][0] * x[0] + W1[j][1] * x[1] + b1[j]).tanh() for j in range(H)]
return (sum((W2[j] * h[j] for j in range(H)), b2)).tanh()
for step in range(201):
loss = sum(((model(x) + (-y)) * (model(x) + (-y)) for x, y in data), Value(0.0))
for p in params: p.grad = 0.0
loss.backward()
for p in params: p.data -= 0.1 * p.grad
if step % 50 == 0: print(f"step {step}: loss {loss.data:.4f}")
print("outputs:", [round(model(x).data, 3) for x, _ in data])step 0: loss 4.1676
step 50: loss 0.3553
step 100: loss 0.0578
step 150: loss 0.0279
step 200: loss 0.0177
outputs: [-0.954, 0.933, 0.931, -0.921]
From scalars to tensors
Real frameworks use the same design with tensors as nodes: each operation (matrix multiply, softmax, convolution) has a hand-written vectorized backward rule, such as for a matrix product (Backpropagation Through an MLP). A scalar engine creates one node per number and is millions of times slower, but the algorithm is identical.
In software
- PyTorch's autograd: every tensor produced by an operation has a
grad_fnnode;.backward()runs a topological traversal like the one above, in C++. loss.backward()accumulates into.grad, which is why training loops calloptimizer.zero_grad()each step.- Custom operations are added by writing
forwardandbackward(torch.autograd.Function), exactly like the closures here.
Go further: A Small Autograd Engine for Arrays extends this scalar engine to NumPy arrays, and the next lesson trains an MLP with it.
Exercises
Exercise 1: Why +=?
What goes wrong if _backward uses = instead of += in the expression x * x?
Answer
The gradient would be instead of .
Solution
Both "parents" of the multiply node are the same object. With =, the second assignment overwrites the first, losing one of the two paths.
Exercise 2: Forgetting zero_grad
If a training loop never resets grad to 0, what does each update use?
Answer
The sum of all gradients so far.
Solution
Gradients accumulate across backward calls, so step would use , acting like a growing, stale momentum. (Accumulating on purpose over a few micro-batches is how gradient accumulation simulates a large batch.)
Exercise 3: Add an exp node (code)
Add an exp method to a minimal Value class and check at against .
Answer
Both give about .
Solution
The local derivative of is itself.
import math
class V:
def __init__(s, d, p=()): s.data, s.grad, s.p, s.b = d, 0.0, p, lambda: None
def __mul__(s, o):
out = V(s.data * o.data, (s, o))
def b(): s.grad += o.data * out.grad; o.grad += s.data * out.grad
out.b = b; return out
def exp(s):
e = math.exp(s.data); out = V(e, (s,))
def b(): s.grad += e * out.grad
out.b = b; return out
x = V(0.5); u = x * x; f = u.exp()
f.grad = 1.0; f.b(); u.b() # reverse order by hand
print(round(x.grad, 4), round(2 * 0.5 * math.exp(0.25), 4))1.284 1.284
Test yourself
In what order does backward call the nodes' local backward functions?
- Random order
- Reverse topological order
- Alphabetical order
- Forward order
Why must gradients be accumulated with +=?
- For speed
- A value used several times receives gradient along every path
- To avoid NaNs
- Python requires it
What does PyTorch's optimizer.zero_grad() prevent?
- Exploding activations
- Gradients from previous steps adding into the current one
- Overfitting
- Dead ReLUs