Numbers That Remember Their Past

BackpropagationHard+30 XP+30

Numbers That Remember Their Past

Libraries like PyTorch never ask you to draw a computational graph. You write ordinary arithmetic, and every number quietly records which numbers produced it and how. Calling .backward() on the final result then walks that recorded graph in reverse, starting from 111 and multiplying local rates: the same walk you did by hand in this chapter. Here you build that machinery for single numbers.

Task: write a class Value that wraps one number.

  • Value(data) stores the number in .data and starts .grad at 0.0.
  • a + b and a * b return a new Value that remembers both operands. Either side may be a plain number instead of a Value, as in x * w + 0.5 or 3 * a; treat it as a constant.
  • v.tanh() and v.relu() return a new Value. Take their slopes as given: if t=tanh⁡(z)t = \tanh(z)t=tanh(z) then dtdz=1−t2\dfrac{dt}{dz} = 1 - t^2dzdt​=1−t2, and ReLU's slope is 111 when z>0z > 0z>0 and 000 otherwise, including at exactly z=0z = 0z=0.
  • out.backward() sets out.grad to 1.0, then fills in .grad on every Value that out was built from with ∂ out∂ (that value)\dfrac{\partial\,\text{out}}{\partial\,(\text{that value})}∂(that value)∂out​.

Python turns operators into method calls. a + b runs a.__add__(b) and a * b runs a.__mul__(b). When the left side is a plain number, as in 3 * a, Python instead runs a.__rmul__(3), and likewise a.__radd__ for +.

A value can be used more than once: in a * a, or when an in-between result feeds two later operations. The gradient it ends up with must account for every use.

The function trace is already written for you in the starter code. Keep it exactly as it is. It turns each named input into a Value, runs a few lines of ordinary Python with them, calls backward() on the variable named out, and reports the output and each input's gradient, rounded to 4 decimal places:

Examples

lines = ["u = a * b", "out = u + c"]
numbers = {"a": 2.0, "b": -3.0, "c": 4.0}
returns [-2.0, {'a': -3.0, 'b': 2.0, 'c': 1.0}]
lines = ["out = a * a + 3 * a"]
numbers = {"a": -2.0}
returns [-2.0, {'a': -1.0}]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run