Algorithmcore
Static scheduling of synchronous dataflow
Also called periodic admissible sequential schedule, PASS construction, SDF balance equations.
Solves the balance equations of an SDF graph for the repetition vector and simulates one period to build a periodic admissible schedule or prove deadlock.
- Solves
- High-level synthesis
- Time
- O(n + E + (n + Q D) D) worst
- Space
- O(n + E) extra
- Where
- D = the largest number of edges at one actor; E = the number of edges; Q = the number of firings in one period (the sum of the repetition vector); n = the number of actors
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Edward A. Lee, David G. Messerschmitt, 1987
Static scheduling of synchronous dataflow turns an SDF graph into a fixed firing order that a compiler can emit as straight-line code or as nested loops. It has two steps. The first solves the balance equations of the synchronous dataflow graph for the repetition vector , the number of times each actor fires in one period; if they have no positive solution, the graph cannot run forever in bounded memory. The second simulates one period: it fires any actor that has enough tokens on its inputs and has not yet reached its count, until every actor has fired times or no actor can fire. Lee and Messerschmitt (1987) proved that this greedy simulation never fails when some schedule exists, so it decides deadlock exactly. The schedule that it finds is valid, but its buffer memory can be larger than needed.
In plain words
A factory line has machines that take parts from bins and put parts into other bins, always in the same numbers: this machine takes 3 bolts and makes 2 brackets. Before the line runs, a planner can work out how many times each machine must run so that every bin ends a shift with as many parts as it started with; that is a small system of equations. Then the planner walks through the shift on paper, running any machine that has its parts. If that walk gets stuck, no other plan works either, because running a machine early never takes parts away from another machine. If it gets through, the walk itself is the plan, repeated shift after shift.
The problem
The input is a connected SDF graph, as on the synchronous dataflow page: actors , and edges with a production rate , a consumption rate and initial tokens. The topology matrix has one row per edge, with in column and in column . The output is either a periodic admissible sequential schedule (PASS), a firing sequence in which every actor is enabled when it fires, every actor fires at least once, and the token counts end where they started; or a proof that no PASS exists, because the graph is inconsistent or because it deadlocks.
The algorithm
SDF-SCHEDULE(n, E)- 1
q_1 ← 1; walk a spanning tree of the undirected graph and set q_b ← q_a · p_e / c_e along each tree edge e = (a, b), or q_a ← q_b · c_e / p_e when the walk enters a from b - 2
if p_e · q_a ≠ c_e · q_b for some edge e = (a, b) then return "inconsistent" - 3
scale q by the least common multiple of its denominators, then divide by the gcd of its entries - 4
tokens ← d; count ← 0; seq ← empty; W ← a FIFO queue holding every actor - 5
while W is not empty do - 6
a ← pop W - 7
if count_a < q_a and tokens_e ≥ c_e for every input edge e of a then - 8
take c_e tokens from each input edge e of a, add p_e tokens to each output edge e of a - 9
count_a ← count_a + 1; append a to seq - 10
push a and every actor that reads an output edge of a onto W, unless already there - 11
if count = q then return (q, seq) else return (q, "deadlock")
Lines L1 to L3 compute the repetition vector by the spanning tree walk of Theorem 1 on the synchronous dataflow page, with exact rational arithmetic; Gaussian elimination of gives the same vector more slowly. A self loop has the row , so line L2 rejects it unless . Lines L4 to L10 are the simulation. The queue only saves work: an actor needs another look only after it fires, or after a firing adds tokens to one of its inputs, so line L10 pushes exactly those actors.
Example
Take the ring of the synchronous dataflow page: with rates , with rates , and with rates and initial tokens. Line L1 sets , and , line L2 checks the edge , , and line L3 scales to .
With , the queue starts as .
| step | pop | fires? | tokens on , , | counts | queue after |
|---|---|---|---|---|---|
| start | 0, 0, 3 | 0, 0, 0 | |||
| 1 | yes | 2, 0, 2 | 1, 0, 0 | ||
| 2 | no, needs 3 | 2, 0, 2 | 1, 0, 0 | ||
| 3 | no, needs 2 | 2, 0, 2 | 1, 0, 0 | ||
| 4 | yes | 4, 0, 1 | 2, 0, 0 | ||
| 5 | yes | 6, 0, 0 | 3, 0, 0 | ||
| 6 | yes | 3, 1, 0 | 3, 1, 0 | ||
| 7 | no, count reached | 3, 1, 0 | 3, 1, 0 | ||
| 8 | yes | 0, 2, 0 | 3, 2, 0 | ||
| 9 | yes | 0, 0, 3 | 3, 2, 1 |
The last three pops find every actor at its count, so the queue empties and the algorithm returns and the sequence , with the tokens back at . The order is also a PASS. Its largest token counts are , while those of are , so the order changes the buffer memory.
With , fires twice and once, which leaves 1 token on , 1 token on and none on . No actor is enabled, the counts are , and the algorithm reports a deadlock. By the theorem below, no other order does better.
Correctness
The full proof shows:
- The repetition vector. If line L2 passes, is the least positive integer solution of ; if it fails, and no PASS exists. This is Theorem 1 of the synchronous dataflow page applied to the walk.
- Valid output. Every firing in seq is enabled when it happens, every actor fires times, and the final token counts are , so seq is a PASS.
- Deadlock is real. If the simulation stops with , then no PASS exists. The proof first cuts any PASS down to an admissible sequence with counts exactly , and then shows that the first firing of that sequence that the simulation did not make would have been enabled at the end of the simulation.
So the algorithm is exact for the question "does a PASS exist", in the order of firings that it chooses. It is not exact for any measure of the schedule: the proof says nothing about buffer memory or code size, and the example shows a schedule whose buffer on is 6 where 4 is enough.
Proof: Correctness of static SDF schedulingfull
We use the notation of the page. The graph is connected, with actors and edges with rates and initial tokens. After an admissible sequence in which actor fires times, the token count of edge is (for a self loop, ), whatever the order of the firings. We write this as .
Lemma 1 (the repetition vector)
If line L2 passes, the vector of line L3 has positive integer entries with gcd 1, and the integer solutions of are exactly the multiples of . If line L2 fails, has no solution other than , and no PASS exists.
Proof. Let with real. The row of a tree edge says , so the walk of line L1 forces , where is the vector of line L1 with ; every entry of is a positive rational. If some edge fails line L2, then is not a solution, so only is, and . A PASS with counts ends in the state , so with ; hence no PASS exists. If every edge passes, is a solution, and the solutions are its real multiples. Line L3 makes the entries integers with gcd 1. An integer solution with in lowest terms has , so for all , so .
Lemma 2 (the simulation is admissible)
Every firing that line L8 makes is enabled, and no actor fires more than times.
Proof. Line L7 checks both conditions just before line L8 fires .
Lemma 3 (the queue misses nothing)
When the loop of lines L5 to L10 ends, no actor has and is enabled.
Proof. We show that at the start of each iteration of the loop, every actor that has and is enabled is in . At the start, holds every actor. Consider one iteration that pops .
- If does not fire, then is not enabled or has reached its count, and nothing else changes, so the claim still holds.
- If fires, the tokens change only on the edges at . An actor that was not enabled can become enabled only if one of its input edges gains tokens, so it reads an output edge of , and line L10 pushes it. Taking tokens from the input edges of can disable but no other actor, because each edge has exactly one reader. The count changes only for , which line L10 pushes too.
When is empty, the claim says that no actor is enabled with .
Lemma 4 (a PASS can be cut to counts q)
If a PASS exists, then there is an admissible sequence in which each actor fires exactly times.
Proof. Let be a PASS. By Lemma 1 its counts are for an integer . Let be with every firing of after the -th one deleted, for each actor . Take a firing in , the -th of actor with , and an input edge of with . Let be the number of firings of before it in ; in the number is . In the firing was enabled, so . If , the count in is the same. If , the count in is
using and the balance equation . For a self loop, the balance equation gives , so the count is at every firing of in both sequences. So every firing of is enabled, and has the counts .
Theorem
The algorithm returns "inconsistent" exactly when the balance equations have no positive solution, and then no PASS exists. Otherwise it returns a PASS whenever one exists, and reports a deadlock only when none exists.
Proof. The first sentence is Lemma 1. Suppose line L2 passes. If line L11 finds , then by Lemma 2 seq is admissible, every actor fires times, and the final state is , so seq is a PASS.
Now suppose a PASS exists but the simulation stops with counts , where by Lemma 2. By Lemma 4 there is an admissible sequence with counts exactly . Since , some firing of is the -th firing of an actor with . Let it be the first such firing in . Then , so at the end of the simulation. Before this firing, has fired each actor at most times, by the choice of the first such firing. For an input edge with , the firing is enabled in , so with earlier firings of ,
and the right side is the token count of at the end of the simulation. For a self loop, and the count is in both runs. So is enabled at the end of the simulation with , which contradicts Lemma 3. Hence the simulation reaches whenever a PASS exists.
What is not proved
The proof does not depend on the order in which line L6 picks actors, and it says nothing about which PASS is returned. In particular, the returned schedule need not have the least buffer memory, the shortest looped form, or the best period on several processors; the example of the page has a schedule with buffer 6 on one edge where another PASS needs 4.
Complexity
Lines L1 to L3 make rational operations. The numbers can be long: a chain of actors in which each produces 2 tokens and the next consumes 1 has , so can be exponential in , and the simulation is linear in , not in the size of the graph. Each firing costs on line L8 and pushes at most actors on line L10, and each pop costs on line L7. There are at most pops, so the simulation takes time. The extra space is for the counts, the tokens and the queue, plus the output of length .
Properties
- Exact for deadlock. It finds a PASS whenever one exists.
- Any order works. The proof holds for any rule that picks an enabled actor below its count, so the queue on line L6 can be replaced by any rule that suits the code generator.
- Deterministic. With the FIFO queue the output is fixed.
- Sequential. It gives one firing order for one processor. Parallel schedules need the precedence expansion described on the synchronous dataflow page.
- Not memory optimal. Different valid orders need different buffer sizes.
Variants and improvements
- Looped and single appearance schedules. Code size grows with if every firing is a line of code. Bhattacharyya, Murthy and Lee (1996) write schedules as nested loops, such as for the ring, and study single appearance schedules, in which each actor appears once. These exist only under conditions on the cycles of the graph, and choosing the loop nest trades code size against buffer memory; the book gives heuristics for this trade.
- Buffer minimization. Among all PASSes, choose one with the least total buffer. The greedy order is not chosen for this; the book treats the problem and its heuristics.
- Parallel schedules. Expand the graph into its precedence graph, with copies of actor , and schedule that graph on several processors with a list scheduler. With execution times, the best period on unlimited processors is the iteration bound of the expansion, and unfolding several periods can help to reach it.
- The requirement graph. The proof of Theorem 3 on the synchronous dataflow page gives another exact test: build the graph of firings and their requirements, and look for a cycle with a topological sort. The simulation is simpler and does the same work in the same order of time.
When to use it
Use it in any compiler or synthesis tool for SDF graphs, as the first check that a program can run forever in bounded memory and as the source of a valid schedule. When code size or buffer memory matters, use its answer as a starting point for a looped or memory-aware scheduler, never as the final schedule. When some rates depend on the data, SDF does not apply; the program is a general Kahn process network, and these questions become undecidable.
Pitfalls
- Floating point rates. Lines L1 to L3 need exact rationals or integers. With floating point, a consistent graph can fail line L2 by rounding, or an inconsistent one can pass.
- Overflow. Entries of grow as products of rates along paths, as in the chain above. Fixed-width integers can overflow on large graphs.
- Firing up to . A loop that fires until no actor is enabled, without the bound count, runs forever on a graph that has a PASS. The bound is what ends the period.
- Stopping on the first blocked actor. A blocked actor may become enabled later. Only an empty queue, with every actor blocked or at its count, proves a deadlock.
- Self loops and disconnected graphs. A self loop with makes the graph inconsistent. A graph with several components must be split first, since its null space has one dimension per component.
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/sdf-static-scheduling/. The authors are listed in prov/XS6G6S.jsonl.
"""Static scheduling of a synchronous dataflow graph (Lee and Messerschmitt).
Actors are 0, ..., n - 1. An edge is (src, dst, prod, cons, delay): each
firing of src puts prod tokens on it, each firing of dst takes cons tokens
from it, and it holds delay tokens at the start. The graph must be
connected (as an undirected graph).
"""
from collections import deque
from fractions import Fraction
from math import gcd, lcm
def topology_matrix(n, edges):
"""Gamma with one row per edge: +prod in the src column, -cons in the dst column."""
rows = []
for s, d, p, c, _ in edges:
row = [0] * n
row[s] += p
row[d] -= c
rows.append(row)
return rows
def repetition_vector(n, edges):
"""The least positive integer q with Gamma q = 0, or None if none exists.
Fix q_0 = 1, give every actor reached along an edge the rate that the
balance equation of that edge forces, then check every edge.
"""
adj = [[] for _ in range(n)]
for s, d, p, c, _ in edges:
if p <= 0 or c <= 0:
raise ValueError("rates must be positive")
adj[s].append((d, Fraction(p, c)))
adj[d].append((s, Fraction(c, p)))
q = [None] * n
q[0] = Fraction(1)
stack = [0]
while stack:
a = stack.pop()
for b, f in adj[a]:
if q[b] is None:
q[b] = q[a] * f # @line L1
stack.append(b)
if any(x is None for x in q):
raise ValueError("the graph is not connected")
if any(q[s] * p != q[d] * c for s, d, p, c, _ in edges): # @line L2
return None
m = lcm(*(x.denominator for x in q)) # @line L3
ints = [int(x * m) for x in q]
g = 0
for x in ints:
g = gcd(g, x)
return [x // g for x in ints]
def schedule(n, edges):
"""Return (q, firing sequence) for one period, or (q, None) on deadlock.
q is None when the balance equations have no positive solution. The
simulation fires any actor that has enough tokens on every input edge
and has fired fewer than q times. A FIFO worklist holds actors to look
at again; an actor is put back when a firing adds tokens to one of its
input edges.
"""
q = repetition_vector(n, edges)
if q is None:
return None, None
ins = [[] for _ in range(n)]
outs = [[] for _ in range(n)]
for i, (s, d, p, c, _) in enumerate(edges):
outs[s].append(i)
ins[d].append(i)
tokens = [e[4] for e in edges] # @line L4
count = [0] * n
seq = []
work = deque(range(n))
queued = [True] * n
while work: # @line L5
a = work.popleft() # @line L6
queued[a] = False
if count[a] == q[a] or any(tokens[i] < edges[i][3] for i in ins[a]): # @line L7
continue
for i in ins[a]: # @line L8
tokens[i] -= edges[i][3]
for i in outs[a]:
tokens[i] += edges[i][2]
count[a] += 1 # @line L9
seq.append(a)
for b in [a] + [edges[i][1] for i in outs[a]]: # @line L10
if not queued[b]:
queued[b] = True
work.append(b)
if count != q: # @line L11
return q, None
return q, seq
def buffer_sizes(edges, seq):
"""The largest token count of each edge while seq runs."""
tokens = [e[4] for e in edges]
peak = list(tokens)
for a in seq:
for i, (s, d, p, c, _) in enumerate(edges):
if d == a:
tokens[i] -= c
for i, (s, d, p, c, _) in enumerate(edges):
if s == a:
tokens[i] += p
peak[i] = max(peak[i], tokens[i])
return peak
test_sdf_static_scheduling.py 215 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sdf-static-scheduling/. The authors are listed in prov/XS6G6S.jsonl.
import random
from fractions import Fraction
from math import gcd, lcm
from sdf_static_scheduling import buffer_sizes, repetition_vector, schedule, topology_matrix
# A -(2, 3)-> B -(1, 2)-> C -(3, 1)-> A, with d tokens on the edge C -> A.
def ring(d):
return [(0, 1, 2, 3, 0), (1, 2, 1, 2, 0), (2, 0, 3, 1, d)]
def null_space(rows, n):
"""Basis of {x : rows x = 0} over the rationals, by Gauss-Jordan elimination."""
m = [[Fraction(v) for v in r] for r in rows]
pivots = []
r = 0
for col in range(n):
piv = next((i for i in range(r, len(m)) if m[i][col] != 0), None)
if piv is None:
continue
m[r], m[piv] = m[piv], m[r]
inv = 1 / m[r][col]
m[r] = [v * inv for v in m[r]]
for i in range(len(m)):
if i != r and m[i][col] != 0:
f = m[i][col]
m[i] = [a - f * b for a, b in zip(m[i], m[r])]
pivots.append(col)
r += 1
free = [c for c in range(n) if c not in pivots]
basis = []
for fcol in free:
x = [Fraction(0)] * n
x[fcol] = Fraction(1)
for i, pc in enumerate(pivots):
x[pc] = -m[i][fcol]
basis.append(x)
return basis
def least_positive(x):
if all(v < 0 for v in x):
x = [-v for v in x]
if not all(v > 0 for v in x):
return None
k = lcm(*(v.denominator for v in x))
ints = [int(v * k) for v in x]
g = 0
for v in ints:
g = gcd(g, v)
return [v // g for v in ints]
def run(edges, seq):
"""Token counts after each firing; fail if one goes negative."""
tokens = [e[4] for e in edges]
for a in seq:
for i, (s, d, p, c, _) in enumerate(edges):
if d == a:
tokens[i] -= c
assert tokens[i] >= 0
for i, (s, d, p, c, _) in enumerate(edges):
if s == a:
tokens[i] += p
return tokens
def some_period_exists(n, edges, q):
"""Brute force: search all orders of firings with counts at most q."""
start = (tuple(e[4] for e in edges), tuple([0] * n))
seen = {start}
stack = [start]
while stack:
tokens, count = stack.pop()
if list(count) == q:
return True
for a in range(n):
if count[a] == q[a]:
continue
if any(d == a and tokens[i] < c for i, (s, d, p, c, _) in enumerate(edges)):
continue
t = list(tokens)
for i, (s, d, p, c, _) in enumerate(edges):
if d == a:
t[i] -= c
if s == a:
t[i] += p
cnt = list(count)
cnt[a] += 1
state = (tuple(t), tuple(cnt))
if state not in seen:
seen.add(state)
stack.append(state)
return False
def random_graph(rng: random.Random):
n = rng.randint(1, 4)
edges = []
for b in range(1, n):
a = rng.randrange(b)
if rng.random() < 0.5:
a, b = b, a
edges.append((a, b, rng.randint(1, 3), rng.randint(1, 3), rng.randint(0, 4)))
for _ in range(rng.randint(0, 3)):
edges.append((rng.randrange(n), rng.randrange(n), rng.randint(1, 3), rng.randint(1, 3), rng.randint(0, 5)))
return n, edges
def simple_cycles(n, edges):
out = []
def walk(s, v, path, seen):
for i, e in enumerate(edges):
if e[0] != v:
continue
if e[1] == s:
out.append(path + [i])
elif e[1] not in seen and e[1] > s:
walk(s, e[1], path + [i], seen | {e[1]})
for s in range(n):
walk(s, s, [], {s})
return out
def cycle_completes(edges, cyc, q):
"""Can the cycle alone, with its own initial tokens, fire each actor q times?"""
sub = [edges[i] for i in cyc]
actors = [e[0] for e in sub]
tokens = [e[4] for e in sub]
count = {a: 0 for a in actors}
moved = True
while moved:
moved = False
for j, a in enumerate(actors):
k = (j - 1) % len(sub) # the edge of the cycle that enters a
if count[a] < q[a] and tokens[k] >= sub[k][3]:
tokens[k] -= sub[k][3]
tokens[j] += sub[j][2]
count[a] += 1
moved = True
return all(count[a] == q[a] for a in actors)
def test_deadlock_exactly_when_a_cycle_is_short_of_tokens():
rng = random.Random(1971)
checked = 0
for _ in range(1500):
n, edges = random_graph(rng)
q, seq = schedule(n, edges)
if q is None or max(q) > 12:
continue
checked += 1
short = any(not cycle_completes(edges, c, q) for c in simple_cycles(n, edges))
assert (seq is None) == short
assert checked > 400
def test_ring_example():
assert topology_matrix(3, ring(0)) == [[2, -3, 0], [0, 1, -2], [-1, 0, 3]]
assert repetition_vector(3, ring(0)) == [3, 2, 1]
for d in range(3):
assert schedule(3, ring(d)) == ([3, 2, 1], None)
q, seq = schedule(3, ring(3))
assert q == [3, 2, 1]
assert seq == [0, 0, 0, 1, 1, 2]
assert run(ring(3), seq) == [0, 0, 3]
assert buffer_sizes(ring(3), seq) == [6, 2, 3]
# Another valid order needs a smaller buffer on the first edge.
assert run(ring(3), [0, 0, 1, 0, 1, 2]) == [0, 0, 3]
assert buffer_sizes(ring(3), [0, 0, 1, 0, 1, 2]) == [4, 2, 3]
def test_inconsistent():
edges = [(0, 1, 2, 3, 0), (1, 2, 1, 2, 0), (2, 0, 2, 1, 5)]
assert repetition_vector(3, edges) is None
assert schedule(3, edges) == (None, None)
assert null_space(topology_matrix(3, edges), 3) == []
def test_chain_grows_exponentially():
n = 12
edges = [(i, i + 1, 2, 1, 0) for i in range(n - 1)]
assert repetition_vector(n, edges) == [2 ** i for i in range(n)]
def test_random_against_null_space_and_search():
rng = random.Random(1987)
consistent = deadlocked = 0
for _ in range(1500):
n, edges = random_graph(rng)
basis = null_space(topology_matrix(n, edges), n)
q = repetition_vector(n, edges)
if q is None:
assert len(basis) == 0 or least_positive(basis[0]) is None
assert schedule(n, edges) == (None, None)
continue
assert len(basis) == 1 and least_positive(basis[0]) == q
consistent += 1
if sum(q) > 40:
continue
q2, seq = schedule(n, edges)
assert q2 == q
exists = some_period_exists(n, edges, q)
assert (seq is not None) == exists
if seq is None:
deadlocked += 1
continue
assert sorted(seq) == sorted(a for a in range(n) for _ in range(q[a]))
assert run(edges, seq) == [e[4] for e in edges]
assert consistent > 400 and deadlocked > 30
History
Lee and Messerschmitt (1987) introduced synchronous dataflow for signal processing and gave the rank test, the repetition vector and the class-S algorithm, the simulation of this page, with the proof that it finds a PASS whenever one exists. The Ptolemy project at Berkeley built code generators on these schedules. Bhattacharyya, Murthy and Lee (1996) turned the flat schedules into looped schedules with small code and buffer memory.
References
- Edward A. Lee and David G. Messerschmitt, Static scheduling of synchronous data flow programs for digital signal processing, IEEE Transactions on Computers C-36(1), 24 to 35, 1987, the rank test, the class-S algorithm for a periodic admissible sequential schedule and its proof, and the expansion for parallel schedules
- Edward A. Lee and David G. Messerschmitt, Synchronous data flow, Proceedings of the IEEE 75(9), 1235 to 1245, 1987, the SDF model and an overview of its static scheduling
- Shuvra S. Bhattacharyya, Praveen K. Murthy and Edward A. Lee, Software Synthesis from Dataflow Graphs, Kluwer, 1996, the chapters on consistency, looped schedules, single appearance schedules and buffer memory
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 XS6G6S Edit this page History Report an error Markdown