Compute a gradient on a DAG with memoized backprop

MediumAutograd

Why it matters This is exactly why reverse-mode autodiff is cheap: shared sub-results are reused instead of enumerating paths.

The chain rule says a gradient is the sum over all paths of the product of local derivatives. The number of paths can explode, but memoization makes it linear.

Write path_grad(edges, src, out). edges is a list of (u, v, d) meaning node v uses node u with local derivative dv/du = d. Return (grad, n_paths): grad is d out / d src (sum over every path from src to out of the product of d along the path), and n_paths is the number of such paths. If there is no path, return (0.0, 0). Your solution must handle graphs with over a billion paths quickly, so cache per node.

Signaturedef path_grad(edges, src, out)

Example

edges [("x", "a", 2), ("x", "b", 3), ("a", "y", 1), ("b", "y", 4)], src "x", out "y" gives (14.0, 2).

Understand the idea

When one value feeds into several later values, its influence on the output travels along every route. The total gradient adds up all routes, each route contributing the product of the slopes along it. Counting routes one by one is hopeless in deep networks, but every route from a node goes through its children, so if you remember each child's answer you never redo work. Like a map app that stores the best time from each junction instead of re-planning from scratch.

Tiny example: x feeds a (slope 2) and b (slope 3); a feeds y (slope 1), b feeds y (slope 4). Paths: 2 * 1 = 2 and 3 * 4 = 12, total 14.

Rule: g(out) = 1, g(n) = sum over edges n to v of d * g(v), cached per node.

Every autograd engine, from PyTorch to JAX, is this memoized sum done in reverse topological order.

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

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplepath_grad([('x', 'a', 2.0), ('x', 'b', 3.0), ('a', 'y', 1.0), ('b', 'y', 4.0)], 'x', 'y')
  • Sample 2: ladder of 32 levelspath_grad(LADDER, 's', 't')
  • Test 3: no pathpath_grad([('x', 'a', 2.0), ('b', 'y', 1.0)], 'x', 'y')
  • Test 4: chainpath_grad([(0, 1, 0.5), (1, 2, -2.0), (2, 3, 3.0), (0, 3, 1.0)], 0, 3)