Algorithmadvanced
SDC-based scheduling
Also called system of difference constraints scheduling, Cong-Zhang scheduling.
Cong and Zhang's scheduler that writes timing, latency and relative constraints as difference constraints, so the LP is totally unimodular and gives integer schedules.
- Time
- O(V (V + E) + V C) worst
- Space
- O(V^2 + C) extra
- Where
- C = the number of difference constraints; E = the number of data edges; V = the number of operations
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jason Cong, Zhiru Zhang, 2006
SDC-based scheduling is a scheduler of high-level synthesis by Cong and Zhang (2006). It gives each operation one integer variable, its start step, and writes every rule of the schedule as a difference constraint : data dependences, chaining within the clock period, minimum and maximum distances between operations, and a latency bound. A system of difference constraints has a constraint matrix in which each row has one and one . Such a matrix is totally unimodular, so a linear program over it has an integral optimal vertex, and a linear objective can be optimized in polynomial time with no integer search. Resource limits do not fit this form, so the scheduler turns them into extra difference constraints from a fixed order of the operations of each type. That step is a heuristic: the schedule always meets the limits, but it is not always the shortest one.
In plain words
Give each operation a number, the clock step in which it starts. Every rule becomes "this number minus that number is at least so much": the multiply must start two steps after the add that feeds it, the three adds in a row do not fit in one clock, everything must end by step ten. Rules of this simple shape are easy. The smallest numbers that obey them all come from a longest path search, and any other straight-line goal is solved exactly by a linear program, which here never answers with fractions. The one rule that does not fit is "at most two multiplies per step". The trick is to line up the multiplies and say "the third one starts after the first one ends", which keeps the simple shape but may waste a step.
The problem
The input is one data flow graph with no cycle. Each operation has a latency in cycles, a combinational delay , and a type . An operation with is combinational: it may run in the same step as its predecessors, and its delay must be at most the clock period . An operation with registers its result, so it breaks combinational paths, and it keeps its unit busy for steps. Some types have a limit on their units. A schedule is valid when
- for each edge ;
- every path of combinational operations that all start in one step has a total delay of at most ;
- in each step, at most operations of type are busy;
- if a latency bound is given, for all .
The goal is a valid schedule that minimizes a linear cost , such as the sum of the starts, or that has a small latency . With the resource limits this contains resource-constrained scheduling, which is NP-hard, so no polynomial method is exact for it unless P = NP.
The algorithm
For two combinational operations and joined by a path of combinational operations, let be the largest total delay of such a path, counting both ends. Write each constraint as a triple for .
SDC-SCHEDULE(G, ℓ, δ, k, a, T, L, w)- 1
C ← ∅ - 2
for each edge (u, v) of G do add s_v − s_u ≥ ℓ(u) to C - 3
for each pair (u, v) with D(u, v) > T do add s_v − s_u ≥ ⌈D(u, v) / T⌉ − 1 to C - 4
compute ASAP(v) and ALAP(v) for each v from C, by longest paths - 5
for each type k with a limit a_k do - 6
o ← the operations of type k, sorted by (ALAP, ASAP, topological index) - 7
for i ← 1 to |o| − a_k do add s_{o[i + a_k]} − s_{o[i]} ≥ max(1, ℓ(o[i])) to C - 8
if L is given then add s_v ≤ L − max(1, ℓ(v)) for each v - 9
s* ← the least s ≥ 0 that meets C, by longest paths; if there is none or s* breaks L8 then return "infeasible" - 10
if every w_v ≥ 0 then return s* - 11
return an optimal vertex of the LP: minimize Σ w_v s_v subject to C, the bounds of L8 and s ≥ 0
Lines L2 and L3 are exact: they hold for a schedule exactly when its dependences and its clock period hold. Line L7 links the operations of type into chains, positions of the order, and in each chain an operation starts only after the previous one is no longer busy. User constraints, such as a maximum distance , enter as . Line L9 is Bellman-Ford for longest paths from an imaginary source with an edge of weight 0 to each operation. Line L11 needs the bound so that the LP is bounded. Cong and Zhang point out that the dual of this LP is a minimum cost flow problem, which polynomial network algorithms solve. The implementation here uses an exact simplex method with Bland's rule, which is enough for small graphs.
Example
Take and six operations: , , , , and . Adds are combinational with delay 2, and multiplies have latency 2. Lines L2 and L3 give
| constraint | reason |
|---|---|
| , , | data edges from adds |
| , | data edges from multiplies |
| , so |
The pairs and have , so two adds may chain but three may not. With no unit limit, the least solution is , with latency 3.
Now allow one multiplier. Line L4 gives ALAP 0 for both and , and equal ASAP values, so the topological index puts first. Line L7 adds . The least solution is with latency 5, which is optimal: the two multiplies need four steps on one unit, and follows the second one.
With and the weights , line L11 maximizes the sum of the starts, an ALAP-like schedule. The LP gives , an integer vertex. The adds and chain in step 4, with delay 4.
The resource step can lose. Take three independent operations of one type with two units and latencies 1, 2 and 1. Line L4 gives ALAP starts 1, 0 and 1, so the order is , and line L7 adds . The schedule has latency 3. The optimum is 2: on one unit in steps 0 and 1, and then on the other.
Correctness
What is proved, in the full proof:
- Total unimodularity. The matrix of with the bound rows of L8 is totally unimodular. So every vertex of the feasible region is integral, and line L11 returns an integer schedule.
- Least solution. The solutions of with are closed under the componentwise minimum, and line L9 finds the least one or proves that none exists. With all it is optimal, so line L10 is exact.
- Exact chaining. A schedule meets the rows of L2 and L3 exactly when it meets the dependences and every in-step combinational path fits in .
- Sound resources. Every solution of the rows of L7 uses at most units of type in each step.
- Always feasible without bounds. With no latency bound and no user constraint, every row of goes forward in the order of line L6 extended to all operations, so has no positive cycle and a schedule always exists.
What is not proved, and is false: that the schedule has the least latency under resource limits. The last example shows a loss of one step. In a measured run of the tests, with 150 random graphs of at most 7 operations, two types and limits of 1 or 2, the latency was above the exhaustive optimum on 4 of them. This is a measurement on small random graphs, not a bound.
Proof: SDC scheduling is exact for timing rules and sound for resource limitsfull
We use the notation of the page. is the set of rows built by lines L2, L3 and L7, plus any user rows, with integer . The bound rows of L8 are with integer . Write for the set of real vectors that meet and the bound rows.
Lemma 1 (total unimodularity). Let be a matrix in which each row has either exactly one and one and zeros elsewhere, or exactly one nonzero entry, equal to . Then every square submatrix of has determinant , or .
Proof. By induction on the size of a square submatrix . For the entries are and . For : if a row of is zero, . If a row of has exactly one nonzero entry, expand along it: for a square submatrix of size , and the claim holds by induction. Otherwise every row of has two nonzero entries, which must be one and one , so the sum of the columns of is the zero vector and .
The rows of , written as , have the first form. The bound rows and the sign rows have the second form. So the full matrix of is totally unimodular. The same holds for the matrix of the standard form that the simplex method uses, because a square submatrix that uses some columns of can be expanded along them, each with at most one nonzero entry, down to a square submatrix of .
Theorem 1 (integral vertices). Every vertex of is an integer vector. If is nonempty and bounded, a linear objective attains its minimum over at an integer vertex, and the simplex method returns one.
Proof. A vertex of is the unique solution of rows of the system that hold with equality at and are linearly independent. Let be their matrix and their right-hand sides, which are integers. By Lemma 1, , and by Cramer's rule each entry of is a determinant with integer entries divided by , an integer. A nonempty polytope is the convex hull of its vertices, so a linear function attains its minimum at a vertex. The simplex method ends at a basic feasible solution of the standard form, which is a vertex of , and its basis matrix is a nonsingular square submatrix of , so the same argument applies to it.
Lemma 2 (closed under minimum). If and meet and , then , taken entry by entry, meets and .
Proof. Take a row . Say ; the case is the same with and swapped. Then and , so .
Theorem 2 (least solution). Line L9 starts with and, in each round, sets for every row. If with has a solution, then after at most rounds no row changes , and is the least solution: entry by entry for every solution . If some round still changes , there is no solution.
Proof. Invariant: for every solution . It holds at the start since . An update sets . Now add a source with a row for each and fix . After round , is at least the largest weight of a path from to with at most edges, by induction on , and is always the weight of some walk from to . If a solution exists, then going around any cycle of rows gives its total weight, so no cycle is positive, the largest walk weight equals the largest path weight, and paths have at most edges. So after round the values equal the longest path weights and round changes nothing. A vector that no row changes meets every row, so it is a solution, and by the invariant it is the least one. Conversely, if round changes some value, a walk with more than edges is heavier than every path, so it holds a positive cycle, and no solution exists.
Corollary (lines L9 and L10). With the bound rows, is nonempty exactly when the least solution of exists and : any point of is a solution of , so it is at least , and then follows; the converse is clear. If for all , then for every , so is optimal. With an integer , is an integer vector, since every update adds integers.
Theorem 3 (exact chaining). Let meet for every edge. Then meets the rows of L3 exactly when every path of combinational operations whose operations all start in one step has total delay at most .
Proof. Suppose the rows of L3 hold, and let be a path of combinational operations from to that all start in step . Its delay is at most . If , the row contradicts . So and the delay of fits. Conversely, suppose every in-step path fits, and take with and a path from to of delay . Along each edge leaves a combinational operation, so the starts do not decrease, and they take the values with . The operations of with start form a contiguous piece of in one step, so its delay is at most . The pieces cover , so , which gives .
Theorem 4 (sound resources). Every that meets the rows of L7 for type has at most busy operations of type in each step.
Proof. Let be the order of L6 and . For a residue , the operations meet , so each one starts after the previous one is no longer busy. By induction along the chain, their busy intervals are pairwise disjoint, so in any step at most one of them is busy. The residues cover all operations of type , so at most of them are busy in a step.
Theorem 5 (feasible without a bound). If there is no latency bound and no user row, then has a solution.
Proof. Let , compared in lexicographic order, where ASAP and ALAP come from the rows of L2 and L3 and topo is the index in a topological order of . The ASAP values are the least solution of those rows, and the ALAP values are computed by over the same rows. Every row of L2 and L3 has and joins to along a path of . So for such a row , and , which gives . Every row of L7 joins to with by the sort. So every row of goes from a smaller key to a larger one, the graph of the rows has no cycle at all, and by Theorem 2 the least solution exists.
What is not claimed. Theorem 4 shows that the rows of L7 are sufficient for the resource limits. They are not necessary: a valid schedule may break them. So the least solution of can have a larger latency than the best valid schedule. The page gives an instance with three operations where it loses one step.
Complexity
Line L3 computes by one pass over the graph for each combinational operation, in time, and adds at most rows. Lines L5 to L7 add fewer than rows in all. Lines L4 and L9 run Bellman-Ford in time, where is at most . So the case of nonnegative weights takes time and space. Line L11 solves an LP with variables and rows. As a minimum cost flow dual it takes polynomial time. The simplex method of the implementation has no polynomial bound in the worst case.
Properties
- Exact for timing, heuristic for resources. All dependence, chaining, latency and relative timing rules are exact. Resource limits are met but may cost latency.
- Integral without branching. No integer program is solved. The LP optimum is integral because of the matrix structure, not because of rounding.
- Global objective. Unlike list scheduling, which decides step by step, the LP sees all operations at once, so the objective can be the sum of the starts, the slack of the edges or the lifetimes of values.
- Incremental. Adding one constraint changes the least solution by a longest path update from the changed node, so a tool can add and remove constraints cheaply.
- Deterministic. The order of line L6 has a full tie-break, and the simplex method uses Bland's rule.
Variants and improvements
- Other objectives. Cong and Zhang list the ASAP and ALAP objectives, the latency of the exit block, an expected latency from a profile, and the total slack of the edges, which is a linear cost with mixed signs and so needs the LP.
- Several blocks. For a whole control data flow graph, each block gets a super source and a super sink, and the control edges become difference constraints between them.
- Pipelined units. A unit that accepts a new operation every cycle needs a separation of 1 in line L7, or the initiation interval of the unit.
- Better resource orders. The order of line L6 can come from a list schedule, or be repaired after the LP when it causes a loss, in a loop.
- Loops. SDC modulo scheduling adds constraints with the initiation interval for the edges that cross iterations, and handles the modulo resource limits by an incremental repair.
- Exact resources. The ILP formulation models the limits exactly, at the cost of one binary variable per operation and step.
When to use it
Use SDC scheduling when the schedule must meet many timing rules at once: a clock period with chaining, minimum and maximum distances to interface signals, latency bounds. Use it when a global linear objective matters. It is the scheduler of xPilot and of the LegUp system. When resource limits are tight and the latency matters most, check its result against a list scheduler or an exact model on small blocks.
Pitfalls
- Not exact under resource limits. Do not call the schedule optimal when line L7 added rows. The rows depend on the order, and a different order can give a shorter schedule.
- Separation of combinational operations. If line L7 used the latency as the separation, two combinational operations of one limited type, with , could still share a step, and a step could hold more than of them. Use .
- A full tie-break. If the order of line L6 breaks ties by something other than a topological order, it can put before its predecessor when both have the same ALAP and ASAP, and then the rows of L7 and the data edge form a positive cycle.
- Bounded LP. Negative weights need upper bounds on the starts, or the LP is unbounded.
- Floating point. An LP solver in floating point can return a vertex such as 2.9999999. Round only after checking the result against .
- Delays on the edges. Chaining rows must use the largest delay over all combinational paths between two operations, not the delay of one path.
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/sdc-scheduling/. The authors are listed in prov/11PCP9.jsonl.
"""SDC-based scheduling (Cong and Zhang) for one data flow graph.
Operations are 0 .. n-1. Operation v has a latency lat[v] >= 0 in cycles and
a combinational delay dly[v]. An operation with lat[v] == 0 is
combinational: it may share a step with its predecessors (chaining), and
dly[v] must be at most the clock period. An operation with lat[v] >= 1
registers its result, so it breaks combinational paths. It keeps its unit
busy for occ(v) = max(1, lat[v]) steps, from s[v] to s[v] + occ(v) - 1.
Every constraint is a difference constraint s[v] - s[u] >= w, kept as the
triple (u, v, w). All arithmetic is exact (int and Fraction).
"""
from fractions import Fraction
from typing import Optional
Constraint = tuple[int, int, int]
def occ(lat: list[int], v: int) -> int:
return max(1, lat[v])
def topological_order(n: int, edges: list[tuple[int, int]]) -> list[int]:
succ: list[list[int]] = [[] for _ in range(n)]
indeg = [0] * n
for (u, v) in edges:
succ[u].append(v)
indeg[v] += 1
order: list[int] = []
ready = sorted(v for v in range(n) if indeg[v] == 0)
while ready:
u = ready.pop(0)
order.append(u)
for v in succ[u]:
indeg[v] -= 1
if indeg[v] == 0:
ready.append(v)
ready.sort()
if len(order) != n:
raise ValueError("the data flow graph has a cycle")
return order
def chain_delays(n: int, edges: list[tuple[int, int]], lat: list[int], dly: list) -> dict:
"""D[(u, v)] = the largest delay of a path from u to v through latency-0 operations only."""
order = topological_order(n, edges)
succ: list[list[int]] = [[] for _ in range(n)]
for (u, v) in edges:
succ[u].append(v)
D: dict = {}
for u in order:
if lat[u] != 0:
continue
best = {u: dly[u]}
for x in order:
if x in best:
for y in succ[x]:
if lat[y] == 0 and best[x] + dly[y] > best.get(y, -1):
best[y] = best[x] + dly[y]
for v, d in best.items():
D[(u, v)] = d
return D
def ceil_div(a, b) -> int:
q = Fraction(a) / Fraction(b)
return -((-q.numerator) // q.denominator)
def least_solution(n: int, cons: list[Constraint]) -> Optional[list[int]]:
"""Least s >= 0 with s[v] - s[u] >= w for all (u, v, w), or None (a positive cycle)."""
s = [0] * n
for _ in range(n + 1):
changed = False
for (u, v, w) in cons:
if s[u] + w > s[v]:
s[v] = s[u] + w
changed = True
if not changed:
return s
return None
def build_constraints(n, edges, lat, dly, kind, limits, period, latency_bound=None, extra=()):
"""Return (constraints, upper) where upper[v] bounds s[v] from above, or None."""
for v in range(n):
if lat[v] == 0 and dly[v] > period:
raise ValueError("a combinational operation is slower than the clock period")
cons: list[Constraint] = []
for (u, v) in edges: # @line L2
cons.append((u, v, lat[u]))
for (u, v), d in sorted(chain_delays(n, edges, lat, dly).items()): # @line L3
k = ceil_div(d, period) - 1
if u != v and k >= 1:
cons.append((u, v, k))
cons.extend(extra)
asap = least_solution(n, cons) # @line L4
if asap is None:
return None, None
span = max(asap[v] + occ(lat, v) for v in range(n)) if n else 0
alap = [span - occ(lat, v) for v in range(n)]
for _ in range(n + 1):
for (u, v, w) in cons:
alap[u] = min(alap[u], alap[v] - w)
topo = {v: i for i, v in enumerate(topological_order(n, edges))}
for k in sorted(limits): # @line L5
o = sorted((v for v in range(n) if kind[v] == k), key=lambda v: (alap[v], asap[v], topo[v])) # @line L6
c = limits[k]
for i in range(len(o) - c): # @line L7
cons.append((o[i], o[i + c], occ(lat, o[i])))
upper = None
if latency_bound is not None: # @line L8
upper = [latency_bound - occ(lat, v) for v in range(n)]
return cons, upper
def lp_max(c: list, A: list[list], b: list):
"""Maximize c.x subject to A x <= b and x >= 0, by the simplex method with Bland's rule.
Returns (value, x) with exact fractions, None if infeasible. Raises ValueError if unbounded.
"""
m, n = len(A), len(c)
F = Fraction
N = list(range(n))
B = list(range(n, n + m))
T = [[F(a) for a in row] for row in A]
rhs = [F(x) for x in b]
obj = [F(0)] * n
val = F(0)
def pivot(l, e):
nonlocal val, m
piv = T[l][e]
rhs[l] /= piv
for j in range(len(N)):
if j != e:
T[l][j] /= piv
T[l][e] = 1 / piv
for i in range(m):
if i != l and T[i][e] != 0:
coef = T[i][e]
rhs[i] -= coef * rhs[l]
for j in range(len(N)):
if j != e:
T[i][j] -= coef * T[l][j]
T[i][e] = -coef * T[l][e]
val += obj[e] * rhs[l]
ce = obj[e]
for j in range(len(N)):
if j != e:
obj[j] -= ce * T[l][j]
obj[e] = -ce * T[l][e]
B[l], N[e] = N[e], B[l]
def run():
while True:
cand = [j for j in range(len(N)) if obj[j] > 0]
if not cand:
return
e = min(cand, key=lambda j: N[j])
rows = [i for i in range(m) if T[i][e] > 0]
if not rows:
raise ValueError("the LP is unbounded")
l = min(rows, key=lambda i: (rhs[i] / T[i][e], B[i]))
pivot(l, e)
if m and min(rhs) < 0:
aux = n + m
N.append(aux)
for row in T:
row.append(F(-1))
obj = [F(0)] * n + [F(-1)]
l = min(range(m), key=lambda i: (rhs[i], B[i]))
pivot(l, len(N) - 1)
run()
if val < 0:
return None
if aux in B:
l = B.index(aux)
nz = [j for j in range(len(N)) if T[l][j] != 0 and N[j] != aux]
if nz:
pivot(l, nz[0])
else:
del T[l], rhs[l], B[l]
m -= 1
e = N.index(aux)
N.pop(e)
for row in T:
row.pop(e)
obj = [F(0)] * len(N)
val = F(0)
for x in range(n):
if x in N:
obj[N.index(x)] += c[x]
else:
i = B.index(x)
val += c[x] * rhs[i]
for j in range(len(N)):
obj[j] -= c[x] * T[i][j]
else:
obj = [F(x) for x in c]
run()
x = [F(0)] * n
for i, var in enumerate(B):
if var < n:
x[var] = rhs[i]
return val, x
def sdc_schedule(n, edges, lat, dly, kind, limits, period, latency_bound=None, weights=None, extra=()):
"""Schedule by the SDC method. Returns a list of start steps, or None when the system is infeasible.
weights[v] is the cost per step of s[v] (default 1, which gives ASAP-like schedules).
With nonnegative weights the least solution is returned. Otherwise an LP is solved,
which needs latency_bound so that the LP is bounded.
"""
cons, upper = build_constraints(n, edges, lat, dly, kind, limits, period, latency_bound, extra) # @line L1
if cons is None:
return None
w = [1] * n if weights is None else list(weights)
least = least_solution(n, cons) # @line L9
if least is None or (upper is not None and any(least[v] > upper[v] for v in range(n))):
return None
if all(x >= 0 for x in w): # @line L10
return least
if upper is None:
raise ValueError("negative weights need a latency bound")
A, b = [], [] # @line L11
for (u, v, c) in cons:
row = [0] * n
row[u] += 1
row[v] -= 1
A.append(row)
b.append(-c)
for v in range(n):
row = [0] * n
row[v] = 1
A.append(row)
b.append(upper[v])
res = lp_max([-x for x in w], A, b)
if res is None:
return None
_, x = res
if any(xi.denominator != 1 for xi in x):
raise AssertionError("a vertex of a totally unimodular system was not integral")
return [int(xi) for xi in x]
def latency(lat: list[int], s: list[int]) -> int:
return max((s[v] + occ(lat, v) for v in range(len(s))), default=0)
def is_valid(n, edges, lat, dly, kind, limits, period, s, latency_bound=None) -> bool:
"""Check a schedule directly against the model, without difference constraints."""
if any(x < 0 for x in s):
return False
if any(s[v] < s[u] + lat[u] for (u, v) in edges):
return False
if latency_bound is not None and latency(lat, s) > latency_bound:
return False
order = topological_order(n, edges)
arrive = [0] * n
for v in order:
if lat[v] == 0:
arrive[v] = dly[v] + max([arrive[u] for (u, x) in edges if x == v and lat[u] == 0 and s[u] == s[v]],
default=0)
if arrive[v] > period:
return False
for k, c in limits.items():
busy: dict = {}
for v in range(n):
if kind[v] == k:
for j in range(s[v], s[v] + occ(lat, v)):
busy[j] = busy.get(j, 0) + 1
if any(x > c for x in busy.values()):
return False
return True
test_sdc_scheduling.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sdc-scheduling/. The authors are listed in prov/11PCP9.jsonl.
import itertools
import random
from fractions import Fraction
from sdc_scheduling import (build_constraints, is_valid, latency, least_solution, lp_max, occ, sdc_schedule)
def random_instance(rng: random.Random, max_n: int):
n = rng.randint(2, max_n)
edges = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.35]
lat = [rng.choice([0, 0, 1, 2]) for _ in range(n)]
dly = [rng.randint(1, 3) for _ in range(n)]
kind = [rng.choice("ab") for _ in range(n)]
limits = {k: rng.randint(1, 2) for k in "ab" if rng.random() < 0.7}
return n, edges, lat, dly, kind, limits, 4
def satisfies(cons, upper, s):
return all(s[v] - s[u] >= w for (u, v, w) in cons) and all(s[v] <= upper[v] for v in range(len(s)))
def box(n, cons, upper):
low = least_solution(n, cons)
if low is None or any(low[v] > upper[v] for v in range(n)):
return []
return [p for p in itertools.product(*[range(low[v], upper[v] + 1) for v in range(n)]) if satisfies(cons, upper, p)]
def test_example_of_the_page():
# v0 = a + b, v1 = v0 + c, v2 = v1 + d, v3 = v0 * e, v4 = f * g, v5 = v3 + v4
n, edges = 6, [(0, 1), (1, 2), (0, 3), (3, 5), (4, 5)]
lat, dly = [0, 0, 0, 2, 2, 0], [2, 2, 2, 0, 0, 2]
kind = ["add", "add", "add", "mul", "mul", "add"]
assert sdc_schedule(n, edges, lat, dly, kind, {}, 5) == [0, 0, 1, 0, 0, 2]
s = sdc_schedule(n, edges, lat, dly, kind, {"mul": 1}, 5)
assert s == [0, 0, 1, 0, 2, 4] and latency(lat, s) == 5
assert is_valid(n, edges, lat, dly, kind, {"mul": 1}, 5, s)
# ALAP-like schedule within 5 steps: maximize the sum of the starts.
t = sdc_schedule(n, edges, lat, dly, kind, {"mul": 1}, 5, latency_bound=5, weights=[-1] * n)
assert t == [0, 4, 4, 0, 2, 4]
def test_simplex_small_lp():
# maximize 3x + 2y with x + y <= 4, x + 3y <= 6, x <= 3: optimum 11 at (3, 1)
val, x = lp_max([3, 2], [[1, 1], [1, 3], [1, 0]], [4, 6, 3])
assert val == 11 and x == [3, 1]
# infeasible: x >= 2 and x <= 1
assert lp_max([1], [[-1], [1]], [-2, 1]) is None
def test_lp_optimum_is_integral_and_matches_exhaustive_search():
rng = random.Random(11)
checked = 0
for _ in range(120):
n, edges, lat, dly, kind, limits, period = random_instance(rng, 5)
cons, _ = build_constraints(n, edges, lat, dly, kind, limits, period)
bound = latency(lat, least_solution(n, cons)) + rng.randint(0, 2)
cons, upper = build_constraints(n, edges, lat, dly, kind, limits, period, bound)
points = box(n, cons, upper)
assert points
w = [rng.randint(-3, 3) for _ in range(n)]
s = sdc_schedule(n, edges, lat, dly, kind, limits, period, bound, weights=w)
assert s is not None and satisfies(cons, upper, s)
best = min(sum(a * b for a, b in zip(w, p)) for p in points)
assert sum(a * b for a, b in zip(w, s)) == best
checked += 1
assert checked == 120
def test_least_solution_is_below_every_solution():
rng = random.Random(12)
for _ in range(80):
n, edges, lat, dly, kind, limits, period = random_instance(rng, 5)
cons, _ = build_constraints(n, edges, lat, dly, kind, limits, period)
low = least_solution(n, cons)
cons, upper = build_constraints(n, edges, lat, dly, kind, limits, period, latency(lat, low) + 1)
for p in box(n, cons, upper):
assert all(p[v] >= low[v] for v in range(n))
def test_chaining_constraints_are_exact():
rng = random.Random(13)
for _ in range(80):
n, edges, lat, dly, kind, _, period = random_instance(rng, 6)
cons, _ = build_constraints(n, edges, lat, dly, kind, {}, period)
bound = latency(lat, least_solution(n, cons)) + 1
upper = [bound - occ(lat, v) for v in range(n)]
for p in itertools.product(*[range(0, upper[v] + 1) for v in range(n)]):
assert satisfies(cons, upper, p) == is_valid(n, edges, lat, dly, kind, {}, period, list(p))
def exhaustive_latency(n, edges, lat, dly, kind, limits, period, start):
cons, _ = build_constraints(n, edges, lat, dly, kind, {}, period)
low = least_solution(n, cons)
lam = latency(lat, low)
while True:
windows = [range(low[v], lam - occ(lat, v) + 1) for v in range(n)]
for p in itertools.product(*windows):
if is_valid(n, edges, lat, dly, kind, limits, period, list(p)):
return lam
lam += 1
assert lam <= start
def test_resource_chains_are_sound_but_not_always_optimal():
rng = random.Random(14)
gaps = 0
for _ in range(150):
n, edges, lat, dly, kind, limits, period = random_instance(rng, 7)
s = sdc_schedule(n, edges, lat, dly, kind, limits, period)
assert s is not None
assert is_valid(n, edges, lat, dly, kind, limits, period, s)
opt = exhaustive_latency(n, edges, lat, dly, kind, limits, period, latency(lat, s))
assert latency(lat, s) >= opt
gaps += latency(lat, s) > opt
assert gaps < 150
def test_infeasible_timing_constraint():
# s1 - s0 >= 2 from the data edge, and a maximum timing constraint s1 - s0 <= 1.
assert sdc_schedule(2, [(0, 1)], [2, 1], [0, 0], ["m", "m"], {}, 5, extra=[(1, 0, -1)]) is None
def test_latency_bound_too_small():
assert sdc_schedule(3, [(0, 1), (1, 2)], [1, 1, 1], [0, 0, 0], "aaa", {}, 5, latency_bound=2) is None
def test_fraction_period():
s = sdc_schedule(3, [(0, 1), (1, 2)], [0, 0, 0], [Fraction(3, 2)] * 3, "aaa", {}, Fraction(3))
assert s == [0, 0, 1]
History
Hwang, Lee and Hsu (1991) had written HLS scheduling as a 0-1 integer program with one variable per operation and step. Cong and Zhang (2006) noticed that most scheduling rules are differences of start times, so one integer variable per operation and an LP suffice when the resource rule is relaxed into an order. They used it in the xPilot system at UCLA, with chaining, timing constraints and several objectives in one model. Zhang and Liu (2013) extended it to loop pipelining. The LegUp system at the University of Toronto also uses SDC scheduling.
References
- Jason Cong and Zhiru Zhang, An efficient and versatile scheduling algorithm based on SDC formulation, Proceedings of the 43rd Design Automation Conference, 433 to 438, 2006, the dependence, cycle time, timing, latency and resource constraints of Section 3, the objectives of Section 3.4, and the network flow dual of Section 3.5
- Cheng-Tsung Hwang, Jiahn-Humg Lee and Yu-Chin Hsu, A formal approach to the scheduling problem in high level synthesis, IEEE Transactions on Computer-Aided Design 10(4), 464 to 475, 1991, the 0-1 model that SDC scheduling replaces by one integer variable per operation
- Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein, Introduction to Algorithms, fourth edition, MIT Press, 2022, Section 22.4, Difference constraints and shortest paths
Where this leads
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 11PCP9 Edit this page History Report an error Markdown