Order a compute graph for backprop with a topological sort

Autograd engines like micrograd and PyTorch run backward by visiting nodes in reverse topological order: a node is processed only after every node that uses it.

Write topo_order(graph, root) where graph maps each node name to the list of its input node names. Return a list of all nodes reachable from root, ordered so that every node comes AFTER all of its inputs (root is last). Use depth-first search, visiting inputs in the listed order, so the answer is unique.

Signaturedef topo_order(graph, root)

Understand the idea

Backprop must process a node only after every node that uses it has passed its gradient back. So you first list nodes so that each one comes after all of its inputs (a topological order), then walk that list in reverse. Like getting dressed: socks must come before shoes. Depth-first search does it: visit all inputs of a node first, and only then append the node. Worked example: graph {L: [a, b], a: [x], b: [x, y], x: [], y: []}, root L. Visit L, go to a, go to x, x has no inputs so append x. Append a. Go to b; x is already visited, go to y, append y. Append b. Finally append L. Order: [x, a, y, b, L]. Every node appears after its inputs, root last. Appending a node before visiting its inputs (pre-order) breaks this. Rule: post-order DFS with a visited set, inputs in listed order. micrograd and PyTorch's autograd both rely on this ordering.

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

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

  • Sample 1: chaintopo_order({'loss': ['y'], 'y': ['x']}, 'loss')
  • Sample 2: diamondtopo_order({'L': ['a', 'b'], 'a': ['x'], 'b': ['x', 'w']}, 'L')
  • Test 3: shared inputtopo_order({'z': ['x', 'x', 'y'], 'y': ['x']}, 'z')