Paul's Python CoursePPC

Project 2 of 14, for Aaesha

Tiny Autograd Engine

A micrograd-style autograd engine: numbers that remember how they were made, so one backward() shares out the blame for a mistake, the puzzle every learning brain has to solve. Drawn as a graph, then a neuron that trains on it.

About 2 hours, in 13 steps.

Sign up free to open itLog in

Act 7 needs a free account, so your work is saved as you go. Act 1 is open to everyone.

The brief

  • AaeshaWhen a network gets an answer wrong, which of its numbers is to blame? Brains have the same puzzle, funnily enough.
  • AaeshaNobody knows yet how a brain shares out the blame, but a network can do it mechanically.
  • NeilAt the moment somebody rewrites backward by hand every time, and it's usually me, and I usually get it wrong.
  • AaeshaSo every number gets its own receipt, and I'm a big fan of receipts.

In engine.py, finish Value: one number that remembers how it was made. + is already written, as the pattern for the rest.

  1. Value(data) keeps the number in .data, its gradient in .grad (starting at 0), the values it was made from in .parents (a tuple, empty for a number you typed in) and the operation's name in .op.
  2. a * b, a ** 2 (the power is a plain number), a.exp() and a.relu() each make a new Value that records its parents and a _backward function: how blame arriving at the new value passes back to each parent. Blame is added to a parent's .grad, never written over it. Plain numbers mixed in, as in 2 * a, work too.
  3. backward(): put every value this one was made from in order, each after its parents; set this value's .grad to 1; then go through the order backwards, calling each value's _backward.

Then, in neuron.py, a neuron built on the engine:

  1. Neuron(n_inputs) keeps a list of Value weights in .weights, one per input, and a Value in .bias, all starting at 0. parameters() gives back the weights, then the bias. Calling the neuron on a night's readings gives the sigmoid of the weighted sum, as a Value.
  2. train(neuron, nights, labels, rate, steps): each step, set every gradient to 0, work out the mean squared error over every night, call backward(), and move each weight against its gradient. It returns the loss at each step.
  3. Run as a program, it learns the stargazing log and gives tonight's chance.
What it prints
Loss: 0.2500 at the start, 0.0476 at the end
Agrees with 24 of 24 nights
Tonight: 0.90, go ahead

What you learn

What's in it

  1. Numbers with receipts
  2. Each card passes blame back
  3. One card, used twice
  4. Who passes the blame first
  5. How Paul would do it
  6. Fix Yahya's version
  7. The tiny engine
  8. Start each step from zero
  9. Backward, twice
  10. A jump has no slope
  11. A neuron on cards
  12. Ship it