Neural networks · lesson 7 of 10
Parts in this lesson
Aout = Value(self.data * other.data, (self, other), "*")an operation that records its parents
Bout._backward = _backwardeach new Value carries a closure that knows its local derivatives
Cfor v in reversed(order): v._backward()reverse topological order: children before parents
Dself.grad += out.grad6.6: gradients add

Build simplenet, part 1: scalars

Last updated

Time to make the computer do lesson 6.6’s backward pass for you. You’ll write Value, a Python class for one number that remembers how it was made: which values it came from, by which operation, and how to pass a gradient back to them. With about 60 lines, any formula you can write with + and * and tanh can differentiate itself. It’s the first half of simplenet, the course’s own autograd library, and the same idea that sits inside PyTorch.

By the end of this lesson you can

  • Write a Value class whose operations record the graph as they compute
  • Write backward(), which visits the graph in reverse topological order
  • Add tanh and exp, and check every gradient by nudging
  • Train a single neuron with Value, zeroing the gradients between steps

A value that remembers its parents

Lesson 6.6 did the backward pass by hand: one line per node, written in reverse. The trick that automates it is to record the graph while the forward pass runs. Instead of plain floats, compute with objects that remember, each time they're made, three things:

  • their number, data;
  • the values they were made from, their parents;
  • a small function, _backward, that knows how to pass a gradient to those parents.

Then the graph builds itself as the formula is worked out, and the backward pass can walk it. Each object also has a grad, starting at 0, for the gradient the backward pass will fill in. (Python names that start with _ are a convention for "inside the class, not for users".)

+ and *

Python calls a.__add__(b) when you write a + b, and a.__mul__(b) for a * b (Simple Python, lesson 4.11). Each makes a new Value with the two inputs as its parents, and gives it a _backward that applies the local derivatives of lesson 6.6. Each _backward is a closure: a function defined inside the method, which remembers self, other and out.

simplenet.ipynb

f knows it was made by + from −6 and 10, and that −6 knows it came from 2×−3. The graph is all there. (if isinstance(...) lets you write a * 2 with a plain number, by wrapping it in a Value.)

Now call each _backward by hand, in reverse order:

simplenet.ipynb

∂f/∂a=−3, ∂f/∂b=2, ∂f/∂c=1, as lesson 6.6's rules say for f=ab+c.

backward() and topological order

Calling them by hand only works if you know the right order. The rule: a node may only pass its gradient back once it has received all of its own, from every node that uses it. So the nodes must be visited children before parents: the reverse of a topological order, an order in which every node comes after all its parents.

A depth-first search builds one: visit a node's parents first, then add the node. Try it on a small graph:

Topological orderthe search inside backward()
abcn₁ = a×bn₂ = n₁+cf = n₂×aorder:(empty)reversed:…

backward() starts by calling visit(f). Press Step.

backward() builds the order, seeds the result's gradient with 1, and runs every _backward in reverse:

simplenet.ipynb

−2, 4 and 2: lesson 6.6's answers for f=(ab+c)a, including a's two paths added together. Note the id(v) in seen: it records each object once, even if it's reached along two paths. (Value.backward = backward attaches the function to the class after the fact; in the finished file it's written inside the class.)

tanh and exp

Any function with a known derivative is a few lines more: compute the output, and give it a _backward that multiplies by the slope. tanh⁡'(z)=1−tanh2⁡z and exp⁡'(z)=ez (lesson 6.2), both computed from the output, so nothing extra needs storing. A few more methods make ordinary arithmetic work too: -x, a - b, and 2 + a (Python tries a.__radd__(2) when int can't add a Value).

simplenet.ipynb

The backward pass and nudging agree to six decimal places. Now type your own formula, in the graph below, using the same operations; step forward, then back, and check the gradients against what you'd expect:

Live graphtype a formula
w10.5grad ·x11grad ·×?grad ·w2−1.5grad ·x22grad ·×?grad ·+?grad ·b0.8grad ·+?grad ·tanh?grad ·

Step 0 of 11. Nothing worked out yet. Press Step to start the forward pass.

Train one neuron with it

That's enough to train something. A single tanh neuron, learning OR with labels −1 and +1, by gradient descent on the squared error. Every step is the training loop: predict, measure the loss, find the gradient (now one call, loss.backward()), step the weights, repeat.

simplenet.ipynb

The loss falls from 4.45 to 0.30 in 30 steps, and the outputs −0.59,0.75,0.76,0.99 have the right signs for OR. Nowhere did you write a derivative of the loss: the graph recorded during the forward pass did it. Before each backward(), the loop sets every gradient back to 0. Step 6 shows why.

Wrong way: calling backward() twice

Gradients accumulate with +=, which is right within one backward pass (lesson 6.6). Across two passes, it's wrong:

simplenet.ipynb

∂(wx)/∂w=x=3, but after a second backward() it says 6: the new gradient was added to the old one. In a training loop, this means each step uses the sum of every gradient so far, so old directions keep pushing long after they stopped being downhill. The fix is to set every parameter's gradient back to 0 before each backward pass:

simplenet.ipynb

PyTorch works the same way, and calls the fix optimizer.zero_grad(). Forgetting it is lesson 7.2's wrong way.

Check what you learned

Why does a Value store its parents?
In backward(), why must the nodes run in reverse topological order?
In the step 5 notebook, delete the two lines that set p.grad = 0.0 and run it. The printed loss falls even faster. Is the code still right?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning