Algorithmadvanced
Path-based scheduling
Also called as fast as possible scheduling, AFAP scheduling, Camposano scheduling.
Camposano's scheduler that takes every path of the control flow graph, cuts each path into the fewest states by interval covering and merges the cuts into one FSM.
- Time
- O(P V^2 log V + R (R V + E log E)) worst
- Space
- O(P V + R V) extra
- Where
- E = the number of control flow edges; P = the number of paths; R = the number of distinct constraints; V = the number of operations
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Raul Camposano, 1991
Path-based scheduling, also called as fast as possible (AFAP) scheduling, schedules a design that has branches by looking at each path through its control flow graph one at a time. Raul Camposano (1991) keeps the order of the operations on a path fixed and asks only where the controller must start a new state, that is, where to cut the path. A cut is needed between two operations that share the one unit of their type, and inside every run of chained operations whose delays exceed the clock period. On one path, every such rule is an interval of possible cut positions, and the fewest cuts that meet all intervals come from a greedy scan by right ends, which is exact. A cut sits on a control flow edge that many paths may share, so the cuts of all paths must then be merged into one set of edges, and one finite state machine. This merge is a hitting set problem on subpaths, and it is NP-hard in the model of this page. The version here merges by a greedy choice and reports the per-path optimum as a lower bound.
In plain words
Think of each way the program can run, from start to end, as a row of tasks in a fixed order. You must split each row into clock ticks. Two tasks that need the one multiplier cannot share a tick, and a run of tasks that is too slow for one tick must be split. For one row, the fewest splits come from walking along it and splitting as late as you can each time a rule forces you. But rows share their first tasks before a branch, and one split there serves every row that passes through it. Picking the splits so that all rows are served with as few as possible is the hard part, so the method picks the split that serves the most rules, again and again.
The problem
The control flow graph is a DAG whose nodes are operations; loops are cut at their back edges first. Each operation has a type and a combinational delay , the clock period. Some types are limited to one unit. A path is a sequence from the entry to an exit, and cut position on it is the edge . The operations between two cuts form one state, which must
- hold at most one operation of each limited type, and
- have a total delay of at most , since the operations of a path are chained in their order.
A set of cut edges is valid when every state of every path meets both rules. The goal is a valid with the fewest edges, so the controller has few states and every path runs in few cycles. Each rule becomes a constraint on a path, a set of consecutive positions that must hold a cut:
- for with limited, the interval ;
- for each , if is the least index with , the interval .
On the graph, the constraint is the set of its edges, a subpath, and is valid exactly when it meets every such subpath.
The algorithm
PATH-BASED-SCHEDULE(G, k, d, T)- 1
P ← every path of G from the entry to an exit - 2
for each path p in P do - 3
I_p ← the constraint intervals of p - 4
c_p ← cuts by the right end greedy on I_p: scan by right end, cut at hi when the interval holds no cut yet - 5
add the edge set of each interval of I_p to the family R - 6
order ← an empty list; U ← R - 7
while U is not empty do - 8
e ← the edge in the most sets of U, ties to the first in a fixed order - 9
append e to order; remove from U every set that holds e - 10
H ← the edges of order; for e in order, last first: drop e from H if H − {e} still meets every set of R - 11
return H, and for each p the states 1 + |c_p| alone and 1 + |H ∩ p| under H
Line L4 gives the fewest states that path could have on its own, a lower bound for any merge. Lines L6 to L9 are the greedy set cover method on the dual of the hitting set instance: the edges are the sets and the constraints are the elements. Line L10 removes cuts that later choices made redundant. Camposano's paper merges the paths in its own way; this page does not reproduce that step.
Example
Take with delay 2, then with delay 1, then a branch to or , each with delay 1, and . There are two paths, and . On the first, fits but does not, so a cut must fall on or . The second path gives the interval in the same way, and no other run is too slow.
The right end greedy of line L4 cuts each path on its last allowed edge, and . Each path then has 2 states, which is the least possible for it alone, but the union has two cut edges and the controller three states: , then or . Lines L7 to L9 see that is in both constraints and take it alone. The controller then has two states, and or , where the branch is decided inside the second state, and each path still takes 2 cycles. The merge, not the per-path step, finds the shared cut.
Correctness
What is proved, in the full proof:
- The intervals are exact. A set of cut edges gives valid states on every path exactly when it meets every constraint of line L5.
- One path is exact. The right end greedy of line L4 meets every interval with the fewest cuts, by an exchange argument. So is a lower bound for the size of any valid , and is the fewest states path can have.
- Valid output. Line L9 ends only when every constraint holds an edge of the list, and line L10 drops an edge only when the rest still meets every constraint.
- The merge is NP-hard. Choosing the fewest edges of a DAG that meet given subpaths is NP-hard, by a reduction from vertex cover: each vertex becomes an edge , each graph edge becomes a private connector edge from the head of to the tail of , and the constraint is the subpath , connector, . A cut on a connector can be moved to , so the fewest cuts equal the least vertex cover.
The greedy merge has the ratio of greedy set cover, where is the largest number of constraints that one edge meets; this is proved on the greedy set cover page and is not repeated. Measured, not proved: on 150 random graphs with at most 8 operations and if/else branches, the greedy merge used more cuts than an exhaustive search on 4, and without line L10 on 18.
Proof: Correctness of path-based schedulingfull
We use the model of the page. The control flow graph is a DAG of operations with types and delays , and some types are limited to one unit. For a path and a set of edges, the states of are the maximal runs of consecutive operations with no edge of between them. is valid when every state of every path holds at most one operation of each limited type and has a total delay of at most .
Lemma 1 (the intervals are exact)
Fix a path and a set of edges. Every state of meets both rules exactly when holds an edge with for every constraint of .
Proof. Operations and with are in one state exactly when none of the edges at positions is in .
Suppose every constraint holds a cut. If and , with , share a limited type, the constraint holds a cut, so they are in different states. If a state had a total delay above , let be the least index with . Then and , since . The constraint holds a cut at a position between and , so and are in different states, a contradiction.
Conversely, suppose some constraint holds no cut. Then are in one state. If the constraint came from two operations of one limited type, both are in the state. If it came from a run with delay above , that run is in the state. Either way a rule fails.
So is valid exactly when it meets the edge set of every constraint of every path, which is the family of line L5.
Lemma 2 (one path, the right end greedy is optimal)
For a finite family of integer intervals, the scan of line L4 returns a set that meets every interval, and no set with fewer points does.
Proof. The scan takes the intervals in order of right end. Let the chosen points be , where is the right end of the interval that was open when it was chosen.
Every interval is met. When the scan reaches an interval , the last point so far is the right end of an earlier interval, so it is at most . If it is at least , it meets the interval. If not, the scan adds , which meets it.
The intervals are pairwise disjoint. Take . When was reached, the last point was at least and below , so . So any set that meets every interval needs a different point in each , at least points.
Corollary. For every valid and every path , the positions of whose edges lie in meet every interval of by Lemma 1, so . Hence is a lower bound for the fewest cuts, and is the fewest states that path can have.
Theorem 1 (valid output)
The set of line L11 is valid.
Proof. Each pass of lines L7 to L9 removes from the sets that hold , and is in at least one set of , so the loop ends after at most passes. When it ends, every set of holds an edge of the list. Line L10 drops an edge only when the remaining edges still meet every set of , so this stays true. By Lemma 1, is valid.
The greedy loop of lines L7 to L9 is the greedy set cover method on the dual instance, in which each edge is the set of constraints that hold . Its ratio , with the largest such set, is proved on the greedy set cover page. Line L10 only removes edges, so the ratio still holds.
Theorem 2 (the merge is NP-hard)
Given a DAG, a family of subpaths of it and an integer , deciding whether some set of at most edges meets every subpath is NP-complete.
Proof. The problem is in NP, since a set of edges is checked in polynomial time. We reduce from vertex cover. Let be a graph with , and an integer. Build a DAG with nodes , an edge for each , and for each with a connector edge . Every edge goes forward in the order , so the graph has no cycle. For each , take the subpath . The build takes polynomial time. A single entry joined to every and an exit joined from every make each part of an entry to exit path, and these extra edges lie in no .
If is a vertex cover, the edges meet every , since or .
Conversely, let meet every with . Drop from the edges that lie in no . Replace each connector by . The connector lies only in , and also lies in , so every subpath is still met, and the size does not grow. Now for some with , and is a vertex cover, since each holds or . Vertex cover is NP-complete (Karp, 1972), so the problem is NP-complete.
The reduction lives in the abstract model of subpaths. Whether every family of subpaths arises from operations, delays and limited units as on the page is not claimed here.
What is not claimed
- The greedy merge is not exact. In the measured run on the page it used more cuts than the exhaustive search on 4 of 150 random graphs.
- The page does not reproduce Camposano's own merge step, and the bounds above concern the version on the page.
- The number of cut edges is the measure that the page minimizes. The number of states of the final controller can be smaller, when cuts on several edges into one operation start the same state.
Complexity
The number of paths can grow as for branches in sequence, which is the main cost and the reason the method enumerates paths only of loop-free bodies. Each path has at most operations and constraints, built in time and stabbed in time. The merge picks at most edges, each pick counts the edges of the open constraints in time and sorts at most candidates, and line L10 makes at most checks of each. So the time is , and the space is for the paths and the constraints.
Properties
- Fixed order. The operations keep their order on each path. The method chooses only where states begin, which is why it is fast on one path and why it may miss a reordering that a list scheduler would find.
- Every path is short. Each path gets a schedule close to its own optimum, rather than the common path only.
- Valid output, not the fewest cuts. The merge is a heuristic in general.
- Deterministic. The order of paths and the tie rule of line L8 are fixed.
Variants and improvements
- Exact merge for small designs. Search over subsets of edges by size, or an integer program with one variable per edge and one covering row per constraint. The tests use the subset search as the reference.
- Area. Bergamaschi and Camposano also weighed the number of units and registers against the number of states.
- Code motion first. The fixed order is a weakness, so speculative code motion and similar moves are often applied before the path step.
- Several units per type. With units, a rule involves operations of one type, and the constraint is still an interval: the positions between the first and the last of any such operations in a row.
When to use it
Use it for control-heavy designs with many short branches, where a scheduler that looks at one basic block or one trace at a time leaves cycles on the less common paths. It suits bodies with few branches in sequence, since the paths are listed one by one. For data flow with few branches, or for loops that must be pipelined, use list scheduling, SDC scheduling or a modulo scheduler instead.
Pitfalls
- Path explosion. With if/else blocks in sequence there are paths. Bound the depth or schedule regions of the body separately.
- Right ends are not shared ends. The per-path greedy puts cuts as late as possible, often after a branch, where no other path can use them. The example shows that merging these cuts directly gives a larger controller.
- States are not cuts. Two cuts on edges into the same operation may start the same state, so the number of cut edges is an upper bound on the extra states, not always their number.
- Long operations. An operation with has no valid cut set. It must be spread over several cycles, which is the opposite case to chaining on the operation chaining page.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/path-based-scheduling/. The authors are listed in prov/60ZARY.jsonl.
"""Path-based (as fast as possible) scheduling in a simple model.
The control flow graph is a DAG whose nodes are operations, given by a
successor list succ. The entry is one node; the exits are the nodes with no
successor. Every operation has a type kind[v] and a combinational delay
delay[v]. Along a path, the operations between two cuts form one state.
A state may not hold two operations of a type in `limited` (one unit each),
and the delays in one state may add up to at most `period`.
A cut sits on an edge (u, v) of the graph. On a path p = p[0], ..., p[m-1],
cut position t means the edge (p[t], p[t+1]). A constraint on p is an
interval [lo, hi] of positions that must hold at least one cut.
"""
from itertools import combinations
def stab_intervals(intervals) -> list[int]:
"""Fewest positions that hit every interval [lo, hi], by the right end greedy."""
cuts: list[int] = []
for lo, hi in sorted(intervals, key=lambda x: (x[1], x[0])):
if not cuts or cuts[-1] < lo:
cuts.append(hi)
return cuts
def all_paths(succ: dict, entry) -> list[list]:
"""Every path from the entry to a node with no successor."""
out: list[list] = []
stack = [[entry]]
while stack:
p = stack.pop()
nxt = succ.get(p[-1], [])
if not nxt:
out.append(p)
for w in reversed(nxt):
stack.append(p + [w])
return out
def path_constraints(p: list, kind: dict, delay: dict, limited, period) -> list[tuple[int, int]]:
"""The intervals of cut positions on path p that must each hold a cut."""
m = len(p)
if any(delay[v] > period for v in p):
raise ValueError("an operation is longer than the clock period")
out = set()
for i in range(m):
for j in range(i + 1, m):
if kind[p[i]] in limited and kind[p[i]] == kind[p[j]]:
out.add((i, j - 1))
total = 0
for j in range(i, m):
total += delay[p[j]]
if total > period:
out.add((i, j - 1))
break
return sorted(out)
def path_based_schedule(succ: dict, entry, kind: dict, delay: dict, limited, period):
"""Return (cuts, per_path) where cuts is a set of edges and per_path lists
(path, fewest states of that path alone, states under the shared cuts)."""
paths = all_paths(succ, entry) # @line L1
rows: set = set()
alone = []
for p in paths: # @line L2
iv = path_constraints(p, kind, delay, limited, period) # @line L3
alone.append(1 + len(stab_intervals(iv))) # @line L4
for lo, hi in iv: # @line L5
rows.add(frozenset((p[t], p[t + 1]) for t in range(lo, hi + 1)))
cuts = greedy_hitting_set(rows) # @line L6
per_path = []
for p, a in zip(paths, alone):
on_p = sum((p[t], p[t + 1]) in cuts for t in range(len(p) - 1))
per_path.append((p, a, 1 + on_p))
return cuts, per_path # @line L11
def greedy_hitting_set(rows) -> set:
"""Pick edges until every row holds one, each time the edge in most open rows."""
open_rows = [r for r in rows]
order: list = []
while open_rows: # @line L7
count: dict = {}
for r in open_rows:
for e in r:
count[e] = count.get(e, 0) + 1
best = max(sorted(count), key=lambda e: count[e]) # @line L8
order.append(best) # @line L9
open_rows = [r for r in open_rows if best not in r]
chosen = set(order)
for e in reversed(order): # @line L10
if all(r & (chosen - {e}) for r in rows):
chosen.discard(e)
return chosen
def exact_hitting_set(rows) -> set:
"""A smallest set of edges that meets every row, by search over subset sizes."""
rows = list(rows)
edges = sorted(set().union(*rows)) if rows else []
for k in range(len(edges) + 1):
for pick in combinations(edges, k):
s = set(pick)
if all(r & s for r in rows):
return s
raise AssertionError("unreachable")
def all_rows(succ: dict, entry, kind: dict, delay: dict, limited, period) -> set:
rows: set = set()
for p in all_paths(succ, entry):
for lo, hi in path_constraints(p, kind, delay, limited, period):
rows.add(frozenset((p[t], p[t + 1]) for t in range(lo, hi + 1)))
return rows
def is_valid(succ: dict, entry, kind: dict, delay: dict, limited, period, cuts) -> bool:
"""Check the states of every path directly, without the interval model."""
for p in all_paths(succ, entry):
state: list = []
for t, v in enumerate(p):
if t > 0 and (p[t - 1], v) in cuts:
state = []
state.append(v)
if sum(delay[x] for x in state) > period:
return False
ks = [kind[x] for x in state if kind[x] in limited]
if len(ks) != len(set(ks)):
return False
return True
test_path_based_scheduling.py 139 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/path-based-scheduling/. The authors are listed in prov/60ZARY.jsonl.
import itertools
import random
from path_based_scheduling import (all_paths, all_rows, exact_hitting_set, greedy_hitting_set,
is_valid, path_based_schedule, path_constraints, stab_intervals)
# a = x * y (delay 2), b = a + 1 (delay 1), then c = b + u or d = b - u (delay 1). Period 3.
SUCC = {"a": ["b"], "b": ["c", "d"]}
KIND = {"a": "mul", "b": "add", "c": "add", "d": "add"}
DELAY = {"a": 2, "b": 1, "c": 1, "d": 1}
def random_cfg(rng: random.Random, max_ops: int):
"""A chain of single operations and if/else diamonds with at most max_ops operations."""
succ: dict = {}
kind: dict = {}
delay: dict = {}
count = 0
def new():
nonlocal count
v = count
count += 1
kind[v] = rng.choice("mma")
delay[v] = rng.randint(1, 3)
return v
entry = new()
tails = [entry]
while count < max_ops:
if count + 3 <= max_ops and rng.random() < 0.5:
left = [new() for _ in range(rng.randint(1, 2 if count + 4 <= max_ops else 1))]
right = [new() for _ in range(1)]
for arm in (left, right):
for t in tails:
succ.setdefault(t, []).append(arm[0])
for x, y in zip(arm, arm[1:]):
succ.setdefault(x, []).append(y)
tails = [left[-1], right[-1]]
else:
v = new()
for t in tails:
succ.setdefault(t, []).append(v)
tails = [v]
return succ, entry, kind, delay
def test_example():
rows = all_rows(SUCC, "a", KIND, DELAY, {"mul"}, 3)
assert rows == {frozenset({("a", "b"), ("b", "c")}), frozenset({("a", "b"), ("b", "d")})}
cuts, per_path = path_based_schedule(SUCC, "a", KIND, DELAY, {"mul"}, 3)
assert cuts == {("a", "b")}
assert [(a, b) for (_, a, b) in per_path] == [(2, 2), (2, 2)]
assert is_valid(SUCC, "a", KIND, DELAY, {"mul"}, 3, cuts)
# The right end cut of each path alone needs two edges.
union = set()
for p in all_paths(SUCC, "a"):
for t in stab_intervals(path_constraints(p, KIND, DELAY, {"mul"}, 3)):
union.add((p[t], p[t + 1]))
assert union == {("b", "c"), ("b", "d")}
def test_stabbing_against_all_subsets():
rng = random.Random(31)
for _ in range(300):
m = rng.randint(1, 7)
iv = []
for _ in range(rng.randint(0, 6)):
lo = rng.randrange(m)
iv.append((lo, rng.randint(lo, m - 1)))
cuts = stab_intervals(iv)
assert all(any(lo <= c <= hi for c in cuts) for lo, hi in iv)
best = next(k for k in range(m + 1) for s in itertools.combinations(range(m), k)
if all(any(lo <= c <= hi for c in s) for lo, hi in iv))
assert len(cuts) == best
def test_schedule_is_valid_and_between_bounds():
rng = random.Random(32)
worse = 0
for _ in range(150):
succ, entry, kind, delay = random_cfg(rng, 8)
cuts, per_path = path_based_schedule(succ, entry, kind, delay, {"m"}, 3)
assert is_valid(succ, entry, kind, delay, {"m"}, 3, cuts)
best = exact_hitting_set(all_rows(succ, entry, kind, delay, {"m"}, 3))
assert is_valid(succ, entry, kind, delay, {"m"}, 3, best)
lower = max(a for (_, a, _) in per_path) - 1
assert lower <= len(best) <= len(cuts)
for (_, a, b) in per_path:
assert a <= b
worse += len(cuts) > len(best)
assert worse < 150
def test_valid_cuts_are_exactly_hitting_sets():
rng = random.Random(33)
for _ in range(60):
succ, entry, kind, delay = random_cfg(rng, 6)
rows = all_rows(succ, entry, kind, delay, {"m"}, 3)
edges = sorted({(u, v) for u in succ for v in succ[u]})
for mask in range(1 << len(edges)):
s = {e for i, e in enumerate(edges) if mask >> i & 1}
assert is_valid(succ, entry, kind, delay, {"m"}, 3, s) == all(r & s for r in rows)
def vertex_cover_dag(n: int, graph_edges):
"""The reduction of the page: one edge x_i per vertex and a connector per graph edge."""
succ: dict = {}
for i in range(n):
succ.setdefault(("a", i), []).append(("b", i))
rows = set()
for i, k in graph_edges:
succ.setdefault(("b", i), []).append(("a", k))
rows.add(frozenset({(("a", i), ("b", i)), (("b", i), ("a", k)), (("a", k), ("b", k))}))
return succ, rows
def test_vertex_cover_reduction():
rng = random.Random(34)
for _ in range(80):
n = rng.randint(1, 6)
ge = [(i, k) for i in range(n) for k in range(i + 1, n) if rng.random() < 0.4]
_, rows = vertex_cover_dag(n, ge)
vc = next(k for k in range(n + 1) for s in itertools.combinations(range(n), k)
if all(i in s or k2 in s for i, k2 in ge))
assert len(exact_hitting_set(rows)) == vc
def test_greedy_hitting_set_hits_everything():
rng = random.Random(35)
for _ in range(200):
universe = list(range(rng.randint(1, 8)))
rows = {frozenset(rng.sample(universe, rng.randint(1, len(universe)))) for _ in range(rng.randint(0, 6))}
h = greedy_hitting_set(rows)
assert all(r & h for r in rows)
assert len(exact_hitting_set(rows)) <= len(h)
History
Camposano described the method at HICSS and, with Bergamaschi, at DAC in 1990, and in full in IEEE TCAD in 1991. Bergamaschi and Camposano extended it to trade area against the number of states at EURO-DAC 1991. Later work in HLS combined it with code motion over branches, since the fixed order of operations limits what it can find.
References
- Raul Camposano, Path-based scheduling for synthesis, IEEE Transactions on Computer-Aided Design of Integrated Circuits and Systems 10(1), 85 to 93, 1991, the scheduling of each path as fast as possible, the constraints as intervals on a path and the merge of all paths into one finite state machine
- Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 5, Schedule Optimization (scheduling with control flow)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 60ZARY Edit this page History Report an error Markdown