Build a Value autograd class that survives very deep graphs

HardAutogradPro

A scalar autograd class is easy to write with a recursive topological sort, but a recurrent net unrolled over thousands of steps makes the graph thousands of nodes deep, and recursion then crashes. This version must handle depth in the tens of thousands.

Write a class Value with .data (float) and .grad (starts at 0.0) that supports:
- a + b, a - b, a * b, a / b, -a, with plain numbers on either side (2 - a, 1 / a, 3 * a all work)
- a ** k for a plain number k
- a.exp(), a.log(), a.tanh()
- a.backward(): sets the output's grad to 1.0 and fills .grad on every Value it depends on, accumulating when a Value is used more than once.
backward must NOT use recursion: build the topological order with an explicit stack. Tests build a chain over 10,000 nodes deep.

Signatureclass Value

Example

x = Value(2.0); y = x * x + x.exp(); y.backward() gives x.grad = 4 + e ** 2.

Understand the idea

A scalar autograd Value stores a number, its gradient, its parent Values and a small function that pushes its gradient to those parents. backward() must visit nodes so that a node is processed only after every node that uses it. That order is a topological sort. Recursion crashes on graphs thousands of nodes deep, so use an explicit stack. Worked example: x = 3, y = 4, z = x * y + x. Order from the output: the add, then the mul, then leaves. The add gives grad 1 to (x * y) and 1 to x. The mul gives 1 * y = 4 to x and 1 * x = 3 to y. So x.grad = 1 + 4 = 5 and y.grad = 3. Local rules: d(a * b) = b and a, d(a ** k) = k * a ** (k - 1), d(exp a) = exp a, d(log a) = 1 / a, d(tanh a) = 1 - tanh(a) ** 2. Subtraction and division can be built from add, neg, mul and pow. Gradients always accumulate with +=. Deep graphs appear when recurrent nets unroll over long sequences.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: example_t_example()
  • Sample 2: all operators_t_ops()