Lab#DL-0003: Building micrograd

Lab

📘 Lab#DL-0003: Building micrograd

Manual backprop is “obviously ridiculous” for anything bigger than a toy, as Karpathy puts it. Each operation will now remember how to push a gradient to its inputs. backward() will sort the graph and call those functions in reverse. We also fix the bug that appears when one value is used twice, and we look at the same neuron in PyTorch — as a reading note, because the browser cell cannot import torch.

This lab follows Andrej Karpathy’s lecture The spelled-out intro to neural networks and backpropagation: building micrograd (playlist). The finished engine is engine.py in wikiml-zero-to-hero (z2h-01), derived from karpathy/micrograd (MIT Licence).

Code on GitHub

The cells are live Python in the browser, pure Python only.

1 Each operation stores a little _backward

At about 1:09:02 Karpathy hangs a closure on every new Value. The closure knows the parents of that node and the local rule we used by hand in the previous lab. It is not called yet. It is just filed away.

  • Addition: self.grad += out.grad and the same for the other parent.
  • Multiplication: multiply out.grad by the other factor.
  • \(\tanh\): multiply out.grad by \(1 - t^2\).

The += is not a flourish. We will need it the moment a value is used in two places.

2 backward(): sort, then walk in reverse

A node’s gradient is finished only after every node that depends on it has already passed gradient back. That is a topological order of the graph, walked in reverse, starting from the output with .grad = 1. Karpathy implements this at about 1:17:32.

The picture is a kitchen: you cannot put away a bowl until every dish that used it has been washed. Depth-first search, adding a node only after its children, gives you that order.

Ex#DL-3001

These should be the same gradients we filled in by hand: \(w_1 \approx 1\), \(x_1 \approx -1.5\), \(w_2 = 0\), \(x_2 \approx 0.5\), \(n \approx 0.5\). The engine has caught up with the notebook.

3 A value used twice must accumulate

Here is the bug Karpathy catches at 1:22:28. Suppose \(L = a + a\), or more honestly \(L = d * d\) with \(d\) coming from earlier. If _backward assigns (=) instead of adding (+=), the second use overwrites the first, and half the gradient vanishes.

The calculus is the multivariable chain rule: if \(L\) depends on \(a\) along two paths, the derivatives add. The everyday picture is two pipes into the same tank; you count both flows.

Ex#DL-3002

If you mentally replace += with = in __add__, a + a would report a.grad = 1. That is the bug. The same trap is why a training loop must zero the gradients before the next backward(): otherwise yesterday’s advice is still in the tank. We will meet that properly in the next lab.

4 The same neuron in PyTorch, as a reading note

From 1:39:31 Karpathy rebuilds the two-input neuron with torch.Tensor and requires_grad=True, calls .backward(), and checks that the gradients match micrograd. That comparison is the right one to have in your head. It is not runnable in this page: the browser kernel is Pyodide, which has no PyTorch, and we will not pretend otherwise.

If you run this on your own machine, with PyTorch installed, you should see the same \(2.0\), \(0.0\), \(-3.0\), \(1.0\) pattern we already have, and gradients about \(1\), \(0\), \(-1.5\), \(0.5\) on \(x_1, x_2, w_1, w_2\) — wait, on \(w_1, x_1, w_2, x_2\) as before. The API is noisier (dtype=float64, item(), grad); the mathematics is the same.

# Not run here: PyTorch is not available in the browser cell.
# Compare on your machine after: pip install torch
import torch

x1 = torch.Tensor([2.0]).double(); x1.requires_grad = True
x2 = torch.Tensor([0.0]).double(); x2.requires_grad = True
w1 = torch.Tensor([-3.0]).double(); w1.requires_grad = True
w2 = torch.Tensor([1.0]).double(); w2.requires_grad = True
b = torch.Tensor([6.8813735870195432]).double(); b.requires_grad = True
n = x1 * w1 + x2 * w2 + b
o = torch.tanh(n)
o.backward()
print(o.item(), n.item())
print("x1", x1.grad.item(), "w1", w1.grad.item())
print("x2", x2.grad.item(), "w2", w2.grad.item())

micrograd is not a toy because it is wrong. It is a toy because it is slow: it works on one scalar at a time. PyTorch batches those scalars into tensors so the same backward pass can run in parallel. The chain rule does not change.

5 Summary

Idea In one sentence
_backward A closure on each node that knows how to push out.grad to its parents.
Topological sort Visit a node only after its children; then walk that list in reverse.
backward() Set the output gradient to \(1\), then call _backward from the end of the graph to the start.
+=, not = A value used twice has two contributions, and they must add.
zero_grad The other side of +=: wipe yesterday’s gradients before the next backward pass.
PyTorch The same math, on tensors; not available in these browser cells.

6 FAQ

Why a closure, not a big if op == "+" switch? Each node already knows its parents and its operation. A closure captures exactly that, and backward() does not have to care what kind of node it is visiting.

What if the graph has a cycle? It should not. A computation graph of ordinary arithmetic is acyclic: you cannot use an output as its own ancestor. The visited set in build_topo also stops us from walking the same node twice.

Why does addition use += out.grad even when the two parents are different objects? Because the same object might also appear in another node. Using += everywhere means we never have to special-case “is this used twice?”.

Can I check a gradient without PyTorch? Yes: nudge the input by a tiny \(h\), re-run the forward pass, and divide the change in the output by \(h\), as in Lab#DL-0001. Karpathy does this constantly.

Where is this in the lecture? _backward from 1:09:02; backward() and the topological sort from 1:17:32; the “used twice” bug from 1:22:28; the PyTorch comparison from 1:39:31. Official YouTube chapter markers, checked on the video page (30 November 2026).

7 See also

8 References

Back to top