← Back to all chapters

Chapter 03Down the Rabbit Hole: What Writing a Toy Autograd Engine Taught Me

3 min read
deep-learninglearning-in-publicpytorch

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 out
a.grad += 1 * out.grad     ──▶  +1
b.grad += 1 * out.grad     ──▶  +1
addition just passes the gradient through
out = a + b
Local derivatives, with a=2, b=3 and out.grad = 1

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.

1/4Forward
 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 on c = a * b + a, with a=2, b=3. Step through.
a=2b=3*t=6+c=8grad 4grad 2grad 1grad 1a collects 3 (through *) + 1 (direct), so grad a = 4
The graph behind c = a * b + a. Forward goes left to right; gradients flow back right to left.

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()
postorder DFS from c: visit children first, append on the way outabtcrun _backward() in reversectbaevery node runs only after all its consumers have
Visit order for the example graph.

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.

without detach: the gradient also flows into whatever produced the maskxmaskmasked oplosswith detach: values still flow forward, gradient stops at the cutxmaskdetach()masked oplossstop
What .detach() does to the backward walk. Schematic of the mechanism, not my actual model.

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().

© 2026 Bharat Kaurav. Built with Next.js & Tailwind.

>_ bk@netherwatcheresc to close

Welcome, reader. Type help to see what this shell can do.