micrograd Lecture Notes
These are my notes of Andrej Karpathy’s micrograd Lecture. Quite useful while trying to revise concepts from the lecture, or even just reviewing the code again. Generated mostly by Claude, edited by me.
Overview
micrograd is a tiny autograd engine (about 100 lines) that computes gradients by backpropagation, plus a ~50-line neural-net library on top. In this 2h25m lecture, Karpathy builds it from an empty notebook and uses it to train a small neural net.
The whole lecture in one sentence: a neural net is just a big mathematical expression; backpropagation applies the chain rule backwards through that expression to get the derivative of the loss with respect to every weight; gradient descent then nudges each weight a little against its gradient, and you repeat.
Key vocabulary
- Autograd = automatic gradient. You write the forward computation; the engine works out all the derivatives for you.
- Backpropagation = reverse-mode automatic differentiation. Start at the output, walk the expression graph backwards, and apply the chain rule at every node.
- Gradient of a value = the derivative of the final output (usually the loss) with respect to that value. It tells you how the output responds if you nudge that value up a tiny bit.
Why scalars? micrograd works on single numbers, so a neuron gets chopped into its individual adds and multiplies. Real libraries like PyTorch pack scalars into tensors (n-dimensional arrays) so the hardware can run them in parallel, but the math is identical. Karpathy’s claim: micrograd holds everything you need to train neural nets, and everything else is efficiency.
The opening demo. He builds a deliberately meaningless expression from two inputs, runs it forward, then calls backward():
from micrograd.engine import Value
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
print(f'{g.data:.4f}') # 24.7041 <- forward pass
g.backward()
print(f'{a.grad:.4f}') # 138.8338 <- dg/da
print(f'{b.grad:.4f}') # 645.5773 <- dg/db
Read a.grad = 138.83 as: if you nudge a up by a tiny amount h, g goes up by about 138.83 × h. The rest of the lecture is about how the engine gets those numbers.
The arc of the lecture
- Build intuition for what a derivative means, using plain Python and a tiny h (Part 1).
- Build the engine: a
Valueobject that remembers how it was made, then backprop by hand, then backprop automatically (Parts 2–7). - Check the engine against PyTorch (Part 8).
- Build a neural-net library on the engine and train it (Parts 9–10).
- Tour the real micrograd repo and PyTorch’s own code (Part 11).
Chapter map
| Time | Chapter in the video | Notes section |
|---|---|---|
| 0:00 | Intro | Overview |
| 0:25 | micrograd overview | Overview |
| 8:08 | Derivative of a simple function with one input | Part 1 |
| 14:12 | Derivative of a function with multiple inputs | Part 1 |
| 19:09 | Starting the core Value object and its visualization | Part 2 |
| 32:10 | Manual backprop example #1: simple expression | Part 3 |
| 51:10 | Preview of a single optimization step | Part 3 |
| 52:52 | Manual backprop example #2: a neuron | Part 4 |
| 1:09:02 | Implementing the backward function for each operation | Part 5 |
| 1:17:32 | Implementing backward for a whole expression graph | Part 5 |
| 1:22:28 | Fixing a backprop bug when one node is used multiple times | Part 6 |
| 1:27:05 | Breaking up a tanh, exercising with more operations | Part 7 |
| 1:39:31 | Doing the same thing in PyTorch | Part 8 |
| 1:43:55 | Building a neural net library (multi-layer perceptron) | Part 9 |
| 1:51:04 | Creating a tiny dataset, writing the loss function | Part 10 |
| 1:57:56 | Collecting all of the parameters of the neural net | Part 10 |
| 2:01:12 | Gradient descent by hand, training the network | Part 10 |
| 2:14:03 | Summary; how to go towards modern neural nets | Part 11 |
| 2:16:46 | Walkthrough of the full micrograd code on GitHub | Part 11 |
| 2:21:10 | Diving into PyTorch: its backward pass for tanh | Part 11 |
| 2:24:39 | Conclusion (outtakes at 2:25:20) | Part 11 |
Code in these notes follows Karpathy’s lecture notebooks and the micrograd repo. Every number quoted was re-run in an independent re-implementation to check it.
Part 1 — Derivatives from scratch
A derivative tells you how sensitive a function’s output is to a tiny nudge in one of its inputs. You can measure it numerically with plain arithmetic, no symbolic calculus needed.
One input
The running example is a simple parabola:
def f(x):
return 3*x**2 - 4*x + 5
f(3.0) # 20.0
The textbook definition of the derivative is the slope over a vanishingly small step:
Karpathy deliberately skips the symbolic route (“the derivative of 3x² is 6x”). Nobody writes out the symbolic derivative of a neural net, which is a massive expression. Instead, ask the practical question: if I bump x up by a tiny h, how does f respond, and with what sensitivity? That ratio, rise over run, is the slope.
h = 0.0001
x = 3.0
(f(x + h) - f(x)) / h # ≈ 14.0003
| x | Numerical slope (h = 0.0001) | Exact slope 6x − 4 | What it means |
|---|---|---|---|
| 3.0 | 14.0003 | 14 | Nudging x up pushes f up, steeply |
| −3.0 | −21.9997 | −22 | Nudging x up pushes f down |
| 2/3 | ≈ 0.0003 | 0 | Flat: the bottom of the parabola |
Two practical notes:
- The sign of the slope says which way the output moves; the size says how strongly.
- h has to be small, but not too small. Push it towards 1e-15 and floating-point rounding swamps the difference, so the estimate becomes garbage.
Several inputs
Now make the output depend on three inputs:
a, b, c = 2.0, -3.0, 10.0
d = a*b + c # 4.0
Bump one input at a time by h and watch d. This is how you estimate a partial derivative:
h = 0.0001
d1 = a*b + c
c += h
d2 = a*b + c
print('slope', (d2 - d1) / h) # ≈ 1.0
| Nudge | What happens to d | Slope | Why |
|---|---|---|---|
| a + h | d goes down (because b is negative) | −3 = b | ∂(a·b)/∂a = b |
| b + h | d goes up | 2 = a | ∂(a·b)/∂b = a |
| c + h | d goes up by exactly h | 1 | c is just added |
Two rules fall out of this that the whole lecture rests on:
- Multiplication: the derivative with respect to one factor is the other factor.
- Addition: the derivative with respect to each term is 1.
With this intuition, the lecture moves on to expressions too big to poke by hand, which is exactly what a neural net is.
Part 2 — The Value object and the expression graph
The Value class wraps one scalar and remembers which values produced it, and by which operation. That memory turns a calculation into a graph you can walk backwards.
Building it up step by step
- Wrap a number.
Value(2.0)storesself.data = 2.0.__repr__makes it print asValue(data=2.0)instead of a memory address. - Teach it arithmetic. Python can’t add two custom objects, so define
__add__and__mul__. When you writea + b, Python actually callsa.__add__(b). - Record the parents. Each result keeps a set of its inputs (
_prev) and the name of the op that made it (_op). Now every node knows where it came from. - Add a label for the graph drawings, and a
gradfield, initialised to 0.
class Value:
def __init__(self, data, _children=(), _op='', label=''):
self.data = data
self.grad = 0.0 # dL/d(this node); 0 means "no effect yet"
self._prev = set(_children) # the Values this one was computed from
self._op = _op # the op that produced it: '+', '*', ...
self.label = label # name for the graph drawing
def __repr__(self):
return f"Value(data={self.data})"
def __add__(self, other):
return Value(self.data + other.data, (self, other), '+')
def __mul__(self, other):
return Value(self.data * other.data, (self, other), '*')
grad starts at 0 because, before backprop runs, we assume no value affects the output.
The example expression
a = Value(2.0, label='a')
b = Value(-3.0, label='b')
c = Value(10.0, label='c')
e = a*b; e.label = 'e' # -6.0
d = e + c; d.label = 'd' # 4.0
f = Value(-2.0, label='f')
L = d * f; L.label = 'L' # -8.0
Computing L from the inputs is the forward pass. L stands in for a loss: the single number at the end that we care about.
Drawing the graph
Karpathy uses graphviz to draw any expression. trace walks backwards from the root and collects every node and edge. draw_dot draws each Value as a record box (label | data | grad). For each op it adds a small fake node: it exists only in the picture, not as a Value.
from graphviz import Digraph
def trace(root):
# build a set of all nodes and edges in the graph
nodes, edges = set(), set()
def build(v):
if v not in nodes:
nodes.add(v)
for child in v._prev:
edges.add((child, v))
build(child)
build(root)
return nodes, edges
def draw_dot(root):
dot = Digraph(format='svg', graph_attr={'rankdir': 'LR'}) # left to right
nodes, edges = trace(root)
for n in nodes:
uid = str(id(n))
dot.node(name=uid, label="{ %s | data %.4f | grad %.4f }" % (n.label, n.data, n.grad), shape='record')
if n._op:
dot.node(name=uid + n._op, label=n._op) # op node
dot.edge(uid + n._op, uid)
for n1, n2 in edges:
dot.edge(str(id(n1)), str(id(n2)) + n2._op) # child -> parent's op node
return dot
You’ll use draw_dot constantly. After every backward pass, drawing the graph is the fastest way to check the gradients. The drawing of this expression, with its gradients filled in, is in Part 3.
Part 3 — Manual backprop #1: a simple expression
Backprop fills in every node’s gradient, dL/d(node), by starting at L and stepping backwards one op at a time with the chain rule. For L = (a·b + c)·f the result is a = 6, b = −4, c = −2, e = −2, d = −2, f = 4.
Read it right to left: the + passes −2 unchanged to e and c, and each × multiplies by the other input.
Step by step, from the output back
1. Base case. dL/dL = 1. Nudge L by h and L changes by h.
2. Through the last multiply, L = d · f. By the multiplication rule from Part 1:
- dL/dd = f = −2
- dL/df = d = 4
Karpathy derives this once from the definition, to show it isn’t magic. ((d + h)·f − d·f) / h = h·f / h = f.
3. Through the add, d = e + c. This is the crux of the lecture. We know dL/dd = −2, and we know d’s local derivatives: dd/de = 1 and dd/dc = 1. How do we get dL/dc? Use the chain rule:
The intuition, borrowed from Wikipedia: if a car goes twice as fast as a bicycle, and the bicycle goes four times as fast as a walking man, the car goes 2 × 4 = 8 times as fast as the man. Rates of change multiply along a chain.
So dL/dc = −2 and dL/de = −2. Because a + node’s local derivative is 1, it simply routes the gradient from above, unchanged, to every one of its inputs.
4. Through the first multiply, e = a · b. Apply the chain rule once more:
- dL/da = dL/de · de/da = (−2) · b = (−2)(−3) = 6
- dL/db = dL/de · de/db = (−2) · a = (−2)(2) = −4
| Node | Value (data) | Gradient dL/d(node) | How it was computed |
|---|---|---|---|
| L | −8 | 1 | base case |
| d | 4 | −2 | = f (from L = d·f) |
| f | −2 | 4 | = d (from L = d·f) |
| c | 10 | −2 | = dL/dd × 1 (plus routes it) |
| e | −6 | −2 | = dL/dd × 1 (plus routes it) |
| a | 2 | 6 | = dL/de × b |
| b | −3 | −4 | = dL/de × a |
The core insight
Every node only needs its local derivative: how its output depends on its direct inputs. It knows nothing about the rest of the graph. Backprop walks backwards and, at each node, multiplies the gradient arriving from above by the local derivative:
That is the whole algorithm: a recursive application of the chain rule backwards through the graph.
Gradient check
Karpathy checks every hand-computed gradient numerically. His throwaway lol() function builds the expression twice, once with one input bumped by h. It compares the two outputs, all inside a local scope so nothing global gets messed up:
def lol():
h = 0.001
# ... build the expression with plain values -> L1 = L.data
# ... rebuild it with b.data += h -> L2 = L.data
print((L2 - L1) / h)
lol() # -3.99999... matches dL/db = -4
This habit, comparing analytic gradients against finite differences, stays useful in real projects.
Preview: one optimization step
The gradient points in the direction that increases L. So nudge every leaf (the inputs you control) a small step along its gradient, then redo the forward pass:
step = 0.01
for v in (a, b, c, f):
v.data += step * v.grad
e = a * b
d = e + c
L = d * f
print(L.data) # -7.286496 (was -8.0: L went up)
Only the leaves get nudged; e and d are recomputed from them. Training a neural net uses the same move with a minus sign: step against the gradient so that the loss goes down.
Part 4 — Manual backprop #2: a neuron
A neuron is a weighted sum plus a bias, squashed by an activation function. Backprop through it uses exactly the same rules as Part 3, plus one new local derivative: tanh’s.
The neuron model
In the standard mathematical model, inputs xᵢ arrive along synapses with weights wᵢ. The cell body adds up wᵢ·xᵢ plus a bias b, the neuron’s overall “trigger-happiness”. The total then goes through an activation function:
tanh squashes any input into (−1, 1). It is 0 at 0, and it flattens out near ±1 for large positive or negative inputs.
Adding tanh as an operation
Our Value only knows + and ×, and tanh needs exponentials. That doesn’t matter. An operation can be as big or small as you like, as long as you know its local derivative. So tanh goes in as a single op:
def tanh(self):
x = self.data
t = (math.exp(2*x) - 1) / (math.exp(2*x) + 1)
out = Value(t, (self,), 'tanh')
return out
A two-input neuron
# inputs
x1 = Value(2.0, label='x1')
x2 = Value(0.0, label='x2')
# weights
w1 = Value(-3.0, label='w1')
w2 = Value(1.0, label='w2')
# bias, picked so the numbers come out nice
b = Value(6.8813735870195432, label='b')
x1w1 = x1*w1; x1w1.label = 'x1*w1' # -6.0
x2w2 = x2*w2; x2w2.label = 'x2*w2' # 0.0
x1w1x2w2 = x1w1 + x2w2; x1w1x2w2.label = 'x1*w1 + x2*w2' # -6.0
n = x1w1x2w2 + b; n.label = 'n' # 0.8814
o = n.tanh(); o.label = 'o' # 0.7071
The odd bias makes o = 0.7071 = 1/√2, so 1 − o² = 0.5 exactly. That keeps the hand calculation clean.
Backprop by hand
- o.grad = 1 (base case).
- Through tanh: do/dn = 1 − o² = 1 − 0.5 = 0.5, so n.grad = 0.5. Note that the local derivative is computed from the tanh’s output, which we already have.
- Through the two + nodes: a plus routes the gradient unchanged. So b.grad = 0.5, the sum node gets 0.5, and both x1w1 and x2w2 get 0.5.
- Through the two × nodes: each input gets (the other input) × 0.5.
| Node | Data | Gradient | Calculation |
|---|---|---|---|
| o | 0.7071 | 1.0 | base case |
| n | 0.8814 | 0.5 | 1 − o² |
| b | 6.8814 | 0.5 | routed by + |
| x1·w1 + x2·w2 | −6.0 | 0.5 | routed by + |
| x1·w1 | −6.0 | 0.5 | routed by + |
| x2·w2 | 0.0 | 0.5 | routed by + |
| x1 | 2.0 | −1.5 | w1 × 0.5 = −3 × 0.5 |
| w1 | −3.0 | 1.0 | x1 × 0.5 = 2 × 0.5 |
| x2 | 0.0 | 0.5 | w2 × 0.5 = 1 × 0.5 |
| w2 | 1.0 | 0.0 | x2 × 0.5 = 0 × 0.5 |
Reading the gradients
- w2.grad = 0 makes sense. Its input x2 is 0, so wiggling w2 has no effect on the output.
- In a real network, the gradients we care about are those on the weights and biases. The inputs x are data, fixed by the dataset, so we never update them, even though backprop computes their gradients too.
- Doing this by hand is clearly not scalable. The next step is to make each operation compute its own local gradients automatically.
Part 5 — Automating backprop
Two pieces turn hand backprop into one call. First, every op stores a small _backward function that applies its own local chain-rule step. Second, a topological sort runs those functions in the right order, from the output back.
Piece 1: a _backward closure per operation
Each op, when it creates its output, also defines how to push the output’s gradient into its inputs. Leaves (inputs and weights) do nothing, so the default is a no-op:
class Value:
def __init__(self, data, _children=(), _op='', label=''):
self.data = data
self.grad = 0.0
self._backward = lambda: None # leaf nodes: nothing to propagate
self._prev = set(_children)
self._op = _op
self.label = label
def __add__(self, other):
out = Value(self.data + other.data, (self, other), '+')
def _backward():
self.grad += 1.0 * out.grad # local derivative of + is 1
other.grad += 1.0 * 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 # local derivative = the other input
other.grad += self.data * out.grad
out._backward = _backward
return out
def tanh(self):
x = self.data
t = (math.exp(2*x) - 1) / (math.exp(2*x) + 1)
out = Value(t, (self,), 'tanh')
def _backward():
self.grad += (1 - t**2) * out.grad # local derivative = 1 - tanh^2
out._backward = _backward
return out
The pattern is always: input.grad += (local derivative) × out.grad. That is the chain rule from Part 3, written once per op.
Why closures? _backward is defined inside __add__, so it captures self, other and out. When it runs later, it reads out.grad as it stands then, after the gradient from above has arrived.
In the video Karpathy first writes these with =. The += is the fix from Part 6; it’s shown here already so you don’t copy the bug.
Calling them by hand
You can now backprop the neuron by calling each node’s _backward in turn:
o.grad = 1.0 # must set this: grad starts at 0, and 0 × anything = 0
o._backward() # fills n.grad
n._backward() # fills b.grad and x1w1x2w2.grad
b._backward() # leaf: does nothing
x1w1x2w2._backward()
x2w2._backward()
x1w1._backward()
The order matters. A node may only call _backward once its own .grad is complete, meaning after every node that uses it has already pushed its gradient back.
Piece 2: topological sort
A topological sort lays out a DAG so that every edge points the same way. Here, a node appears in the list only after all of its inputs:
topo = []
visited = set()
def build_topo(v):
if v not in visited:
visited.add(v)
for child in v._prev:
build_topo(child)
topo.append(v) # added only after all its children
build_topo(o)
# topo goes from the leaves ... to o, which is last
Walk that list in reverse (output first) and call _backward on each node. Every node then gets its full gradient before it passes anything on.
Packaged as Value.backward()
def backward(self):
topo = []
visited = set()
def build_topo(v):
if v not in visited:
visited.add(v)
for child in v._prev:
build_topo(child)
topo.append(v)
build_topo(self)
self.grad = 1.0 # base case: dL/dL = 1
for node in reversed(topo):
node._backward()
Now one call does it all: o.backward() fills in every gradient from Part 4 (x1 = −1.5, w1 = 1.0, x2 = 0.5, w2 = 0.0, b = 0.5).
Part 6 — The bug: reusing a node
If a value is used more than once, its gradient must be the sum of the gradients from every use. Writing self.grad = … overwrites earlier contributions. The fix is to accumulate with +=.
Symptom 1: b = a + a
a = Value(3.0, label='a')
b = a + a; b.label = 'b'
b.backward()
a.grad # buggy version: 1.0 correct: 2.0
b = 2a, so db/da should be 2. But in __add__, self and other are the same object. The buggy _backward sets a.grad = 1, then sets a.grad = 1 again, and the second write clobbers the first.
Symptom 2: a variable feeding two branches
a = Value(-2.0, label='a')
b = Value(3.0, label='b')
d = a * b ; d.label = 'd' # -6
e = a + b ; e.label = 'e' # 1
f = d * e ; f.label = 'f' # -6
f.backward()
Both a and b reach f along two paths, one through d and one through e. Each path’s _backward writes into a.grad, and whichever runs last wins.
The correct gradients add up both paths:
- df/da = (path through d) + (path through e) = e·b + d·1 = (1)(3) + (−6)(1) = −3
- df/db = e·a + d·1 = (1)(−2) + (−6)(1) = −8
The fix: the multivariable chain rule
When a variable branches out into several uses, the gradients flowing back along each branch add:
In code, every _backward uses += instead of =:
def _backward():
self.grad += 1.0 * out.grad
other.grad += 1.0 * out.grad
Two consequences to keep in mind:
- Gradients must start at 0 before a backward pass, which is why
grad = 0.0in__init__. - If you call
backward()again later, the new gradients pile on top of the old ones. In training you must reset them to 0 before every backward pass. Forgetting that is the bug Karpathy hits in Part 10.
Part 7 — Breaking up tanh: more operations
Rebuilding tanh out of exp, +, −, × and ÷ gives exactly the same gradients as the single tanh op. The lesson: how big or small you make an operation is up to you, as long as you know its local derivative.
Plumbing: let Values mix with plain numbers
a + 1 fails, because the int 1 has no .data. The fix is to wrap non-Values on the way in, in both __add__ and __mul__:
other = other if isinstance(other, Value) else Value(other)
2 * a still fails. Python first tries int.__mul__(2, a), which doesn’t know about Values. It then falls back to the right-hand operand’s __rmul__. Define the reflected versions to swap the order back:
def __rmul__(self, other): # other * self
return self * other
def __radd__(self, other): # other + self (needed later for sum())
return self + other
New operations
exp. The derivative of eˣ is eˣ, which is the output we just computed:
def exp(self):
x = self.data
out = Value(math.exp(x), (self,), 'exp')
def _backward():
self.grad += out.data * out.grad # (the video writes '=' here; '+=' is correct)
out._backward = _backward
return out
Power (constant exponents only), using the power rule:
def __pow__(self, other):
assert isinstance(other, (int, float)), "only supporting int/float powers for now"
out = Value(self.data**other, (self,), f'**{other}')
def _backward():
self.grad += other * (self.data ** (other - 1)) * out.grad
out._backward = _backward
return out
Division, negation, subtraction are built from what already exists, so they need no _backward of their own:
def __truediv__(self, other): # self / other = self * other^-1
return self * other**-1
def __neg__(self): # -self
return self * -1
def __sub__(self, other): # self - other
return self + (-other)
Division is the neat trick here: a / b = a · b⁻¹, so it is a power followed by a multiply.
The neuron again, with tanh spelled out
n = x1*w1 + x2*w2 + b
# ----
e = (2*n).exp()
o = (e - 1) / (e + 1)
# ----
o.backward()
The graph is now much longer: a multiply, an exp, two adds (e − 1 becomes e + (−1)), a power and a final multiply, where before there was one tanh node. Yet the forward value is still o = 0.7071, and the backward pass gives the same gradients: x1 = −1.5, w1 = 1.0, x2 = 0.5, w2 = 0.0.
Why this matters
- Operations are an abstraction level you choose. tanh can be one composite op or six atomic ones. Mathematically they are equivalent.
- The only contract an op must honour is a forward pass plus a local derivative. Chaining is then handled by backprop.
- Fusing many small ops into one bigger op means fewer nodes and less overhead. Using only tiny ops means less calculus to write per op. Real libraries make this trade-off all the time.
Part 8 — The same thing in PyTorch
PyTorch computes the same gradients for the same neuron: x2 = 0.5, w2 = 0, x1 = −1.5, w1 = 1. micrograd’s API (.data, .grad, .backward()) is a deliberate miniature of PyTorch’s.
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)
print(o.data.item()) # 0.70710669...
o.backward()
print('x2', x2.grad.item()) # 0.5000001...
print('w2', w2.grad.item()) # 0.0
print('x1', x1.grad.item()) # -1.5000004...
print('w1', w1.grad.item()) # 1.0000003...
What’s different in PyTorch
- Everything is a tensor, an n-dimensional array of scalars. Here each tensor holds a single element, to mirror micrograd. Real code puts thousands of numbers in one tensor so the operations run in parallel.
- Precision. Python floats are float64, but PyTorch defaults to float32.
.double()casts to float64 so the results line up with micrograd. requires_grad. Leaf tensors don’t track gradients by default, because you rarely want gradients for input data. You opt in for anything you want.gradon..item()pulls the plain Python number out of a one-element tensor..datagives the tensor’s values without the autograd wrapping.
Why the last digits differ
The outputs are 0.70710669 and 0.50000013, not exactly 0.70710678 and 0.5. torch.Tensor([...]) first builds a float32 tensor, so the long bias gets rounded to float32 before .double() widens it. That tiny change in b shifts n, and so o and the gradients. The engine is fine; the input changed slightly.
The takeaway
micrograd and PyTorch implement the same idea: build the graph during the forward pass, then call .backward() on the output. PyTorch adds tensors, GPU kernels and a large library of ops, each with its own forward and backward. Part 11 looks at one of those backward functions.
Part 9 — A neural net library: Neuron, Layer, MLP
Three small classes on top of Value give you a multi-layer perceptron (MLP). A Neuron is a weighted sum plus tanh, a Layer is a list of Neurons, and an MLP is a list of Layers called in sequence. The interface deliberately mirrors PyTorch’s nn module.
Each line is one weight; each neuron also has one bias, which is where the 41 comes from (Part 10).
Neuron
import random
class Neuron:
def __init__(self, nin):
self.w = [Value(random.uniform(-1, 1)) for _ in range(nin)] # one weight per input
self.b = Value(random.uniform(-1, 1)) # bias: "trigger-happiness"
def __call__(self, x):
# w · x + b
act = sum((wi*xi for wi, xi in zip(self.w, x)), self.b)
out = act.tanh()
return out
__call__lets you writen(x)as if the neuron were a function.zip(self.w, x)pairs each weight with its input.sum(iterable, start)takes an optional start value. Starting atself.bfolds the bias in for free. Becausesumbegins withstart + first_item, this works with Values. With no start,sumbegins at the int 0, which is why__radd__is needed (0 + Value).
Layer
A layer is a set of neurons that are not connected to each other, but each is fully connected to every input. Each one is evaluated independently:
class Layer:
def __init__(self, nin, nout):
self.neurons = [Neuron(nin) for _ in range(nout)]
def __call__(self, x):
outs = [n(x) for n in self.neurons]
return outs[0] if len(outs) == 1 else outs # unwrap single outputs
MLP
An MLP takes the input size and a list of layer sizes. It chains consecutive sizes into layers, and feeds each layer’s output into the next:
class MLP:
def __init__(self, nin, nouts):
sz = [nin] + nouts
self.layers = [Layer(sz[i], sz[i+1]) for i in range(len(nouts))]
def __call__(self, x):
for layer in self.layers:
x = layer(x)
return x
Using it
x = [2.0, 3.0, -1.0]
n = MLP(3, [4, 4, 1]) # 3 inputs -> 4 -> 4 -> 1 output
n(x) # a single Value, e.g. Value(data=0.1658)
The output varies from run to run because the weights are random. Calling draw_dot(n(x)) shows the whole thing is still just one big expression graph of + , × and tanh nodes. That is the point: an MLP is a mathematical expression, so backward() works on it unchanged.
Part 10 — Training: data, loss, gradient descent
Training repeats four steps: forward pass, compute the loss, backward pass, and nudge every parameter against its gradient. On a four-example dataset, 20 such steps take the 41-parameter MLP from a random guess to near-perfect predictions.
The zero step belongs to the backward pass in Karpathy’s code; it gets its own box because skipping it is the classic bug.
The dataset
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] # desired targets
Four inputs, each with three numbers, and a target of +1 or −1 for each: a tiny binary classifier. Before training, the network’s predictions are essentially random, and several are on the wrong side.
The loss
A loss is a single number that measures how badly the network is doing. Lower is better. Karpathy uses squared error, calling it the mean squared error loss (strictly, it’s a sum here, since there’s no divide by 4):
ypred = [n(x) for x in xs]
loss = sum((yout - ygt)**2 for ygt, yout in zip(ys, ypred))
- Squaring throws away the sign, so being too high and being too low are punished equally. An absolute value would also work.
- Each term is zero only when the prediction equals the target. The further off a prediction is, the bigger its contribution.
sumstarts from the int 0, so0 + Valueneeds__radd__(Part 7).
Backward through the whole network
loss.backward()
n.layers[0].neurons[0].w[0].grad # e.g. a negative number
A negative gradient on a weight means that increasing that weight would decrease the loss. draw_dot(loss) is now huge, roughly 400 nodes: four full forward passes through the MLP, plus the loss on top. The inputs get gradients too, but they’re useless to us because the data is fixed.
Collecting the parameters
To update all the weights and biases, each class gets a parameters() method, the same idea as PyTorch’s nn.Module.parameters():
# in Neuron
def parameters(self):
return self.w + [self.b]
# in Layer
def parameters(self):
return [p for neuron in self.neurons for p in neuron.parameters()]
# in MLP
def parameters(self):
return [p for layer in self.layers for p in layer.parameters()]
MLP(3, [4, 4, 1]) has 41 parameters:
| Layer | Weights | Biases | Total |
|---|---|---|---|
| 3 → 4 | 3 × 4 = 12 | 4 | 16 |
| 4 → 4 | 4 × 4 = 16 | 4 | 20 |
| 4 → 1 | 4 × 1 = 4 | 1 | 5 |
| All | 32 | 9 | 41 |
Gradient descent
The gradient points in the direction that increases the loss. To decrease it, step the other way, hence the minus sign:
for p in n.parameters():
p.data += -0.01 * p.grad
η (the step size, or learning rate) controls how far each step goes. Karpathy first forgets the minus sign, then reasons it through on one weight and fixes it.
He then steps by hand, re-running forward, backward and update, and the loss falls each time. Playing with the step size shows the classic trade-off:
- Too small (0.01 here): safe but slow.
- Bigger: much faster progress.
- Too big: the loss can overshoot and blow up. The gradient only describes the loss locally, near the current point. A huge step jumps somewhere the gradient said nothing about, and training becomes unstable.
Setting the learning rate is, in his words, a subtle art.
The training loop
for k in range(20):
# forward pass
ypred = [n(x) for x in xs]
loss = sum((yout - ygt)**2 for ygt, yout in zip(ys, ypred))
# backward pass
for p in n.parameters():
p.grad = 0.0 # zero_grad: the line he forgot at first
loss.backward()
# update
for p in n.parameters():
p.data += -0.1 * p.grad
print(k, loss.data)
The lecture notebook uses a step of 0.1. In one re-run from fresh random weights, the loss went from 6.0 at step 0 to 0.018 at step 19, with predictions of about [0.92, −0.99, −0.92, 0.92] against targets [1, −1, −1, 1].
The zero_grad bug
Karpathy’s first loop had no p.grad = 0.0 line. Because every _backward uses += (Part 6), each iteration’s gradients piled on top of the last. He calls it a very common mistake, and he points to his own list of common neural-net mistakes, where forgetting to zero gradients is one entry.
Why did training still work? The problem is so easy that the accumulated, ever-growing gradients just acted like a much larger step size. On a harder problem the same bug would quietly wreck the optimisation. With the fix, training is a bit slower but correct. PyTorch has the same pitfall, which is why real training loops call optimizer.zero_grad() or model.zero_grad() before loss.backward().
Part 11 — Wrap-up: the real micrograd and real PyTorch
The same four steps (forward, loss, backward, update) train a 41-parameter toy and a GPT with billions of parameters. What changes at scale is efficiency and a few choices: tensors, batching, loss functions and update rules. The math is the same.
From micrograd to modern neural nets
- A neural net is a “blob” of simulated neural tissue. Its parameters can be tuned to make it do almost anything, which is where its power comes from.
- Our net has 41 parameters. Production models have billions, and some approach a trillion.
- GPT is trained on a huge amount of internet text to predict the next token. At that scale it shows striking emergent behaviour, yet training it uses the same forward pass, backprop and gradient descent shown here.
- Two differences Karpathy flags. Language models use a cross-entropy loss for next-token prediction instead of squared error. They also use update rules more refined than the plain stochastic gradient descent written here.
Tour of the real micrograd repo
| File | What’s in it | Differences from the lecture version |
|---|---|---|
micrograd/engine.py | Value with +, ×, ** (scalar powers), ReLU, backward(), and the reflected and derived ops (__rsub__, __rtruediv__, …) | Uses ReLU instead of tanh. No label field. |
micrograd/nn.py | Module, Neuron, Layer, MLP | Module base class with zero_grad() and parameters(). Biases start at 0. The last layer is linear (no ReLU). |
test/test_engine.py | Builds the same expressions in micrograd and PyTorch, and asserts that forward values and gradients match (to 1e-6) | The lecture’s PyTorch check, made automatic |
demo.ipynb | Trains an MLP binary classifier on the 2D “moons” dataset | Bigger data, bigger model, different loss (below) |
trace_graph.ipynb | draw_dot graph visualisation | Same idea as Part 2 |
ReLU is the repo’s nonlinearity: max(0, x). Its local derivative is 1 where the output is positive and 0 elsewhere:
def relu(self):
out = Value(0 if self.data < 0 else self.data, (self,), 'ReLU')
def _backward():
self.grad += (out.data > 0) * out.grad
out._backward = _backward
return out
Module mirrors PyTorch’s nn.Module, so the zero-grad fix from Part 10 lives in one place:
class Module:
def zero_grad(self):
for p in self.parameters():
p.grad = 0
def parameters(self):
return []
The demo notebook goes a step beyond the lecture:
- Data: 100 points from
make_moons(noise 0.1), with labels mapped to ±1. - Model:
MLP(2, [16, 16, 1]), which has 337 parameters. - Loss: an SVM-style max-margin loss, averaged over examples. A point stops costing anything once it is on the right side with a margin of at least 1. Binary cross-entropy would also work; for a simple problem the choice matters little.
- L2 regularisation: adds 1e-4 × Σp² to the loss, which discourages large weights and so limits overfitting. The lecture doesn’t cover it.
- Batching: an optional
batch_sizepicks a random subset of examples for each step (an “inline DataLoader”). With large datasets you can’t afford to forward every example every step. - Learning-rate decay: lr = 1.0 − 0.9 × k/100. Take big steps early and small steps late, to settle into the details.
- Result: after 100 steps, 100% training accuracy with a loss of about 0.011, plus a plot of the decision boundary.
losses = [(1 + -yi*scorei).relu() for yi, scorei in zip(yb, scores)] # max-margin
data_loss = sum(losses) * (1.0 / len(losses))
reg_loss = 1e-4 * sum((p*p for p in model.parameters())) # L2
total_loss = data_loss + reg_loss
for k in range(100):
total_loss, acc = loss()
model.zero_grad()
total_loss.backward()
learning_rate = 1.0 - 0.9*k/100 # decay
for p in model.parameters():
p.data -= learning_rate * p.grad
Into PyTorch: hunting for tanh’s backward
In micrograd, tanh’s backward is one line: self.grad += (1 - t**2) * out.grad. Karpathy goes looking for the same thing in PyTorch’s source:
- Searching for “tanh” turns up thousands of hits across hundreds of files. Finding the right one takes him about 15 minutes.
- The CPU version sits in a kernel file for binary operations. Tanh’s backward takes two inputs, the incoming gradient and tanh’s output, so it’s implemented as a two-input op. The core is the same formula: grad × (1 − output²).
- That formula is wrapped in extra branches for complex numbers and low-precision types like bfloat16, and there’s a separate CUDA version for GPUs.
The lesson: production code is the same math as micrograd, buried under data types, devices and speed.
Adding your own operation to PyTorch
You can register a new op by giving PyTorch the same two things micrograd needs: a forward pass and a local derivative. Karpathy shows the example from PyTorch’s docs, a third-order Legendre polynomial:
class LegendrePolynomial3(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input) # stash what backward will need
return 0.5 * (5 * input ** 3 - 3 * input)
@staticmethod
def backward(ctx, grad_output):
input, = ctx.saved_tensors
return grad_output * 1.5 * (5 * input ** 2 - 1) # local derivative x upstream grad
P3 = LegendrePolynomial3.apply # now usable like any built-in op
Conclusion
A neural net is a mathematical expression of the inputs and the weights. The forward pass computes predictions; the loss scores them; backprop gets the gradient of the loss for every weight; gradient descent nudges the weights to lower the loss. Repeat. micrograd contains all of it in about 150 lines. Everything else in a real library is about doing it faster, at scale. (Outtakes run from 2:25:20.)
Cheat sheet
Every op in micrograd follows one rule: input.grad += (local derivative) × out.grad, run in reverse topological order.
Local derivatives
| Op | Forward | Local derivative(s) | _backward line |
|---|---|---|---|
| a + b | a + b | 1 and 1 | self.grad += out.grad; other.grad += out.grad |
| a × b | a·b | b and a | self.grad += other.data * out.grad; other.grad += self.data * out.grad |
| a ** k (k constant) | aᵏ | k·aᵏ⁻¹ | self.grad += k * self.data**(k-1) * out.grad |
| exp(a) | eᵃ | eᵃ (= the output) | self.grad += out.data * out.grad |
| tanh(a) | t | 1 − t² | self.grad += (1 - t**2) * out.grad |
| relu(a) | max(0, a) | 1 if a > 0, else 0 | self.grad += (out.data > 0) * out.grad |
| −a | a · (−1) | −1 | none: built from × |
| a − b | a + (−b) | 1 and −1 | none: built from + and × |
| a / b | a · b⁻¹ | 1/b and −a/b² | none: built from ** and × |
Rules of thumb
- + routes: it passes the incoming gradient unchanged to every input.
- × swaps: each input’s gradient is the other input times the incoming gradient.
- Reuse adds: a value used in several places gets the sum of the gradients from each use.
- Sign: the gradient points uphill (towards more loss), so the update steps the other way.
The training loop, compressed
for step in range(num_steps):
loss = compute_loss(model(xs), ys) # 1. forward pass + loss
for p in model.parameters(): # 2. zero the gradients
p.grad = 0.0
loss.backward() # 3. backward pass
for p in model.parameters(): # 4. update
p.data -= learning_rate * p.grad
Common bugs
| Bug | Symptom | Fix |
|---|---|---|
= instead of += in _backward | Wrong gradients whenever a node is reused (a + a gives 1, not 2) | Always accumulate with += |
| Forgetting to zero gradients | Gradients pile up across steps, acting like an ever-growing step size | p.grad = 0 (or zero_grad()) before every backward() |
| Missing minus sign in the update | Loss goes up | p.data += -lr * p.grad |
| Learning rate too high | Loss overshoots, oscillates or explodes | Smaller rate, or decay it over time |
Calling _backward out of order | Gradients incomplete | Reverse topological order; backward() handles it |
| Not seeding the output gradient | Everything stays 0 | Output grad = 1.0 (backward() sets it) |
| h too small in a numerical check | Noisy or garbage slope from float rounding | h around 1e-3 to 1e-6 |
PyTorch leaf without requires_grad | .grad is None | x.requires_grad = True |
| float32 vs float64 | Last digits don’t match micrograd | .double() in PyTorch |
Glossary
| Term | Meaning |
|---|---|
| Forward pass | Computing the output (and the loss) from the inputs and the parameters |
| Backward pass / backprop | Computing dLoss/d(node) for every node, from the output back, via the chain rule |
| Loss | One number scoring how wrong the predictions are; training makes it small |
| Gradient | The derivative of the loss with respect to a value: which way, and how strongly, the loss reacts to a nudge |
| Local derivative | How one op’s output depends on its direct inputs; all an op needs to know |
| Chain rule | Global gradient = gradient from above × local derivative |
| Topological sort | An ordering of the graph in which every node comes after its inputs |
| Leaf node | A value not computed from others: an input, weight or bias |
| Parameters | The weights and biases that training adjusts |
| Learning rate (step size) | How far each gradient-descent step moves the parameters |
| Activation function | The nonlinearity after the weighted sum (tanh, ReLU) |
| MLP | Multi-layer perceptron: fully connected layers of neurons, one after another |
| Autograd | A system that computes gradients automatically from the forward computation |
Self-check and exercises
If you can answer these without scrolling up, you’ve got the lecture. Answers are below the questions.
Questions
- For f(x) = 3x² − 4x + 5, how would you estimate f′(3) with no calculus? What sign do you expect at x = 0?
- In L = d · f with d = 4 and f = −2, what are dL/dd and dL/df?
- Why does a + node pass its incoming gradient through unchanged?
- In the neuron example, why is w2.grad exactly 0?
- After
b = a + a; b.backward(), what shoulda.gradbe? What does the=version give, and why? - Why must
_backwardrun in reverse topological order? - Why doesn’t division need its own
_backward? - How many parameters does
MLP(2, [16, 16, 1])have? - Why is there a minus sign in
p.data += -lr * p.grad? - Training seemed to work despite the missing zero-grad line. Why, and why is that dangerous?
- In the PyTorch version, what are
.double()andrequires_grad = Truefor?
Answers
- Compute (f(3 + h) − f(3)) / h with h = 0.0001, giving about 14. At x = 0 the slope is −4: negative, so f falls as x rises.
- dL/dd = f = −2 and dL/df = d = 4.
- Its local derivative with respect to each input is 1, and gradient from above × 1 = gradient from above.
- w2’s gradient is x2 × 0.5, and x2 = 0. Changing w2 can’t affect the output while its input is 0.
- It should be 2. The
=version gives 1, becauseselfandotherare the same object and the second write overwrites the first. - A node can only pass on its gradient once it holds the full sum from every node that uses it. Reverse topological order guarantees that.
- a / b = a · b⁻¹, so it is built from
**and*, which already have backward functions. - (2·16 + 16) + (16·16 + 16) + (16·1 + 1) = 48 + 272 + 17 = 337.
- The gradient points in the direction that increases the loss. We want the loss to go down, so we step the opposite way.
- The
+=accumulation made gradients grow every step, which acted like an ever-larger learning rate. On an easy problem that happened to converge fast. On a real problem it would wreck training. .double()makes PyTorch use float64 like Python, so results match micrograd.requires_grad = Trueasks PyTorch to compute.gradfor leaf tensors, which it skips by default.
Exercises
- Rebuild micrograd in a blank notebook without looking:
Value, the ops,backward(), thenNeuron/Layer/MLP. - Write a numerical gradient checker. For every parameter, compare
.gradwith (L(p + h) − L(p − h)) / 2h. - Port
test_engine.py: build expressions in both your engine and PyTorch, and assert that values and gradients match. - Add more ops with their local derivatives:
tanhto the repo’sengine.py, plussigmoid(σ(1 − σ)) andlog(1/x). - Swap the squared-error loss for the max-margin loss from the demo, and compare how training behaves.
- Train on
make_moonswith your own MLP. Add L2 regularisation and learning-rate decay, and plot the decision boundary. - Re-introduce the zero-grad bug on the moons task and watch what happens to the loss.
Going further
The micrograd README now points to microgpt: a full GPT-2-style transformer trained in pure, dependency-free Python. It runs on a more efficient version of this autograd engine, which stores local gradients during the forward pass instead of building per-op backward closures. It is a natural next step after this lecture and the makemore series.
Sources
- The spelled-out intro to neural networks and backpropagation: building micrograd (Andrej Karpathy, YouTube)
- karpathy/micrograd:
engine.py,nn.py,test/test_engine.py,demo.ipynb, README - nn-zero-to-hero lecture notebooks for micrograd: the code written in the video
- Video transcript with chapter timestamps
- microgpt and its explainer post, both linked from the micrograd README