Week 6 of the course adds GRADIENT(loss, wrt) and DETACH(x) to the UOp language. The gradient is not a number computed on the side: it is more graph, built from the same ops, which the compiler can then simplify, fuse and even differentiate again. Implement it for scalar graphs given as nested tuples:
("param", name) reads env[name], ("const", v) is a number, and a plain Python number is also a constant.("add", a, b), ("mul", a, b), ("max", a, b) and ("recip", a) compute .("cmplt", a, b) gives a < b, and ("where", c, a, b) gives a if c else b.("detach", a) has the value of a but passes no gradient.Structurally equal tuples are the same node.
Implement:
evaluate(node, env): the value of a graph, with Python floats and bools.
gradient(loss, wrt): a graph (nested tuples using only the ops above) computing , where wrt is a param node. Use reverse-mode accumulation: start the loss's adjoint at 1.0, visit nodes in reverse topological order, and sum the contributions arriving at each node through all of its uses. The rules:
add passes the adjoint to both inputs; mul passes adjoint times the other input.recip(a) passes adjoint times .where routes the adjoint to the branch that was taken, so the other branch gets 0.max routes it to the larger input, with ties going to the first input.cmplt, detach, params and constants pass nothing on.If wrt receives no gradient, return the constant 0.0.
Because the result is a graph, gradient(gradient(f, x), x) must give the second derivative.