In P4.8 you ran backpropagation by hand, on one neuron with four nodes. P1.C10 showed that the same idea fits in about 30 lines of Python. This lesson takes the last step: a small but complete autograd engine of about 100 lines. It handles any expression built from add, subtract, multiply, divide, powers, , , , ReLU and sigmoid. At the end it trains a small neural network, and every gradient comes from your own code.
The lesson goes in short steps. Code cells run in your browser (plain Python, no NumPy), and each cell is self-contained, so you can run any of them first.
Where this design comes from. This lesson follows the design of Andrej Karpathy’s micrograd (a small scalar Value class with operator overloading and a backward pass; MIT licence, Copyright (c) 2020 Andrej Karpathy; the notice is in the box below) and his video lecture on it. The structure of the operators deliberately stays close to his; the explanations, the checks, the extra topo method, the gradient reset and the widget are our own. His lecture is a good second take on the same idea.
Go deeper micrograd's licence notice
The engine code in this lesson follows micrograd closely, so its licence notice is reproduced here, as the MIT licence asks.
The MIT License (MIT) Copyright (c) 2020 Andrej Karpathy
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Step 1: a number that remembers where it came from
An ordinary Python number forgets how it was made. To differentiate, we need the opposite. Each number keeps four things:
class Value:
def __init__(self, data, parents=(), op=""):
self.data = float(data) # the forward value
self.grad = 0.0 # d(output)/d(this value), filled in by backward()
self.parents = parents # the Values this one was computed from
self.op = op # the operation that made it (for printing)
self._backward = lambda: None # leaves have nothing to pass back
P1.C10 stored a number for each edge. Here each node stores a small function instead, _backward, which is easier to extend: a new operation only has to supply its own function. A value with no parents (an input, a weight, a constant) is a leaf.
Step 2: operators that build the graph
When you write a + b with two Value objects, Python calls a.__add__(b). We make that method compute the new number and create a new node that remembers a and b (these methods go inside the class Value: body):
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 # local derivative 1
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 # the swap
other.grad += self.data * out.grad
out._backward = _backward
return out
The first line wraps a plain number, so x + 1 works. _backward is a closure: a function defined inside another function that keeps access to its variables (self, other and out), even after __add__ has returned. So each node carries its own local rule from P4.8: gradient from above (out.grad) times the local derivative. For an add node the local derivative is . For a multiply node each parent gets the other parent’s value.
Look at +=. It is the heart of the engine, and step 3 shows why.
The other operators are one line each. Python tries 3 * x as int.__mul__, fails, and falls back to x.__rmul__(3), so we define __radd__ and __rmul__ too. Negation, subtraction and division are built from the operations we already have, and __pow__ takes a constant exponent:
def __neg__(self): return self * -1.0
def __radd__(self, other): return self + other
def __sub__(self, other): return self + (-other)
def __rsub__(self, other): return (-self) + other
def __rmul__(self, other): return self * other
def __truediv__(self, other): return self * other ** -1
def __rtruediv__(self, other): return other * self ** -1
Step 3: the backward pass
The backward pass must visit a node only after every node that uses it has passed its gradient down. That is a topological sort: a list in which every node comes after its parents. A depth-first search builds it. To visit a node, first visit its parents, then append the node:
def topo(self):
"""All Values this one depends on, parents before children."""
order, seen = [], set()
def visit(v):
if v not in seen:
seen.add(v)
for p in v.parents:
visit(p)
order.append(v)
visit(self)
return order
def backward(self):
order = self.topo()
for v in order:
if v.parents:
v.grad = 0.0 # in-between values start fresh; leaves keep adding
self.grad = 1.0 # the seed: d(output)/d(output) = 1
for v in reversed(order): # children before parents
v._backward()
The seen set makes sure a node used twice is listed once. Reading the list backwards puts the output first and the inputs last, which is the order of P4.8’s backward pass. The seed is because the output changes by exactly as much as itself. The loop at the top of backward() that sets the in-between gradients to is explained in step 5.
The widget draws the graph for an expression you type, numbers the nodes in this topological order, and steps through the backward pass one node at a time.
Try it. Pick a + a and step through: the leaf a is used twice, so it receives two contributions and the second one is added to the first. Pick x*x + x and predict before the last step. With the P4.8 example, every number matches P4.8’s widget. The **2 node is the square of P4.8, so the gradient on is at once.
Run steps 1 to 3
The cell below holds the engine so far (only add and multiply), rebuilds P4.8’s neuron, and then breaks the engine in two ways on purpose. Here the square is written , so the value is used twice.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
What the output shows:
- Correct engine. , and : exactly P4.8’s numbers. The node is used twice in . Each use contributes , and the two add to , the square rule of P4.8.
- Wrong order. Visiting parents before children gives and . The product node passes its gradient to and before has received anything, so it passes on , and the real gradient arrives too late.
=instead of+=. The second use overwrites the first. keeps instead of , so both gradients come out at half their true size. Nothing crashes: the numbers are just wrong. This is why every_backwardadds.
Go deeper Do we need the topological sort at all?
In this engine, every node is created after the nodes it was computed from, so the order of creation is already a valid topological order. You could keep a list of all nodes in creation order and run it backwards. The depth-first version has two advantages here. It needs no global list, and it visits only the nodes that the output actually depends on, so values computed along the way but never used are skipped.
It has one weakness. Python limits nested function calls (by default to about 1,000), and visit calls itself once per level of depth. A chain of 2,000 additions, such as s = s + t in a loop, makes backward() raise a RecursionError. A production engine keeps its own stack instead of recursing. For the small graphs in this lesson, the recursive version is fine.
Step 4: more operations
Every other operation follows the same pattern: compute the value, store the parents, and add local derivative × out.grad. The local derivatives are the rules of P4.8, plus the one for , which is :
def __pow__(self, k):
assert isinstance(k, (int, float)), "the exponent must be a constant"
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 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
exp, log, relu and sigmoid look the same, with local derivatives (the output itself), , or depending on whether the input is above , and . Each takes five lines, and the full listing is in the next cell.
Go deeper Why is the exponent a constant, and why are subtract and divide built from other operations?
For with a constant the derivative is . If the exponent were itself a Value, the rule would also need , which only exists for . Keeping constant avoids that, and covers squares, square roots and reciprocals.
Subtract and divide need no new rules. is , and is . The chain rule then gives the subtract rule of P4.8 ( and ) and the divide rule: the derivative with respect to is . The price is a few extra nodes, which is why the widget draws them as single nodes.
Step 5: the whole engine, and three checks
Here is the complete engine in one cell, about 100 lines, followed by three checks.
- P4.8’s training loop on , , starting at , , with learning rate . The graph is rebuilt in every step, and only the leaves and persist.
- A finite-difference check (P1.F3) of a longer expression that uses , , , division, sigmoid and ReLU. For each input, nudge it by and compare the slope with the engine’s gradient, using the relative difference of P4.8.
- A wrong rule ( without the square), to see that the check notices.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Running the cell gives this output. The numbers in step 1 are P4.8’s, from the engine instead of by hand.
- With the reset the losses at steps , , and are , , and , and , . These are the values of P4.8’s loop.
- Without the reset the first two losses are the same, because the first update does not yet include an old gradient. The third loss, , matches only by coincidence: the weights are already different there ( instead of ), and squaring hides the sign of . After that the losses drift apart. At step the loss is instead of . The gradient of each step is added to all the earlier ones, so the update is no longer the slope of the current loss. This is P4.8’s warning about
.gradmade visible, and no error tells you. - The check agrees to a relative difference of about for both inputs. The exact figure can differ slightly on another machine, since it depends on rounding.
- The wrong rule gives relative differences of about and , nowhere near rounding noise. The check does its job: a wrong rule on the way to a parameter shows up as a large difference.
Resetting gradients. Because every _backward uses +=, a leaf keeps whatever it already holds and adds to it. That is what a leaf used in many places needs. It also means that you must reset the leaves before each backward pass: that is the line w.grad = b.grad = 0.0, and in PyTorch it is optimizer.zero_grad() (P2.7; accumulation itself is in P2.6). The in-between nodes need no reset in a training loop, because each step builds a new graph. This engine still resets them at the start of backward(). Without that loop, calling backward() twice on one graph would also pile old gradients onto the in-between nodes, and the leaves would get more than double. With it, the second call exactly doubles the leaf gradients. P1.C10’s engine and micrograd do not reset in-between nodes this way, and PyTorch does not keep gradients on in-between tensors by default.
Go deeper Why is the central difference the right check, and how many points should I test?
P4.8 explains why a two-sided difference is more accurate than a one-sided one. For a test it is good practice to use several random points, not one. A rule can be right at one point and wrong elsewhere, for example a ReLU rule that is only wrong for negative inputs. At a kink such as ReLU at exactly the finite difference is not reliable either: the engine returns there (the same choice as PyTorch), while a central difference gives .
The check costs two extra evaluations per parameter, so it is a debugging tool, run on a few parameters of a small model. It is not part of training.
Step 6: check against PyTorch
PyTorch is not available in the browser here, so the block below is a static listing with real output from a local run (PyTorch 2.9.1). It computes the same function as the check above, at the same point, in 64-bit floats:
import torch
def f(a, b):
return (a * b).tanh() + (a - b).exp() / (1 + a * a).log() + b.sigmoid() * a.relu() ** 2
a = torch.tensor(0.7, dtype=torch.float64, requires_grad=True)
b = torch.tensor(-1.3, dtype=torch.float64, requires_grad=True)
out = f(a, b)
out.backward()
print(f"value = {out.item():.5f}")
print(f"a.grad = {a.grad.item():.5f}, b.grad = {b.grad.item():.5f}")
print("leaf:", a.is_leaf, " non-leaf:", out.is_leaf)
out2 = f(a, b) # a second graph, same leaves
out2.backward()
print(f"after a second backward: a.grad = {a.grad.item():.5f}")
a.grad.zero_()
b.grad.zero_()
out3 = f(a, b)
out3.backward()
print(f"after zeroing: a.grad = {a.grad.item():.5f}")
value = 17.91314
a.grad = -25.45366, b.grad = -18.11089
leaf: True non-leaf: False
after a second backward: a.grad = -50.90732
after zeroing: a.grad = -25.45366
The engine gives the same value, , and the same gradients, and (the finite-difference cell above shows the same two numbers). The pieces map one to one:
.dataand.grad. OurValue.dataandValue.gradare PyTorch’s tensor value and.grad.- Leaves.
aandbare leaf tensors: you created them, and.gradis kept on them. Our engine keeps a.gradon every node, while PyTorch keeps one only on leaves by default. - Accumulation. The second
backward()doubleda.gradto , and after the reset it is back to . Same+=, same bug, same cure. _backward. PyTorch stores agrad_fnon each result, the counterpart of our closure.
PyTorch builds its graph on the fly, as ours does, and it frees the saved values after a backward pass (P2.6), so a second backward pass through the same graph is refused unless you ask to keep it. Our engine keeps everything, so you can call it again.
Step 7: a tiny neural network from Values
A neuron is a weighted sum plus a bias, then a . A layer is a list of neurons, and a network is a list of layers. All of it is made of Value objects, so the whole network is a graph and backward() gives the gradient of every weight. The cell below starts with the same engine, then defines the network, then trains it.
The data are made up: 16 points in the square, with target when and have the same sign and otherwise. This is the XOR pattern of P4.2 on random points. The network has 2 inputs, 8 tanh units and 1 linear output, so parameters. The loss is the mean squared error against the targets. Each step is the loop of P4.8: forward, reset, backward, update.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
The loss falls from to in 100 steps, and the number of the 16 training points the network gets right rises from to all . That is training accuracy on 16 points, which says nothing about new points: there is no held-out data here. The point of the cell is that no gradient was written by hand. The model is built from ordinary Python arithmetic, and loss.backward() finds all 33 gradients. The cell finishes in a few seconds, and it uses sum(...), which starts from the number and so also uses __radd__.
From scalars to tensors: what real frameworks add
The engine above, and PyTorch, share one design: build the graph as the forward pass runs, keep what each node needs, then run backward() in reverse. What changes in a real framework is the size of each node and what surrounds it.
- Tensors instead of single numbers. One node is a whole matrix product or convolution, and its local rule is a matrix rule (P1.C11). The loss of the network above is a graph of about 1,500 scalar nodes for 16 examples, while a tensor framework would use a handful of nodes per layer.
- Fast kernels and GPUs. The forward and backward rules are compiled code, run in parallel (P2.2, P2.7). Our Python loop is far too slow for a large model.
- Switching recording off.
torch.no_grad()stops the graph from being recorded, for evaluation and for the parameter update (P2.6). - Memory. Saved values are freed once a backward pass has used them, and checkpointing trades extra computation for less memory (P1.C10).
- Many more rules. Hundreds of operations, numerically stable versions of and softmax, and derivatives of derivatives.
The next lesson, P4.10, keeps the same backward rules but writes them with NumPy arrays, and trains on real handwritten digits.
Depth: three ways to see it
Intuition
Think of each node as a small clerk. During the forward pass the clerk computes a number and writes down who gave the inputs. During the backward pass the clerk gets a note from the output side, saying how much the final answer cares about this clerk’s number. The clerk multiplies the note by a local factor and hands a note to each input clerk. A clerk with two bosses receives two notes and adds them. No clerk needs to know the whole company. The analogy breaks in one place: real notes are numbers, and they can be negative or zero, so the notes are not shares of one total.
Math
For a node with children (the nodes that use ), the chain rule says
Each _backward supplies one term of this sum: out.grad is , the local derivative is , and += builds the sum. The sum is complete when every child has been processed, which a reverse topological order guarantees, and the seed is . For the node has the same child twice, with local derivative each time, so .
Code
Using the engine looks like using PyTorch:
x = Value(2.0)
w = Value(-0.5)
y = (x * w + 1).tanh()
y.backward()
print(y.data, x.grad, w.grad) # 0.0 -0.5 2.0You write the forward computation as ordinary Python. Every *, + and .tanh() adds a node, and backward() fills .grad on x and w.
Check your understanding
An engine writes
self.grad = …instead ofself.grad += …in__mul__. What gradient does it give for at ?Both uses write the same number, the other factor times the incoming gradient, which is 5 × 1. The later write replaces the earlier one, so the engine returns 5. The correct sum is 5 + 5 = 10. The value 25 is the output , and 0 would need a gradient that was never written.
Why does
backward()visit the nodes in reverse topological order?The gradient of a node is a sum over every place it was used, so it is only complete after all of them have contributed. Python has no such restriction on calling functions, and the forward values stay in memory until the graph is dropped. The leaves are visited last, not first, and their data is already known from the forward pass.
A training loop builds a new graph in every step and calls
loss.backward(), but never resets the parameters’ gradients. What does a parameter’sgradhold in step 3?The graph is new each step, but the parameters are the same leaf objects, and
+=adds to whatever they hold. The update then uses a sum of old and new gradients instead of the slope of the current loss. Nothing refuses the addition, so there is no error. The seed is placed on the output node, not on the parameters.A gradient check gives a relative difference of about for one parameter and about for another. What is the most likely conclusion?
Rounding errors of a central difference are around to here, so 0.3 is far outside what rounding could cause, and the size of a parameter’s value does not make a correct rule disagree. A difference of is normal for correct code and need not be exactly zero. The check is a test of the engine, so a large difference points to a bug.
The engine evaluates at and calls
y.backward(). What isx.grad?is used twice. The multiply node sends 3 × 1 = 3 to , and the add node sends 1. The two contributions add to 4, which is the derivative of . Counting only the multiply gives 3, counting only the add gives 1, and 8 is the value of .
When does this engine build its graph?
Each operator creates a new Value as it runs, so the graph is a record of what actually happened. Nothing reads the source code.
backward()only walks a graph that already exists. Training builds a new graph every step, because new numbers give new values on every node.
Exercises
- Add a method
sqrtto the engine (without writing a new_backward). What are the value and the gradient at ?Show answer
Writedef sqrt(self): return self ** 0.5. At the value is and the gradient is , which the engine confirms. - Let
x = Value(0.0), callx.relu().backward()and readx.grad. What gradient does the engine give for the input, and what does a central difference give with ?Show answer
The engine gives (the rule is only when the input is above ). The central difference is . ReLU has a kink at , so no single number is the derivative there. PyTorch also uses . - How many parameters does
MLP([2, 8, 1])have, and how many inMLP([2, 8, 8, 1])?Show answer
for the first. For the second add a layer of 8 units reading 8 inputs, so . - In the last cell, change the learning rate from to . What happens to the loss?
Show answer
It explodes: by step 20 it is above , and the number of correct points stays at 7 of 16. The steps are so large that they overshoot the minimum by more than the distance they started from, as in P1.F3. - In the last cell, delete the loop that sets
p.grad = 0.0. The loss may still go down in this run. Why is that still a bug?Show answer
Each update then uses the sum of all earlier gradients as well as the current one, not the slope of the current loss. Each step then behaves like a larger, momentum-like step. On this problem that happens to help, but it is not the gradient descent you meant, and on other problems it can fail with no error message. - Name two things PyTorch does that this engine does not, and say why each matters.
Show answer
For example, it works on tensors with compiled kernels, so one node covers a whole matrix product and runs fast on a GPU. It also frees saved values after the backward pass, and hasno_grad, which saves memory in evaluation and in the parameter update.
Next: P4.10 writes the same forward and backward rules with NumPy matrices, one node per layer instead of one per number, and trains a network on handwritten digits. P4.16 follows the same backward rule through many layers to see what happens to gradients in deep networks.