Sub topic 11
Grouping Tasks into Parallel Levels
This chapter assumes you know Kahn's algorithm from earlier in the tutorial, in particular how in-degree counts and the queue of ready nodes work. It also assumes basic Python and Big-O notation.
A topological order tells you a safe sequence for running tasks one at a time. Many real systems have more than one worker, though. A build server can compile several files at once, and a scheduler can run independent jobs on separate machines. To use them, you need to know which tasks can run together.
The idea: process Kahn's algorithm in rounds
In Kahn's algorithm, any node in the queue has no remaining unfinished dependencies. Every node that is ready at the same moment can therefore run at the same time.
To group them, process the ready nodes in rounds instead of one at a time:
- Level 0 is every node whose in-degree starts at zero.
- Finish the whole current level. For each node in it, decrement the in-degree of its successors.
- Successors whose in-degree drops to zero form the next level.
- Repeat until a round produces no new nodes.
No two nodes in the same level depend on each other. If one did, the dependent node's in-degree would still have been positive when the level was formed.
Implementation
def topo_levels(graph):
indegree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
indegree[v] = indegree.get(v, 0) + 1
level = [u for u, d in indegree.items() if d == 0]
levels = []
seen = 0
while level:
levels.append(level)
seen += len(level)
next_level = []
for u in level:
for v in graph.get(u, []):
indegree[v] -= 1
if indegree[v] == 0:
next_level.append(v)
level = next_level
if seen != len(indegree):
raise ValueError("graph has a cycle")
return levels
print(topo_levels({"fetch": ["compile", "lint"], "compile": ["test"], "lint": ["test"], "test": []}))
# [['fetch'], ['compile', 'lint'], ['test']]The running time is still O(V + E), because each node enters exactly one level and each edge is decremented once. Cycle detection also works the same way as in Kahn's algorithm. Nodes on a cycle never reach in-degree zero, so seen falls short of the node count.
What the levels tell you
| Property | Meaning |
|---|---|
| Number of levels | The fewest rounds needed if every task takes one unit of time and you have unlimited workers |
| Size of the largest level | The most workers that can be busy at once in this schedule |
| Level of a node | The number of edges on the longest path from any source to that node |
The number of levels equals the number of nodes on the longest path in the graph. That longest path is the critical path: no amount of extra workers can make the whole job finish faster than it.
Common errors
- Mixing rounds in one queue. If you append newly ready nodes to the list you are currently iterating over, you lose the level boundaries. Build
next_levelseparately, as the code does. - Assuming levels are an optimal schedule. They are optimal only for unit-time tasks with unlimited workers. With a fixed number of workers, or tasks of different durations, finding the best schedule is NP-hard in general. In those cases, levels are a starting point, and real schedulers use heuristics such as running critical-path tasks first.
- Forgetting sink-only nodes. If a node appears only as a successor and never as a key,
indegree.get(v, 0)still counts it. Code that indexesgraph[v]directly would crash on it.
Exercise
For the graph {"a": ["c"], "b": ["c", "d"], "c": ["d"], "d": []}, what does topo_levels return, and what is the minimum number of rounds needed with unlimited workers?
Show answer
[['a', 'b'], ['c'], ['d']]. Here a and b start with in-degree 0. After that round, c drops to 0 and d drops to 1. After c finishes, d drops to 0. That makes 3 rounds, matching the longest path a → c → d (or b → c → d), which has 3 nodes.
Exercise
Why can no two nodes in the same level have an edge between them?
Show answer
Suppose an edge u → v joined two nodes in the same level. Then v's in-degree would still count that edge until u was processed. But u is processed only in the round that builds the next level, so v could not have had in-degree zero when the current level was formed. That contradicts v being in the level.