275. 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.
def topo_order(graph, root)Example 1
Input: graph = {'loss': ['y'], 'y': ['x']}, root = 'loss'
Output: ['x', 'y', 'loss']
Constraints
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
Hint 1
A node can only be added after all of its inputs, which is exactly what post-order depth-first search gives you.
Hint 2
Write a recursive visit with a seen set: if a node is new, mark it, visit each of its inputs in the listed order, then append the node to the output.
Hint 3
Use graph.get(n, []) so leaf nodes that are not keys in the dict still work, and mark the node as seen before visiting its inputs so shared nodes appear only once.
Common mistakes
- The buggy version appends before visiting inputs (pre-order), which breaks that guarantee.
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.
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.
post-order DFS with a visited set, inputs in listed order. micrograd and PyTorch's autograd both rely on this ordering