Algorithm Search⌘K

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.

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
Properties
deterministicexactofflineiterative
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 Γq=0\Gamma q = 0 of the synchronous dataflow graph for the repetition vector qq, 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 qaq_a 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 1,…,n1, \ldots, n, and edges e=(a,b)e = (a, b) with a production rate pe≥1p_e \ge 1, a consumption rate ce≥1c_e \ge 1 and de≥0d_e \ge 0 initial tokens. The topology matrix Γ\Gamma has one row per edge, with pep_e in column aa and −ce-c_e in column bb. 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

  1. SDF-SCHEDULE(n, E)
  2. 1q_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
  3. 2if p_e · q_a ≠ c_e · q_b for some edge e = (a, b) then return "inconsistent"
  4. 3scale q by the least common multiple of its denominators, then divide by the gcd of its entries
  5. 4tokens ← d; count ← 0; seq ← empty; W ← a FIFO queue holding every actor
  6. 5while W is not empty do
  7. 6a ← pop W
  8. 7if count_a < q_a and tokens_e ≥ c_e for every input edge e of a then
  9. 8take c_e tokens from each input edge e of a, add p_e tokens to each output edge e of a
  10. 9count_a ← count_a + 1; append a to seq
  11. 10push a and every actor that reads an output edge of a onto W, unless already there
  12. 11if 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 Γ\Gamma gives the same vector more slowly. A self loop has the row pe−cep_e - c_e, so line L2 rejects it unless pe=cep_e = c_e. Lines L4 to L10 are the simulation. The queue WW 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: A→BA \to B with rates (2,3)(2, 3), B→CB \to C with rates (1,2)(1, 2), and C→AC \to A with rates (3,1)(3, 1) and dd initial tokens. Line L1 sets qA=1q_A = 1, qB=2/3q_B = 2/3 and qC=1/3q_C = 1/3, line L2 checks the edge C→AC \to A, 3⋅1/3=1⋅13 \cdot 1/3 = 1 \cdot 1, and line L3 scales to q=(3,2,1)q = (3, 2, 1).

With d=3d = 3, the queue starts as A,B,CA, B, C.

step pop fires? tokens on A→BA{\to}B, B→CB{\to}C, C→AC{\to}A counts A,B,CA, B, C queue after
start 0, 0, 3 0, 0, 0 A,B,CA, B, C
1 AA yes 2, 0, 2 1, 0, 0 B,C,AB, C, A
2 BB no, needs 3 2, 0, 2 1, 0, 0 C,AC, A
3 CC no, needs 2 2, 0, 2 1, 0, 0 AA
4 AA yes 4, 0, 1 2, 0, 0 A,BA, B
5 AA yes 6, 0, 0 3, 0, 0 B,AB, A
6 BB yes 3, 1, 0 3, 1, 0 A,B,CA, B, C
7 AA no, count reached 3, 1, 0 3, 1, 0 B,CB, C
8 BB yes 0, 2, 0 3, 2, 0 C,BC, B
9 CC yes 0, 0, 3 3, 2, 1 B,C,AB, C, A

The last three pops find every actor at its count, so the queue empties and the algorithm returns q=(3,2,1)q = (3, 2, 1) and the sequence AAABBCAAABBC, with the tokens back at (0,0,3)(0, 0, 3). The order AABABCAABABC is also a PASS. Its largest token counts are (4,2,3)(4, 2, 3), while those of AAABBCAAABBC are (6,2,3)(6, 2, 3), so the order changes the buffer memory.

With d=2d = 2, AA fires twice and BB once, which leaves 1 token on A→BA \to B, 1 token on B→CB \to C and none on C→AC \to A. No actor is enabled, the counts are (2,1,0)≠q(2, 1, 0) \ne q, 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, qq is the least positive integer solution of Γq=0\Gamma q = 0; if it fails, rank⁡Γ=n\operatorname{rank} \Gamma = n 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 qa≥1q_a \ge 1 times, and the final token counts are d+Γq=dd + \Gamma q = d, so seq is a PASS.
  • Deadlock is real. If the simulation stops with count≠q\mathrm{count} \ne q, then no PASS exists. The proof first cuts any PASS down to an admissible sequence with counts exactly qq, 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 A→BA \to B 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 1,…,n1, \ldots, n and edges e=(a,b)e = (a, b) with rates pe,ce≥1p_e, c_e \ge 1 and de≥0d_e \ge 0 initial tokens. After an admissible sequence in which actor aa fires xax_a times, the token count of edge ee is de+pexa−cexbd_e + p_e x_a - c_e x_b (for a self loop, de+(pe−ce)xad_e + (p_e - c_e) x_a), whatever the order of the firings. We write this as d+Γxd + \Gamma x.

Lemma 1 (the repetition vector)

If line L2 passes, the vector qq of line L3 has positive integer entries with gcd 1, and the integer solutions of Γx=0\Gamma x = 0 are exactly the multiples of qq. If line L2 fails, Γx=0\Gamma x = 0 has no solution other than x=0x = 0, and no PASS exists.

Proof. Let Γx=0\Gamma x = 0 with xx real. The row of a tree edge e=(a,b)e = (a, b) says pexa=cexbp_e x_a = c_e x_b, so the walk of line L1 forces x=x1⋅yx = x_1 \cdot y, where yy is the vector of line L1 with y1=1y_1 = 1; every entry of yy is a positive rational. If some edge fails line L2, then yy is not a solution, so only x1=0x_1 = 0 is, and x=0x = 0. A PASS with counts xx ends in the state d+Γx=dd + \Gamma x = d, so Γx=0\Gamma x = 0 with x≠0x \ne 0; hence no PASS exists. If every edge passes, yy is a solution, and the solutions are its real multiples. Line L3 makes the entries integers with gcd 1. An integer solution x=rqx = r q with r=u/vr = u / v in lowest terms has v∣uqav \mid u q_a, so v∣qav \mid q_a for all aa, so v=1v = 1. □\square

