Chapter 03Down the Rabbit Hole: What Writing a Toy Autograd Engine Taught Me
This started as a distraction. I was deep in a fine-tuning bug where gradients looked fine on paper but the loss wasn't moving. Instead of staring at the same loop a fourth hour, I asked the question I'd avoided for two years: what does .backward() actually do? Not the calculus. The code. Four hours later I had a ~150-line autograd engine and knew exactly where my real bug was.
The core idea is small#
Every autograd system records what produced a value, then walks that record backwards. A node remembers its inputs and knows how to push a gradient back to each:
class Value:
def __init__(self, data, children=(), op=""):
self.data = data
self.grad = 0.0
self._children = children
self._op = op
self._backward = lambda: None # filled in by the op that created it
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 outa.grad += 1 * out.grad ──▶ +1 b.grad += 1 * out.grad ──▶ +1 addition just passes the gradient through
a.grad += b.data * out.grad ──▶ +3 b.grad += a.data * out.grad ──▶ +2 each input gets the OTHER input's value
That's the trick. Each op knows its local derivative and how to distribute an incoming gradient. The graph is never a separate data structure; it falls out of the _children pointers, built by ordinary Python arithmetic.
a=2 ──┬──▶ [*] ──▶ t=6 ──▶ [+] ──▶ c=8 b=3 ──┘ ▲ a=2 ────────────────────────┘ grads: a=0 b=0 t=0 c=0
The forward pass builds the graph as it computes. Each output remembers its children.
Backward is a topological sort#
What had been a black box: how .backward() knows the visit order. A depth-first postorder, so by the time you process a node, everything downstream of it already has its gradient finalized.
def backward(self):
topo, visited = [], set()
def build(node):
if node not in visited:
visited.add(node)
for child in node._children:
build(child)
topo.append(node)
build(self)
self.grad = 1.0
for node in reversed(topo):
node._backward()This clicked in a way three deep learning courses hadn't: PyTorch can't compute a gradient until the full forward graph exists because the traversal needs it. It builds the whole dependency order, then walks it in reverse.
Where it paid off#
Back to the bug. Every layer's gradients were fine except one custom masking op, where the forward was right but the backward implicitly assumed the mask was constant. A .detach() was silently needed and missing. I wouldn't have looked there without rebuilding the exact mechanism that was misbehaving.
Toy implementations are usually framed as "build it to learn it". The more useful version is narrower: build the toy of the specific mechanism your real bug lives in, not the whole system. I didn't need a toy transformer. I needed a toy .backward().