Directed Acyclic Graph (DAG) Topological Sorting
Agent-Assisted Engineering Check
Prerequisites
Day 31 computational graph concepts and depth-first search (DFS) fundamentals.
Learning Objective
Understand why reverse-mode backpropagation requires post-order topological sorting so that all outgoing dependencies finish before a node executes its backward closure.
Instructions
Inspect the branching shared-node graph structure using the CLI:
python3 projects/autograd/cli.py graph --preset shared-node --format ascii
Notice that node a feeds into both sum $(a+b)$ and final product $(a+b) \cdot a$. A simple BFS or arbitrary traversal would run a._backward() before all downstream gradient contributions have arrived.
Practice & Prediction Log
Consider the expression $f = (a + b) \cdot a$, where $a = 3.0, b = 4.0$.
1. Trace the depth-first search (DFS) traversal starting at root node $f$.
2. List the post-order sequence of nodes visited.
3. Verify that the reversed sequence orders $f$ first, then the sum node, and finally leaf nodes $a, b$.
In post-order DFS: recursively visit child nodes in node._prev. Only after all child nodes are fully processed, append the current node to the list. Reversing this list guarantees that every node appears after all nodes that depend on it.
Reference Solution:
1. Root $f$ has children $\{sum, a\}$.
2. Child $sum$ has children $\{a, b\}$.
3. DFS visits $a$, then $b$, appends $sum$, then appends $f$.
4. Reversed topological ordering: $[f, sum, b, a]$.
When backward() runs along this reversed sequence, $f._backward()$ fires first, then $sum._backward()$, and finally $a$'s gradient is fully accumulated.
The learner independently writes a DFS post-order topological sort algorithm without relying on third-party graph libraries.
Authoritative Source Resources & Provenance
micrograd: A tiny scalar-valued autograd engine
Relevant Section / Range: micrograd/engine.py: class Value (_backward closures and backward() topological sort); README 'Example usage'
Verified Version & Date: commit a9a9f94 (Verified: 2026-10-30)
Clear reference implementation of recursive DFS topological sort for reverse-mode ordering.
Graph traversal fundamentals (DFS/BFS)
Local implementation in projects/autograd/engine.py.
Compared Candidate Sources & Selection Analysis (2)
Production scale, but too large and complex for tracing by hand in introductory lessons.
Vectorized autograd; micrograd's pure scalar model is pedagogical for hand backprop.