Project: build micrograd¶
In about 150 lines of plain Python, with no NumPy and no framework, you will build a working automatic-differentiation engine and a small neural-network library on top of it, then train a 337-parameter network to 98.5% held-out accuracy. When you finish, loss.backward() will never again be a black box.
10,000 ft
Every neural network ever trained, from LeCun's 1989 digit reader to a 2026 frontier model, learns by the same loop: compute a loss, get its gradient with respect to every parameter, take a step downhill. The gradient comes from reverse-mode automatic differentiation: record the computation as a graph, then walk it backwards applying the chain rule (backpropagation, autodiff). PyTorch, JAX and MLX are that idea plus tensors, GPUs and decades of engineering. micrograd, Andrej Karpathy's 2020 teaching engine, is that idea with nothing else: every number is a scalar node, so you can print the whole machine. It is the first rung of the project ladder because everything above it (a GPT, LoRA, RL from feedback) is this engine at larger scale.
2,000 ft
A Value holds a number and remembers which Values produced it and how. Arithmetic on Values therefore builds a graph as a side effect. Each operation also leaves behind a tiny closure that knows its local derivative. backward() sorts the graph so every node comes after its inputs, sets \(\partial L/\partial L = 1\), and runs the closures in reverse: each one multiplies the gradient arriving from above by its local derivative and adds the result into its inputs' gradients. Wrap neurons around Values and you have a neural network library; add a loss and a loop and it learns.
Ground level¶
What you are building, and the rules¶
| file | contents | lines |
|---|---|---|
engine.py |
the Value class: data, gradient, graph edges, eight primitive operations, backward() |
~90 |
nn.py |
Module, Neuron, Layer, MLP |
~40 |
test_engine.py |
hand-worked gradients, the README expression, finite-difference checks | ~40 |
train_moons.py |
dataset, hinge loss, L2, the training loop, a held-out test | ~45 |
Rules. Python 3 standard library only (math, random). Type the code rather than pasting it: the point is to make each line a decision you understand. Do not move to the next milestone until the current one's expected output matches exactly; every number below was produced by running this code (Python 3.12).
Time. Four to six focused hours. Karpathy's two-and-a-half-hour lecture builds the same thing live; watch it after you have tried each milestone yourself, not before.
Milestone 1: a number that remembers where it came from¶
Start with a class that wraps a float and records its parents:
class Value:
def __init__(self, data, _children=(), _op=''):
self.data = data
self._prev = set(_children)
self._op = _op
def __add__(self, other): return Value(self.data + other.data, (self, other), '+')
def __mul__(self, other): return Value(self.data * other.data, (self, other), '*')
def __repr__(self): return f"Value(data={self.data})"
a, b, c, f = Value(2.0), Value(-3.0), Value(10.0), Value(-2.0)
e = a * b; d = e + c; L = d * f
print(L, L._op, [p.data for p in L._prev])
(The order of the parent list can differ; it is a set.) Nothing clever has happened yet, but L now is a graph: from L you can reach every number that influenced it. That graph is the data structure all of deep learning runs on. PyTorch builds exactly this when you compute with tensors that have requires_grad=True; it is called define-by-run because the graph is recorded as the code executes.
Milestone 2: derivatives by hand, then local rules¶
Before writing any backward code, compute the gradients of \(L = (ab + c)\,f\) by hand at \(a=2, b=-3, c=10, f=-2\). Name the intermediates \(e = ab = -6\) and \(d = e + c = 4\), so \(L = df = -8\).
- \(\partial L/\partial L = 1\).
- \(L = d f\), so \(\partial L/\partial f = d = 4\) and \(\partial L/\partial d = f = -2\).
- \(d = e + c\): addition has local derivative 1 for both inputs, so it copies the gradient: \(\partial L/\partial e = \partial L/\partial c = -2\).
- \(e = ab\): multiplication's local derivative for each input is the other input, so it swaps and scales: \(\partial L/\partial a = b \cdot(-2) = 6\) and \(\partial L/\partial b = a\cdot(-2) = -4\).
Those two rules generalise to every operation: a node only needs to know its own local derivative. Turn that into code by giving every Value a grad (initially 0) and a _backward closure that pushes out.grad to the parents:
def __add__(self, other):
out = Value(self.data + other.data, (self, other), '+')
def _backward():
self.grad += out.grad # local derivative 1
other.grad += out.grad
out._backward = _backward
return out
def __mul__(self, 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
The closure captures self, other and out, so it can run long after __mul__ has returned. Test it by calling the closures by hand in reverse order: L.grad = 1.0; L._backward(); d._backward(); e._backward(), then print a.grad and b.grad. You should see 6.0 -4.0.
Why +=, not =
A value used twice (y = x + x, or a weight shared across 100 training examples) receives gradient along every path, and the multivariable chain rule says those contributions add. Write self.grad = out.grad and y = x + x silently gives \(dy/dx = 1\) instead of 2: the second assignment overwrites the first, because self and other are the same object. The run below uses exactly that bug. It is the most common mistake in every from-scratch autodiff, and it is also why you must zero the gradients before each training step.
Milestone 3: backward() in topological order¶
Calling closures by hand only works because you knew the order. In general, a node's _backward may run only after the gradient arriving at it is complete, which means after every node that uses it has run. Ordering the graph so that each node comes after its inputs is a topological sort; running the closures over it in reverse guarantees the condition. A post-order depth-first search produces one:
def backward(self):
topo, seen = [], set()
def build(v): # post-order DFS = topological order
if v not in seen:
seen.add(v)
for child in v._prev:
build(child)
topo.append(v) # appended only after all its inputs
build(self)
self.grad = 1.0 # dL/dL = 1
for v in reversed(topo):
v._backward()
Leaf nodes keep the default _backward = lambda: None (set it in __init__, along with self.grad = 0.0). Run the three checks:
a, b, c, f = Value(2.0), Value(-3.0), Value(10.0), Value(-2.0)
e = a * b; d = e + c; L = d * f
L.backward()
print("L =", L.data, "| grads a b c f:", a.grad, b.grad, c.grad, f.grad, "| d e:", d.grad, e.grad)
x = Value(3.0); y = x + x; y.backward(); print("d(x+x)/dx =", x.grad)
x = Value(3.0); y = x * x; y.backward(); print("d(x*x)/dx =", x.grad)
With the overwrite bug from the pitfall above, the second line prints buggy d(x+x)/dx = 1.0. Check that yours prints 2.
What backward really is
The gradient of \(L\) with respect to a node is the sum, over every path from that node to \(L\), of the product of the local derivatives along the path. The number of paths can grow exponentially with depth; reverse topological order lets every node compute its sum once and reuse it, so the backward pass costs about as much as the forward pass. That is dynamic programming, and it is the whole reason training billion-parameter models is possible (First principles).
Milestone 4: enough operations to build a neural network¶
Every remaining operation is the same pattern: compute the output, then write the local derivative.
| operation | forward | local derivative used in _backward |
|---|---|---|
x ** k (constant \(k\)) |
\(x^k\) | \(k x^{k-1}\) |
x.exp() |
\(e^x\) | \(e^x\), reuse out.data |
x.log() |
\(\ln x\) | \(1/x\) |
x.tanh() |
\(t = \tanh x\) | \(1 - t^2\) |
x.relu() |
\(\max(0, x)\) | \(1\) if \(x > 0\) else \(0\) |
Subtraction, negation and division need no backward code at all: define them from the primitives (-x is x * -1, a - b is a + (-b), a / b is a * b**-1) and the chain rule takes care of them. Add __radd__, __rmul__, __rsub__ and __rtruediv__ so that 2 * x and 1 + x work, and let __add__ and __mul__ wrap plain numbers in Value. The full file is in Build it.
The acceptance test is the expression from the micrograd README, which exercises every operation, uses values more than once, and mixes in-place updates:
a = Value(-4.0); b = Value(2.0)
c = a + b
d = a * b + b**3
c += c + 1
c += 1 + c + (-a)
d += d * 2 + (b + a).relu()
d += 3 * d + (b - a).relu()
e = c - d
f = e**2
g = f / 2.0
g += 10.0 / f
g.backward()
print(f"g = {g.data:.4f} dg/da = {a.grad:.4f} dg/db = {b.grad:.4f}")
These match the README's numbers (which were checked against PyTorch). Note what c += c + 1 does: it does not mutate c; it creates a new node and rebinds the name, so the old c stays in the graph as a parent. That is why the graph stays correct.
Milestone 5: trust nothing, check gradients numerically¶
You have one test that passes. Before building on the engine, check it against the definition of a derivative. The central difference
has error \(O(h^2)\) (the \(h^2\) term of the Taylor expansion cancels), so with \(h = 10^{-6}\) it agrees with the analytic gradient to about 8 significant figures:
Make this a reusable test: perturb every parameter of a small network, one at a time, and compare. On an MLP(3, [4, 4, 1]) with a squared-error loss over four examples (code in Build it):
A worst-case error of \(10^{-9}\) means the engine is right. An error near \(10^{-2}\) means a wrong local derivative; an error that is exactly the analytic value (or half of it) usually means a missing +=. Two caveats: finite differences are unreliable where the function has a kink (ReLU at exactly 0), and they cost two forward passes per parameter, which is why we use them only to test.
Milestone 6: neurons, layers and an MLP¶
A neuron computes \(\phi(\sum_i w_i x_i + b)\). With Values, that is one line, and the library is three small classes that each know how to list their parameters:
class Neuron(Module):
def __init__(self, nin, nonlin=True):
self.w = [Value(random.uniform(-1, 1)) for _ in range(nin)]
self.b = Value(0.0)
self.nonlin = nonlin
def __call__(self, x):
act = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
return act.relu() if self.nonlin else act
def parameters(self): return self.w + [self.b]
Layer holds nout neurons and returns their outputs; MLP chains layers and makes the last layer linear (no ReLU), because a ReLU output could never go negative and the loss below needs signed scores. Module.zero_grad() sets every parameter's grad to 0. For MLP(2, [16, 16, 1]) the count is \((2+1)\cdot16 + (16+1)\cdot16 + (16+1)\cdot1 = 48 + 272 + 17 = 337\) parameters.
This mirrors PyTorch's nn.Module deliberately: parameters(), zero_grad() and __call__ are the same idea. In PyTorch a layer stores one weight matrix and does one matrix multiply; here a layer is a list of neurons doing scalar arithmetic. Same mathematics, about \(10^5\) times slower.
Milestone 7: train it¶
The dataset is "two moons": two interleaved half-circles that no straight line can separate, the same task as the micrograd demo notebook. We generate it in pure Python (a re-implementation of scikit-learn's make_moons) with labels \(\pm 1\).
The loss is the SVM hinge loss plus a small L2 penalty, as in the original demo:
where \(s_i\) is the network's score. A point contributes nothing once it is on the right side with margin \(y_i s_i \ge 1\); otherwise it pulls its score in the right direction with gradient \(-y_i\). That is why the loss is built from relu: \(\max(0, z)\) is a ReLU. The optimiser is plain gradient descent on the full batch, with the learning rate decaying linearly from 1.0 to 0.1.
Running train_moons.py (100 steps, seed 1337) prints:
parameters: 337
step 0 loss 0.9510 accuracy 50%
step 10 loss 0.1730 accuracy 94%
step 20 loss 0.1494 accuracy 95%
step 30 loss 0.1185 accuracy 97%
step 40 loss 0.0921 accuracy 97%
step 50 loss 0.0722 accuracy 97%
step 60 loss 0.0588 accuracy 98%
step 70 loss 0.0532 accuracy 98%
step 80 loss 0.0451 accuracy 99%
step 90 loss 0.0377 accuracy 99%
step 99 loss 0.0350 accuracy 99%
65 s
held-out accuracy: 98.5%
........................................
........................................
........................................
........................................
.............++++++.................++++
............+++++++++..........+++++++++
...........+++++++++++++..++++++++++++++
..........++++++++++++++++++++++++++++++
..........++++++++++++++++++++++++++++++
.............+++++++++++++++++++++++++++
The text map is the learned decision boundary over \(x \in [-1.5, 2.4]\), \(y \in [-0.75, 1.5]\): + is the region the network assigns to the lower moon. It curves up between the two moons, which a linear model could never do.
Read the numbers, not just the final line:
- Step 0: loss 0.951, accuracy 50%. With random weights, scores are small and the hinge term is close to 1 for every point. Accuracy at chance is the right start; if your step-0 loss were 30, your initialisation would be broken.
- A fast drop, then a slow tail. Most points are classified by step 10; the remaining 90 steps push the hard points near the boundary past the margin.
- About a minute for 100 steps (65 s on the run shown; a busy laptop took 100 s). Each step builds and differentiates a graph of 68,818
Valuenodes (counted by walking the graph), so the engine processes about 7 million nodes in a minute: roughly 10 microseconds per scalar operation, forward and backward. A GPU multiplies two \(8192\times8192\) matrices, about \(10^{12}\) scalar operations, in well under a second. The gap is not the algorithm; it is vectorisation, memory layout and hardware. That is what Project: build a tiny GPT and the systems track are about.
How you know you have succeeded¶
You are done when all of these are true:
- The Milestone 3 checks print
6.0 -4.0 -2.0 4.0,2.0and6.0. - The README expression prints
24.7041,138.8338,645.5773. - The gradient check on a fresh MLP gives a worst-case error below \(10^{-6}\).
- Training on moons reaches at least 97% held-out accuracy.
- Without looking, you can write
__mul__'s_backwardandbackward()on a whiteboard, and explain why the gradients must be zeroed each step. - You can answer every question in Check yourself.
History¶
Reverse-mode differentiation predates neural networks: Seppo Linnainmaa described it for arbitrary programs of elementary operations in his 1970 master's thesis, and Rumelhart, Hinton and Williams's 1986 Nature paper showed what it could do for hidden layers (the full story). Tape-based and operator-overloading autodiff tools followed through the 1980s and 1990s in scientific computing. In machine learning, Theano and the first versions of TensorFlow (2015) built a static graph first and executed it later; Chainer (2015) and then PyTorch (released 2017) recorded the graph as the program ran, the define-by-run style you have just implemented. Karpathy published micrograd in April 2020 as a teaching tool and recorded the spelled-out lecture in 2022 as the first part of Neural Networks: Zero to Hero. In February 2026 he released microgpt, a dependency-free GPT trainer in one Python file whose autograd is a variant of this engine: each node stores its local gradients as numbers instead of a closure, and backward() multiplies them along the reversed topological order.
First principles¶
Why a graph at all. A program that computes a loss is a composition of primitive operations. The chain rule says the derivative of a composition is assembled from the derivatives of its parts. To apply it mechanically you need two things the program does not normally keep: which operations happened, and the intermediate values they used. The graph of Values keeps both. This is the memory cost of training: every activation of the forward pass is stored until the backward pass consumes it.
Why reverse rather than forward. Forward-mode differentiation pushes \(\partial(\text{node})/\partial a\) from one input towards the output, so getting the gradient for \(P\) parameters needs \(P\) passes. Reverse mode pulls \(\partial L/\partial(\text{node})\) from the one output back to all inputs in a single pass. A loss is one number and a model has millions of parameters, so reverse mode wins by a factor of \(P\) (autodiff treats both modes).
Why the cost is a constant times the forward pass. Each edge of the graph is touched once forwards and once backwards, and each _backward does a constant amount of work. Baur and Strassen proved the general version in 1983: the full gradient of a function costs a small constant factor more than evaluating it. This "cheap gradient principle" is why the field could scale.
Why only local knowledge is needed. The chain rule factorises: \(\partial L/\partial a = \sum_{v\,\in\,\text{users}(a)} \frac{\partial L}{\partial v}\frac{\partial v}{\partial a}\). The first factor arrives from above; the second is purely local. So each operation is a sealed unit with a forward rule and a backward rule. Adding a new operation (say, sigmoid) never requires touching any other code. That modularity is why frameworks can grow to thousands of operations.
What breaks if you change the design.
- Run
backward()twice without zeroing: gradients double, because they accumulate. PyTorch has the same behaviour, which is useful for gradient accumulation across micro-batches and a bug otherwise. - Use a value in the graph, then mutate its
.data: the closures captured the object, not a copy, so the backward pass uses the new value and silently computes a wrong gradient. PyTorch detects this with version counters on tensors and raises an error. - Make the closure read
self.dataforexp's derivative and recompute \(e^x\): correct, but you pay the exponential twice. Reusingout.datais the first example of a real framework trick: save what the backward pass needs during the forward pass. - Differentiate the gradient: you cannot, because
_backwarddoes arithmetic on raw floats, notValues, so it builds no graph. Higher-order derivatives (Hessian-vector products, MAML) need the backward pass itself to be recorded; PyTorch'screate_graph=Truedoes exactly that.
The maths¶
The setting. The program defines nodes \(v_1, \dots, v_n\) in topological order, with \(v_n = L\). Each non-leaf node is \(v_j = f_j(v_{i} : i \in \text{pa}(j))\) for a primitive \(f_j\). Define the adjoint \(\bar v_i = \partial L/\partial v_i\) (this is what .grad stores).
The recurrence. By the multivariable chain rule,
Processing \(j = n, n-1, \dots, 1\) and, at each \(j\), adding \(\bar v_j \,\partial f_j/\partial v_i\) into each parent's accumulator computes exactly this sum: every term is added once, and \(\bar v_j\) is complete before it is used, because all of \(v_j\)'s users come later in topological order. The += is the \(\sum\).
The local derivatives you implemented, derived
- Addition \(v = a + b\): \(\partial v/\partial a = \partial v/\partial b = 1\).
- Multiplication \(v = ab\): \(\partial v/\partial a = b\), \(\partial v/\partial b = a\).
- Power \(v = a^k\), \(k\) constant: \(\partial v/\partial a = k a^{k-1}\). Division \(a/b = a \cdot b^{-1}\) then gives \(\partial/\partial b = -a b^{-2}\) automatically.
- Exponential \(v = e^a\): \(\partial v/\partial a = e^a = v\).
- Logarithm \(v = \ln a\): \(\partial v/\partial a = 1/a\).
-
tanh \(v = \tanh a = \dfrac{e^a - e^{-a}}{e^a + e^{-a}}\). By the quotient rule,
\[ \frac{dv}{da} = \frac{(e^a + e^{-a})^2 - (e^a - e^{-a})^2}{(e^a + e^{-a})^2} = 1 - \tanh^2 a = 1 - v^2 . \] -
ReLU \(v = \max(0, a)\): derivative 1 for \(a > 0\), 0 for \(a < 0\); at \(a = 0\) any value in \([0, 1]\) is a valid subgradient and we use 0, as PyTorch does.
A worked neuron. Take \(o = \tanh(x_1 w_1 + x_2 w_2 + b)\) with \(x_1 = 2, x_2 = 0, w_1 = -3, w_2 = 1, b = 6.8814\) (the numbers from Karpathy's lecture, chosen so the pre-activation is \(n = 0.8814\) and \(o = \tanh(0.8814) = 0.7071\)). Then \(\partial o/\partial n = 1 - 0.7071^2 = 0.5\), and since \(n\) is a sum of products:
Your engine prints o = 0.7071 grads x1 -1.5000 w1 1.0000 x2 0.5000 w2 0.0000. Note \(\partial o/\partial w_2 = 0\): a weight attached to an input of 0 gets no gradient, which is why inputs are normalised in practice.
The hinge loss gradient. For one point, \(\ell = \max(0, 1 - y s)\), so \(\partial\ell/\partial s = -y\) if \(ys < 1\) and \(0\) otherwise. Only points inside the margin teach. The L2 term adds \(2\lambda w_j\) to each parameter's gradient: gradient descent with it multiplies each weight by \((1 - 2\eta\lambda)\) before the data step, which is why L2 is called weight decay.
Cost accounting. Forward and backward each touch every one of the 68,818 nodes once, and a gradient step touches 337 parameters. Memory is \(O(\text{nodes})\): every intermediate is alive until backward() finishes. For a transformer the same accounting says activation memory grows with batch size × sequence length × width × depth, which is why activation checkpointing exists.
Build it¶
Here are the four files in full. They contain exactly the code that produced the outputs on this page.
engine.py: the complete autograd engine (88 lines)
import math
class Value:
"""A scalar that remembers how it was computed, so it can send gradients back."""
def __init__(self, data, _children=(), _op=''):
self.data = data
self.grad = 0.0
self._backward = lambda: None # pushes self.grad into the children's .grad
self._prev = set(_children)
self._op = _op
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 # d(a+b)/da = 1
other.grad += out.grad # d(a+b)/db = 1
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 # d(ab)/da = b
other.grad += self.data * out.grad # d(ab)/db = a
out._backward = _backward
return out
def __pow__(self, k):
assert isinstance(k, (int, float)), "only constant powers"
out = Value(self.data ** k, (self,), f'**{k}')
def _backward():
self.grad += k * self.data ** (k - 1) * out.grad
out._backward = _backward
return out
def exp(self):
out = Value(math.exp(self.data), (self,), 'exp')
def _backward():
self.grad += out.data * out.grad # d(e^x)/dx = e^x, already computed
out._backward = _backward
return out
def log(self):
out = Value(math.log(self.data), (self,), 'log')
def _backward():
self.grad += (1 / self.data) * out.grad
out._backward = _backward
return out
def tanh(self):
t = math.tanh(self.data)
out = Value(t, (self,), 'tanh')
def _backward():
self.grad += (1 - t * t) * out.grad
out._backward = _backward
return out
def relu(self):
out = Value(max(0.0, self.data), (self,), 'ReLU')
def _backward():
self.grad += (out.data > 0) * out.grad
out._backward = _backward
return out
def backward(self):
topo, seen = [], set()
def build(v): # post-order DFS = topological order
if v not in seen:
seen.add(v)
for child in v._prev:
build(child)
topo.append(v)
build(self)
self.grad = 1.0 # dL/dL = 1
for v in reversed(topo):
v._backward()
# everything else is built from the ops above
def __neg__(self): return self * -1
def __radd__(self, other): return self + other
def __sub__(self, other): return self + (-other)
def __rsub__(self, other): return other + (-self)
def __rmul__(self, other): return self * other
def __truediv__(self, other): return self * other ** -1
def __rtruediv__(self, other): return other * self ** -1
def __repr__(self): return f"Value(data={self.data:.4f}, grad={self.grad:.4f})"
nn.py: Module, Neuron, Layer, MLP
import random
from engine import Value
class Module:
def parameters(self): return []
def zero_grad(self):
for p in self.parameters():
p.grad = 0.0
class Neuron(Module):
def __init__(self, nin, nonlin=True):
self.w = [Value(random.uniform(-1, 1)) for _ in range(nin)]
self.b = Value(0.0)
self.nonlin = nonlin
def __call__(self, x):
act = sum((wi * xi for wi, xi in zip(self.w, x)), self.b)
return act.relu() if self.nonlin else act
def parameters(self): return self.w + [self.b]
class Layer(Module):
def __init__(self, nin, nout, **kw):
self.neurons = [Neuron(nin, **kw) for _ in range(nout)]
def __call__(self, x):
out = [n(x) for n in self.neurons]
return out[0] if len(out) == 1 else out
def parameters(self): return [p for n in self.neurons for p in n.parameters()]
class MLP(Module):
def __init__(self, nin, nouts):
sz = [nin] + nouts
self.layers = [Layer(sz[i], sz[i + 1], nonlin=i != len(nouts) - 1)
for i in range(len(nouts))]
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x
def parameters(self): return [p for l in self.layers for p in l.parameters()]
test_engine.py: every hand-worked number on this page, as assertions
import math
from engine import Value
# Milestone 3: the hand-worked graph, and values used twice
a, b, c, f = Value(2.0), Value(-3.0), Value(10.0), Value(-2.0)
e = a * b; d = e + c; L = d * f
L.backward()
assert (a.grad, b.grad, c.grad, f.grad, d.grad, e.grad) == (6.0, -4.0, -2.0, 4.0, -2.0, -2.0)
x = Value(3.0); y = x + x; y.backward(); assert x.grad == 2.0
x = Value(3.0); y = x * x; y.backward(); assert x.grad == 6.0
# Milestone 4: the micrograd README expression
def readme(av, bv):
a = Value(av); b = Value(bv)
c = a + b
d = a * b + b**3
c += c + 1
c += 1 + c + (-a)
d += d * 2 + (b + a).relu()
d += 3 * d + (b - a).relu()
e = c - d
f = e**2
g = f / 2.0
g += 10.0 / f
return a, b, g
a, b, g = readme(-4.0, 2.0); g.backward()
print(f"g = {g.data:.4f} dg/da = {a.grad:.4f} dg/db = {b.grad:.4f}")
assert abs(a.grad - 138.8338) < 1e-4 and abs(b.grad - 645.5773) < 1e-4
# Milestone 5: central differences on the same expression
h = 1e-6
na = (readme(-4.0 + h, 2.0)[2].data - readme(-4.0 - h, 2.0)[2].data) / (2 * h)
nb = (readme(-4.0, 2.0 + h)[2].data - readme(-4.0, 2.0 - h)[2].data) / (2 * h)
print(f"numeric: dg/da = {na:.4f} dg/db = {nb:.4f}")
# The worked neuron from "The maths"
x1, x2, w1, w2, bb = Value(2.0), Value(0.0), Value(-3.0), Value(1.0), Value(6.8813735870195432)
o = (x1 * w1 + x2 * w2 + bb).tanh(); o.backward()
print(f"o = {o.data:.4f} grads x1 {x1.grad:.4f} w1 {w1.grad:.4f} x2 {x2.grad:.4f} w2 {w2.grad:.4f}")
# exp, log and division against the closed form of d/dx (e^x + ln x) / x
x = Value(0.5); y = (x.exp() + x.log()) / x; y.backward()
exact = ((math.exp(.5) + 1 / .5) * .5 - (math.exp(.5) + math.log(.5))) / .25
assert abs(x.grad - exact) < 1e-12
print("all engine tests passed")
gradcheck.py: finite differences against backward() on every parameter
import random
from nn import MLP
random.seed(0)
model = MLP(3, [4, 4, 1])
xs = [[2.0, 3.0, -1.0], [3.0, -1.0, 0.5], [0.5, 1.0, 1.0], [1.0, 1.0, -1.0]]
ys = [1.0, -1.0, -1.0, 1.0]
def loss_fn():
return sum((model(x) - y) ** 2 for x, y in zip(xs, ys))
loss = loss_fn(); model.zero_grad(); loss.backward()
worst, h = 0.0, 1e-6
for p in model.parameters():
old = p.data
p.data = old + h; up = loss_fn().data
p.data = old - h; down = loss_fn().data
p.data = old
worst = max(worst, abs((up - down) / (2 * h) - p.grad))
print(f"{len(model.parameters())} parameters, worst |analytic - numeric| = {worst:.2e}")
def count(v, seen=None): # how big is the graph?
seen = set() if seen is None else seen
if v in seen: return 0
seen.add(v); return 1 + sum(count(c, seen) for c in v._prev)
print("graph nodes for 4 examples:", count(loss))
train_moons.py: data, loss, training loop, held-out test
import math, random, time
from nn import MLP
def make_moons(n=100, noise=0.1, seed=1):
"""Two interleaved half-circles, labels -1 / +1 (a pure-Python sklearn.make_moons)."""
rng = random.Random(seed)
pts = []
for i in range(n):
t = math.pi * rng.random()
if i % 2 == 0: x, y, lab = math.cos(t), math.sin(t), -1 # upper moon
else: x, y, lab = 1 - math.cos(t), 0.5 - math.sin(t), 1 # lower moon
pts.append(([x + rng.gauss(0, noise), y + rng.gauss(0, noise)], lab))
return pts
random.seed(1337)
data = make_moons()
model = MLP(2, [16, 16, 1])
print("parameters:", len(model.parameters()))
def loss_and_acc():
scores = [model(x) for x, _ in data]
margins = [(1 + -y * s).relu() for (_, y), s in zip(data, scores)] # SVM hinge
data_loss = sum(margins) * (1.0 / len(margins))
reg = 1e-4 * sum(p * p for p in model.parameters()) # L2
acc = sum((s.data > 0) == (y > 0) for (_, y), s in zip(data, scores)) / len(data)
return data_loss + reg, acc
t0 = time.time()
for k in range(100):
loss, acc = loss_and_acc()
model.zero_grad()
loss.backward()
lr = 1.0 - 0.9 * k / 100 # linear decay
for p in model.parameters():
p.data -= lr * p.grad
if k % 10 == 0 or k == 99:
print(f"step {k:3d} loss {loss.data:.4f} accuracy {acc:.0%}")
print(f"{time.time() - t0:.0f} s")
test = make_moons(n=200, seed=2)
test_acc = sum((model(x).data > 0) == (y > 0) for x, y in test) / len(test)
print(f"held-out accuracy: {test_acc:.1%}")
for r in range(10): # the learned boundary, as text
yy = 1.5 - r * 0.25
print("".join("+" if model([-1.5 + c * 0.1, yy]).data > 0 else "." for c in range(40)))
Run the files from one folder: python test_engine.py, python gradcheck.py, python train_moons.py. The engine's recursive build() reaches Python's default recursion limit (1,000) only for graphs deeper than that; if you build deep chains, rewrite it with an explicit stack, as in the node-counting code above.
Stretch goals, roughly in order of difficulty
- Draw the graph. Write
draw_dot(root)with thegraphvizpackage (one record node perValueshowingdataandgrad, one small node per_op). Karpathy'strace_graph.ipynbin the micrograd repo shows the idea. - Cross-entropy instead of hinge. Give the MLP two outputs, add a numerically stable softmax (subtract the max logit first: see log-sum-exp) and train with negative log-likelihood. Confirm the step-0 loss is close to \(\ln 2 = 0.693\).
- Mini-batches and momentum. Sample 32 points per step and add momentum (\(v \leftarrow 0.9v + g\), \(p \leftarrow p - \eta v\)). Compare the loss curves and wall-clock time (optimisers).
- Iterative topological sort. Replace recursion with an explicit stack, then train a 30-layer, 4-wide MLP. Watch the gradients of the first layer vanish (initialisation).
- Second derivatives. Make
_backwardbuildValues instead of floats (acreate_graphmode) and compute \(d^2/dx^2\) of \(x^3\) at \(x = 2\) (answer: 12). - Vectorise. Re-implement the engine with NumPy arrays as
data, writing backward rules formatmul,sumand broadcasting. Time it against the scalar engine on the same MLP. Build a GPT from scratch contains a full array engine to compare yours with. - A character model. Use the engine for a bigram, then an MLP language model on a list of names, as in Karpathy's makemore lectures. Then read microgpt end to end: it is your engine plus attention, RMSNorm and Adam, about 200 lines.
- Port it. Write the engine in a language without operator overloading (Go or C). You will discover that the closures were doing a lot of work.
Common misconceptions¶
- "Backprop is a learning algorithm." It is a way to compute a gradient. The learning algorithm is the optimiser (here, gradient descent) that uses the gradient.
- "Autodiff is numerical differentiation." It is exact to floating-point precision, because it applies exact derivative rules. Finite differences are approximate and cost \(O(P)\) passes.
- "Autodiff is symbolic differentiation." It never builds a formula for the derivative; it evaluates derivatives at the current point, reusing intermediate values, so it avoids the expression blow-up of symbolic methods.
- "The
gradof a parameter is how important it is." It is how much the current loss would change per unit change of that parameter, at this point. It says nothing about importance once you move.
Check yourself¶
In __mul__, why does self.grad use other.data and not self.data?
Because \(\partial(ab)/\partial a = b\). The local derivative of a product with respect to one factor is the other factor. Using self.data would compute \(\partial(a^2/2)/\partial a\) instead.
You forget to call zero_grad() in the training loop. What happens, exactly?
Each step's gradient is added to all previous ones, so the update at step \(k\) is \(\eta \sum_{t \le k} g_t\): an ever-growing sum of stale gradients. Training typically diverges or oscillates. (PyTorch accumulates the same way, which is how gradient accumulation over micro-batches is implemented on purpose.)
Why must backward() process nodes in reverse topological order? Give a graph where any other order fails.
A node's _backward uses its own .grad, which is only complete once every node that consumes it has pushed its contribution. For \(y = x\cdot x\), \(z = y + x\): if \(y\)'s closure runs before \(z\)'s, \(y.grad\) is still 0, so \(x\) receives nothing via \(y\), and \(dz/dx\) comes out as 1 instead of \(2x + 1\).
The step-0 hinge loss is 0.951 and accuracy is 50%. What would you expect for a 2-class cross-entropy loss at step 0, and why is that a useful check?
About \(\ln 2 \approx 0.693\): with small random weights the two logits are nearly equal, so the softmax is close to uniform and the loss is \(-\ln(1/2)\). Comparing your first loss with \(\ln(\text{classes})\) catches broken initialisation or label bugs before you waste a training run.
Why can't this engine compute second derivatives, and what would you change?
_backward does arithmetic on Python floats (other.data * out.grad), so the backward pass is not itself recorded as a graph. To differentiate it, store gradients as Values and write the closures with Value arithmetic, so the backward pass builds a graph you can call backward() on again (PyTorch's create_graph=True).
Hard: a 2-16-16-1 network on 100 points builds 68,818 nodes per step. Estimate how that count scales with width and batch size, and why GPUs make the scalar view irrelevant.
The count is dominated by the multiply-adds in the layers: about \(2(2\cdot16 + 16\cdot16 + 16)\) nodes per example, roughly 600, plus activations and loss terms, times 100 examples. It scales linearly in batch size and quadratically in width. A framework represents each layer's work as one matrix multiply on contiguous memory, executed by thousands of parallel units, so the number of graph nodes is the number of tensor operations (a handful per layer), not scalar ones.
Hard: p.data -= lr * p.grad with L2 regularisation in the loss is the same as 'weight decay'. Show it, and say when the two differ.
With \(\mathcal{L}' = \mathcal{L} + \lambda\lVert w\rVert^2\), the step is \(w \leftarrow w - \eta(\nabla\mathcal{L} + 2\lambda w) = (1 - 2\eta\lambda)w - \eta\nabla\mathcal{L}\): the weights shrink by a constant factor each step. They differ under adaptive optimisers like Adam, which rescale the gradient (including the \(2\lambda w\) term) per parameter; AdamW decouples the decay from the gradient so it is applied uniformly (optimisers).
Go deeper¶
Videos and lectures
- The spelled-out intro to neural networks and backpropagation: building micrograd — Andrej Karpathy, 2h25m. The canonical walk-through of this exact project. Try each milestone first, then watch the matching segment.
- Backpropagation calculus — 3Blue1Brown. The chain rule on a network, drawn; the picture to hold while writing
_backward. - Neural Networks: Zero to Hero — Andrej Karpathy. The course this project opens; lectures 2 to 7 take you from here to a GPT.
Code
- karpathy/micrograd — The original, with the moons demo notebook, the graph-tracing notebook and tests against PyTorch.
- microgpt — Andrej Karpathy, 2026. A complete GPT trainer in about 200 lines of dependency-free Python, built on a micrograd-style engine. Read it after the project.
- tinygrad/tinygrad — The next step up: a small tensor autograd library that runs on real accelerators.
Papers
- Learning representations by back-propagating errors — Rumelhart, Hinton and Williams, Nature 1986. The paper that made backpropagation the training method for hidden layers.
- Automatic differentiation in machine learning: a survey — Baydin, Pearlmutter, Radul and Siskind, 2018. Forward vs reverse mode, operator overloading vs source transformation; sections 2 and 3 cover what you built.
- Automatic differentiation in PyTorch — Paszke et al., 2017. Four pages on how PyTorch's define-by-run autograd works: your engine, with tensors, in-place checks and C++.
Articles and notes
- Calculus on computational graphs: backpropagation — Chris Olah, 2015. The sum-over-paths view and why reverse mode factors it; the best short explanation.
- Yes you should understand backprop — Andrej Karpathy, 2016. Concrete failure modes (saturated sigmoids, dead ReLUs, exploding RNN gradients) that only make sense once you know the backward rules.
- CS231n: Backpropagation, intuitions — Stanford. Gates as local units, patterns in the backward flow, and gradients for vectorised operations.
- Autograd mechanics — PyTorch documentation. How the real thing records graphs, saves tensors for backward and detects in-place modification.
Where this leads¶
- Automatic differentiation — forward mode, JVPs and VJPs, and how PyTorch and JAX generalise what you built.
- Backpropagation from scratch — the same algorithm in matrix form, which is how you will write it from now on.
- Project: build and train a tiny GPT — the next rung: tensors, a tokeniser, attention and a real training run.
- The project ladder — where this project sits among thirty-odd others, and what to build next.