Lemma 2 (the simulation is admissible)

Every firing that line L8 makes is enabled, and no actor fires more than qaq_a times.

Proof. Line L7 checks both conditions just before line L8 fires aa. □\square

Lemma 3 (the queue misses nothing)

When the loop of lines L5 to L10 ends, no actor aa has counta<qa\mathrm{count}_a < q_a and is enabled.

Proof. We show that at the start of each iteration of the loop, every actor that has counta<qa\mathrm{count}_a < q_a and is enabled is in WW. At the start, WW holds every actor. Consider one iteration that pops aa.

  • If aa does not fire, then aa is not enabled or has reached its count, and nothing else changes, so the claim still holds.
  • If aa fires, the tokens change only on the edges at aa. An actor b≠ab \ne a that was not enabled can become enabled only if one of its input edges gains tokens, so it reads an output edge of aa, and line L10 pushes it. Taking tokens from the input edges of aa can disable aa but no other actor, because each edge has exactly one reader. The count changes only for aa, which line L10 pushes too.

When WW is empty, the claim says that no actor is enabled with counta<qa\mathrm{count}_a < q_a. □\square

Lemma 4 (a PASS can be cut to counts q)

If a PASS exists, then there is an admissible sequence in which each actor aa fires exactly qaq_a times.

Proof. Let σ\sigma be a PASS. By Lemma 1 its counts are JqJ q for an integer J≥1J \ge 1. Let σ′\sigma' be σ\sigma with every firing of aa after the qaq_a-th one deleted, for each actor aa. Take a firing in σ′\sigma', the kk-th of actor bb with k≤qbk \le q_b, and an input edge e=(a,b)e = (a, b) of bb with a≠ba \ne b. Let mm be the number of firings of aa before it in σ\sigma; in σ′\sigma' the number is min⁡(m,qa)\min(m, q_a). In σ\sigma the firing was enabled, so de+pem−ce(k−1)≥ced_e + p_e m - c_e (k - 1) \ge c_e. If m≤qam \le q_a, the count in σ′\sigma' is the same. If m>qam > q_a, the count in σ′\sigma' is

de+peqa−ce(k−1)≥peqa−ce(qb−1)=ce,d_e + p_e q_a - c_e (k - 1) \ge p_e q_a - c_e (q_b - 1) = c_e,

using k≤qbk \le q_b and the balance equation peqa=ceqbp_e q_a = c_e q_b. For a self loop, the balance equation gives pe=cep_e = c_e, so the count is ded_e at every firing of bb in both sequences. So every firing of σ′\sigma' is enabled, and σ′\sigma' has the counts qq. □\square

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 count=q\mathrm{count} = q, then by Lemma 2 seq is admissible, every actor fires qa≥1q_a \ge 1 times, and the final state is d+Γq=dd + \Gamma q = d, so seq is a PASS.

Now suppose a PASS exists but the simulation stops with counts x≠qx \ne q, where x≤qx \le q by Lemma 2. By Lemma 4 there is an admissible sequence σ′\sigma' with counts exactly qq. Since x≠qx \ne q, some firing of σ′\sigma' is the kk-th firing of an actor bb with k>xbk > x_b. Let it be the first such firing in σ′\sigma'. Then k=xb+1≤qbk = x_b + 1 \le q_b, so countb=xb<qb\mathrm{count}_b = x_b < q_b at the end of the simulation. Before this firing, σ′\sigma' has fired each actor aa at most xax_a times, by the choice of the first such firing. For an input edge e=(a,b)e = (a, b) with a≠ba \ne b, the firing is enabled in σ′\sigma', so with m≤xam \le x_a earlier firings of aa,

ce≤de+pem−cexb≤de+pexa−cexb,c_e \le d_e + p_e m - c_e x_b \le d_e + p_e x_a - c_e x_b,

and the right side is the token count of ee at the end of the simulation. For a self loop, pe=cep_e = c_e and the count is ded_e in both runs. So bb is enabled at the end of the simulation with countb<qb\mathrm{count}_b < q_b, which contradicts Lemma 3. Hence the simulation reaches count=q\mathrm{count} = q whenever a PASS exists. ■\blacksquare

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 O(n+E)O(n + E) rational operations. The numbers can be long: a chain of nn actors in which each produces 2 tokens and the next consumes 1 has q=(1,2,4,…,2n−1)q = (1, 2, 4, \ldots, 2^{n-1}), so QQ can be exponential in nn, and the simulation is linear in QQ, not in the size of the graph. Each firing costs O(D)O(D) on line L8 and pushes at most D+1D + 1 actors on line L10, and each pop costs O(D)O(D) on line L7. There are at most n+Q(D+1)n + Q(D + 1) pops, so the simulation takes O((n+QD)D)O((n + Q D) D) time. The extra space is O(n+E)O(n + E) for the counts, the tokens and the queue, plus the output of length QQ.

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 QQ if every firing is a line of code. Bhattacharyya, Murthy and Lee (1996) write schedules as nested loops, such as (3A)(2B)C(3A)(2B)C 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 qaq_a copies of actor aa, 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 qq grow as products of rates along paths, as in the chain above. Fixed-width integers can overflow on large graphs.
  • Firing up to JqJ q. A loop that fires until no actor is enabled, without the bound counta<qa_a < q_a, 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 pe≠cep_e \ne c_e 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.

sdf_static_scheduling.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example