Build a tiny reverse-mode autograd engine
Write a class Value that wraps a float and records how it was made, so that calling .backward() on a final result fills .grad on every input.
Support: Value(3.0), a + b, a * b, a.tanh(), and plain numbers on either side of + and * (so 2 * a and a + 1 work). Each Value has .data and .grad (starting at 0.0). backward() sets the output's grad to 1 and propagates in reverse topological order. Gradients must ACCUMULATE when a value is used more than once.
class ValueUnderstand the idea
A reverse-mode autograd engine wraps each number in an object that remembers which values produced it and how. Calling backward on the final result sets its gradient to 1, then walks the graph in reverse topological order, and each operation multiplies the incoming gradient by its local derivative and adds it to its inputs. Worked example: a = 2, c = a x a, b = c + a, so b = 6. By hand, db/da = 2a + 1 = 5. In the engine: b.grad = 1. The + node gives c.grad += 1 and a.grad += 1. The x node uses a twice, giving a.grad += c.grad x a = 2 two times, so a.grad = 1 + 2 + 2 = 5. That only works with +=; overwriting with = would lose paths. Local rules: for a + b both get the output gradient; for a x b, a gets out.grad x b and b gets out.grad x a; for t = tanh(a), a gets out.grad x (1 - t^2). Plain numbers must be wrapped too. PyTorch's autograd is the same idea for tensors.