Algorithmresearch
SDC-based modulo scheduling
Also called Zhang-Liu modulo scheduling.
Zhang and Liu's loop pipelining scheduler that adds modulo resource constraints to an SDC formulation and repairs conflicts incrementally for a target initiation interval.
- Time
- O(I P V^2 (V + E)) worst
- Space
- O(V + E) extra
- Where
- E = the number of dependence edges; I = the number of initiation intervals tried; P = the largest initiation interval tried; V = the number of operations
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Zhiru Zhang, Bin Liu, 2013
SDC-based modulo scheduling pipelines a loop in high-level synthesis: it schedules one iteration of the loop body so that a new iteration can start every cycles, the initiation interval, while the earlier iterations are still running. It combines two older ideas. From compilers it takes the modulo reservation table of iterative modulo scheduling: with a new iteration every cycles, an operation that starts at step uses its unit in slot in the steady state, so each slot may hold at most as many operations of a type as there are units. From SDC scheduling it takes the system of difference constraints, which now also holds the dependences that cross iterations, as rows . Zhang and Liu (2013) place the operations that use limited units one at a time and keep the system feasible after each choice. If an operation finds no free slot, the scheduler raises and starts again. The result always meets all rules, and it is not always the least .
In plain words
A loop that runs a million times should not wait for one pass to end before the next one starts. If a new pass starts every two clock ticks, the hardware works on several passes at once, like an assembly line. Two things limit how close the passes can be. A value that one pass hands to the next one, such as a running sum, must be ready in time. And if there is one multiplier, every pass gets it only once per two ticks, so its multiplies must fall on ticks with different remainders. The scheduler writes the first kind of rule as simple differences, places the multiplies one by one into free remainder slots, and checks after each step that all rules can still hold.
The problem
The input is a loop body: operations with a latency and a type , and dependence edges with a distance in iterations. Edges with distance 0 form a graph with no cycle. Units of a limited type number and are pipelined: each accepts a new operation every cycle. A modulo schedule for gives starts with
- for each edge, since iteration starts cycles after iteration ;
- for each limited type and each residue , at most operations of type have .
The goal is the least that admits a modulo schedule, and then a short schedule for it. Two lower bounds hold (Rau, 1994):
where is the number of operations of type and the sums run over the edges of the cycle and their tails . This page does not treat the hardness of the exact problem; it solves it only by exhaustive search on small loops.
The algorithm
SDC-MODULO-SCHEDULE(V, E, ℓ, k, a)- 1
II ← max(ResMII, RecMII) - 2
loop - 3
C ← { s_v − s_u ≥ ℓ(u) − II · dist(u, v) : (u, v) ∈ E } - 4
s ← the least solution of C with s ≥ 0 - 5
MRT ← an empty table with II slots per limited type - 6
Q ← the operations of limited types, sorted by (s_v, v) - 7
for each v in Q do - 8
for t ← lo(v) to lo(v) + II − 1, where lo(v) is the least start of v that C allows now, do - 9
if MRT has no free unit of type k(v) in slot t mod II then try the next t - 10
if C with s_v = t added has a solution then - 11
add s_v = t to C; take a unit in slot t mod II; go to the next v - 12
if no t worked then this II fails; leave the for loop - 13
if this II failed then II ← II + 1 and go back to L3 - 14
else return II and the least solution of C
Each test on line L10 is a longest path run, as on the SDC scheduling page: a fixed start is a lower bound and an upper bound on one variable, and the system is feasible exactly when the least solution exists and meets every upper bound. This is a simplified form of Zhang and Liu's Algorithm 1. Their scheduler goes step by step, orders the operations by how many other operations a choice perturbs, and updates the SDC solution incrementally after each change instead of solving it again. The form here orders by the least start and tries one full period of starts.
Example
Take the accumulator loop acc = acc * c + x[i] * y[i] with one pipelined multiplier: and with latency 2, and with latency 1. The edges are and with distance 0, and with distance 1, since the next iteration multiplies the new sum. So and .
At the rows are , and , so exactly. The least solution is , so line L6 orders before . Line L11 fixes at 0, in slot 0, which forces . For , start 0 has a full slot, and starts 1 and 2 would need . So fails. At , goes to 0, to 1, and to 3, a valid schedule.
The least is 3: the schedule , , uses slots 1 and 0 and meets . The greedy order fixed at its earliest start, which left no room for before it. Zhang and Liu's perturbation order and Canis, Brown and Anderson's backtracking aim at exactly this kind of loss.
Correctness
What is proved, in the full proof:
- Lower bounds. Every modulo schedule has , by counting residues, and , by adding the rows around a cycle. For the rows of L3 have no positive cycle, so line L4 always succeeds.
- Valid output. After each fixing step, the rows of with the fixed starts still have a solution, and the table never holds more than operations of type in a slot. The returned schedule meets every edge and every slot limit.
- Full period of candidates. The starts of that keep feasible form an interval of integers that begins at . So lines L8 to L11 try one start of every residue that the interval offers, and an operation fails only if no feasible start has a free slot.
What is not proved, and is false: that the returned is the least. The example loses one cycle. In a measured run of the tests, with 150 random loops of at most 5 operations, one unit per limited type and up to two recurrence edges, the scheduler returned an above the exhaustive optimum on 2 of them. On all 150 the exhaustive optimum equalled . These are measurements on small random loops, not bounds. The proof also does not show that the outer loop always ends with a schedule; the implementation stops at a cap on , and it never reached the cap in the tests.
Proof: Correctness of SDC-based modulo schedulingfull
We use the notation of the page. A loop body has operations with latency and type , and edges with distance . Every cycle of edges has a total distance of at least 1. A limited type has pipelined units. For an integer , a modulo schedule is a vector with
- (D) for each edge ;
- (M) for each limited type and each , at most operations of type have .
Let be the rows (D). A fixing step adds the two rows and . All rows are difference constraints or bounds on one variable, as on the SDC scheduling page.
Facts used from SDC scheduling
The proof of the SDC page gives these facts for a finite system of rows with integer , lower bounds and upper bounds , all integers.
- (F1) has a real solution exactly when it has an integer solution, since its matrix is totally unimodular and its data are integers.
- (F2) If has a solution, it has a least one, componentwise, and it is integral. The longest path computation from the lower bounds finds it, and is feasible exactly when that computation ends with no positive cycle and the result meets every upper bound. This is the test that
least_solutionmakes.
Lemma 1 (lower bounds)
Every modulo schedule for has and .
Proof. Fix a limited type with operations. By (M), each of the residues holds at most of them, and every operation has one residue, so , which gives . Now fix a cycle of edges. Add the rows (D) of its edges. Each start appears once with a plus sign and once with a minus sign, so the left sides add to 0, and
The total distance is at least 1, so , and as is an integer, .
Lemma 2 (the rows of L3 are feasible)
If , then with has a solution, so line L4 succeeds. If , then has none.
Proof. Read as a graph with an arc of weight . A cycle has weight , which is at most 0 exactly when . So all cycles have weight at most 0 exactly when . With no positive cycle, the longest path from a source joined to every node with weight 0 gives a solution with . With a positive cycle, the sum argument of Lemma 1 shows that no solution exists.
So the least with no positive cycle, which the implementation finds by trying , is . Since a cycle weight only falls when grows, a binary search also works.
Lemma 3 (the feasible starts of one operation form an interval)
Let be a feasible system of the form in (F2), and let be an operation. Let . Then is a set of consecutive integers, and its least element is , the value of in the least solution of .
Proof. The real solutions of form a convex set . Its image under is a convex subset of , an interval . Take an integer . Then with the two rows and has a real solution, and these rows are bounds of the form in (F1), so it has an integer solution. Hence , a set of consecutive integers. Let be the least solution of . Then , and every solution has , so no is in .
Theorem 1 (the candidates of L8 cover every residue that can work)
When line L7 handles with the current system , write . If some has a free unit of type in slot , then line L8 reaches such a and line L11 fixes .
Proof. Let have a free slot. By Lemma 3, is a set of consecutive integers that starts at , so it holds every integer from to . Let . Then , so , and , so has the same free slot. Also , so line L8 tries unless an earlier candidate is fixed first. Each candidate that L8 tries passes L9 only with a free slot, and passes L10 exactly when it lies in , by (F2). So the scan fixes the first candidate in that is in and has a free slot, and is such a candidate.
So an operation fails on line L12 only when no feasible start of it, under the earlier choices, has a free slot. The failure comes from the earlier choices, not from a missed candidate.
Theorem 2 (valid output)
If the algorithm returns , then is a modulo schedule for .
Proof. We keep this invariant: the current system , which is with and the rows added on line L11, is feasible, and the table holds, for each limited type and residue , the number of fixed operations of type with residue , which is at most .
At the start, is feasible by Lemma 2, since on line L1 and only grows, and the table is empty. On line L11, the system with added was found feasible on line L10, and the slot of had fewer than entries on line L9, so after one more entry it holds at most . Every limited operation is fixed once, since line L6 lists each of them once.
On line L14 every limited operation is fixed, and is feasible, so its least solution exists by (F2). It meets (D), since , and . Each limited has equal to its fixed value , so the operations of type with residue are exactly the fixed ones that the table counts, and (M) holds. Operations of unlimited types have no slot limit.
Theorem 3 (the exact search)
For fixed , the function exact_schedule returns a modulo schedule exactly when one exists.
Proof. Each is written in one way as with and . Condition (M) depends only on , and _residues lists exactly the vectors that meet (M), since it skips a value of only when its slot is already full. For fixed , a row of (D) with weight reads , that is, . As is an integer, this holds exactly when . These rows are difference constraints with integer weights, and with they have an integer solution exactly when the longest path computation succeeds, by (F2). So for each the search finds a exactly when some schedule has residues , and it returns , which meets (D) and (M). If it finds none for every , no schedule exists.
Then exact_min_ii returns the least in its range with a schedule, since it tries upward from , and Lemma 1 shows that no smaller has one.
What is not claimed
- The heuristic is not always the least. The accumulator example on the page returns 4 where 3 is possible.
- We do not prove that the outer loop ends with a schedule for some . The implementation stops at a cap and returns
None. In the tests it never reached the cap. - The measured counts on the page, 2 losses in 150 random loops and the optimum at on all 150, are observations on small loops, not bounds.
- The order of line L6 and the scan of line L8 are a simplified form of Zhang and Liu's method. The theorems above concern this form.
Complexity
RecMII comes from at most longest path runs, or from a binary search over , since a positive cycle at some stays positive at every smaller . For one , line L10 runs at most times for each of at most operations, and each run is Bellman-Ford in time. So one costs , and values of , each at most , cost . Space is for the rows and the table, plus slots per limited type. An incremental longest path update, as Zhang and Liu use, lowers the cost of each test on line L10 in practice.
Properties
- Always valid. The schedule meets every dependence across iterations and every slot limit.
- Not exact. The may exceed the least one.
- Global timing view. Unlike a list scheduler with a reservation table, every fixing step keeps the whole system of timing rules feasible, so a choice never silently breaks a recurrence that is placed later.
- Extensible. Any rule that is a difference of starts, such as the cross-iteration chaining rows of Zhang and Liu, joins without a change to the method.
- Deterministic. The order of line L6 and the scan of line L8 are fixed.
Variants and improvements
- Perturbation order. Zhang and Liu order the operations by the number of other operations whose least start a choice moves, with ties broken by ALAP and ASAP starts.
- Backtracking. Canis, Brown and Anderson (2014) let a blocked operation evict a placed one, as Rau's iterative modulo scheduler does, with a budget on the number of steps before grows. They also rewrite associative recurrences to shorten them before scheduling.
- Chaining across iterations. With a clock period, a combinational path may cross from one iteration into the next. The pair rule of SDC scheduling then compares with , which is still a difference of two starts.
- Register pressure. After the slots are fixed, an LP over the same rows can minimize a weighted sum of value lifetimes. The matrix keeps the form of the SDC page, so the LP has an integral optimum.
- Exact search. For small loops, the residues of the limited operations can be enumerated. For fixed residues , writing turns the rows into difference constraints on the integers , so feasibility is one longest path run. The tests use this as the reference.
- Non-pipelined units. A unit busy for cycles takes consecutive slots modulo in the table.
When to use it
Use it to pipeline inner loops in HLS when the throughput target is a small and the body has many timing rules, such as a clock period with chaining or fixed interface delays. When the body is small, an exact search or an integer program gives the least . For signal processing graphs with no control flow, retiming and folding give the classic alternative.
Pitfalls
- Not exact. Do not report the returned as the least one, unless it equals .
- Distance 0 cycles. A cycle of edges with distance 0 has no schedule for any . Check the input before computing RecMII.
- Residues of negative starts. If starts may be negative, use a residue in , not the remainder that some languages give for negative numbers.
- Prologue and epilogue. The schedule of one iteration is not the whole design. The controller must also run the first and last iterations, where the pipeline fills and drains.
- Memory ports. Loads and stores to one memory bank compete for its ports exactly like units. Leaving them out of the table gives schedules that the memory cannot serve.
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-modulo-scheduling/. The authors are listed in prov/6XQDH6.jsonl.
"""SDC-based modulo scheduling of one loop body, in a simplified form.
Operations are 0 .. n-1 with a latency lat[v] >= 0 and a type kind[v].
An edge (u, v, dist) says that v in iteration i + dist uses the result of
u in iteration i: s[v] + II * dist >= s[u] + lat[u]. Edges with dist == 0
must form a graph with no cycle. Units are pipelined: an operation of type
k that starts at step t uses one unit of type k in the slot t mod II of the
modulo reservation table, and limits[k] units exist in each slot.
Every timing rule is a difference constraint s[v] - s[u] >= w, kept as
(u, v, w). A fixed start is a lower and an upper bound on one variable.
"""
from typing import Optional
def least_solution(n: int, cons, low: list[int], high: list[Optional[int]]) -> Optional[list[int]]:
"""Least s >= low with every row, if it also meets s <= high; else None."""
s = list(low)
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:
break
else:
return None
if any(h is not None and s[v] > h for v, h in enumerate(high)):
return None
return s
def dependence_rows(edges, lat: list[int], ii: int):
return [(u, v, lat[u] - ii * dist) for (u, v, dist) in edges]
def res_mii(kind: list, limits: dict) -> int:
count: dict = {}
for k in kind:
count[k] = count.get(k, 0) + 1
return max([1] + [-(-count[k] // c) for k, c in limits.items() if k in count])
def rec_mii(n: int, edges, lat: list[int]) -> int:
"""The least II >= 1 for which the dependence rows have no positive cycle."""
bound = 1 + sum(lat)
for ii in range(1, bound + 1):
if least_solution(n, dependence_rows(edges, lat, ii), [0] * n, [None] * n) is not None:
return ii
raise ValueError("a cycle of edges with distance 0")
def sdc_modulo_schedule(n, edges, lat, kind, limits, max_ii=None):
"""Return (II, starts) for the least II this heuristic reaches."""
ii = max(res_mii(kind, limits), rec_mii(n, edges, lat)) # @line L1
cap = max_ii if max_ii is not None else ii + n * (1 + max(lat, default=0)) + n
while ii <= cap: # @line L2
s = try_ii(n, edges, lat, kind, limits, ii)
if s is not None:
return ii, s
ii += 1 # @line L13
return None
def try_ii(n, edges, lat, kind, limits, ii) -> Optional[list[int]]:
cons = dependence_rows(edges, lat, ii) # @line L3
low, high = [0] * n, [None] * n
asap = least_solution(n, cons, low, high) # @line L4
if asap is None:
return None
mrt: dict = {} # @line L5
todo = sorted((v for v in range(n) if kind[v] in limits), key=lambda v: (asap[v], v)) # @line L6
for v in todo: # @line L7
cur = least_solution(n, cons, low, high)
placed = False
for t in range(cur[v], cur[v] + ii): # @line L8
slot = (kind[v], t % ii)
if mrt.get(slot, 0) >= limits[kind[v]]: # @line L9
continue
low2, high2 = list(low), list(high)
low2[v], high2[v] = t, t
if least_solution(n, cons, low2, high2) is not None: # @line L10
low, high = low2, high2
mrt[slot] = mrt.get(slot, 0) + 1 # @line L11
placed = True
break
if not placed:
return None # @line L12
return least_solution(n, cons, low, high) # @line L14
def is_valid(n, edges, lat, kind, limits, ii, s) -> bool:
if len(s) != n or any(x < 0 for x in s):
return False
if any(s[v] + ii * dist < s[u] + lat[u] for (u, v, dist) in edges):
return False
use: dict = {}
for v in range(n):
if kind[v] in limits:
key = (kind[v], s[v] % ii)
use[key] = use.get(key, 0) + 1
if use[key] > limits[kind[v]]:
return False
return True
def exact_min_ii(n, edges, lat, kind, limits, max_ii):
"""The least II with a valid modulo schedule, by search over all residues.
For residues r, write s = r + II * q. The rows s[v] - s[u] >= w become
q[v] - q[u] >= ceil((w - r[v] + r[u]) / II), again difference constraints.
"""
lo = max(res_mii(kind, limits), rec_mii(n, edges, lat))
for ii in range(lo, max_ii + 1):
if exact_schedule(n, edges, lat, kind, limits, ii) is not None:
return ii
return None
def exact_schedule(n, edges, lat, kind, limits, ii) -> Optional[list[int]]:
"""A valid modulo schedule for this II, or None, by search over all residue vectors."""
cons = dependence_rows(edges, lat, ii)
for r in _residues(n, kind, limits, ii):
rows = [(u, v, -(-(w - r[v] + r[u]) // ii)) for (u, v, w) in cons]
q = least_solution(n, rows, [0] * n, [None] * n)
if q is not None:
return [r[v] + ii * q[v] for v in range(n)]
return None
def _residues(n, kind, limits, ii):
"""All residue vectors whose limited operations fit the modulo reservation table."""
use: dict = {}
acc: list[int] = []
def rec(v):
if v == n:
yield list(acc)
return
for x in range(ii):
key = (kind[v], x)
if kind[v] in limits and use.get(key, 0) >= limits[kind[v]]:
continue
use[key] = use.get(key, 0) + 1
acc.append(x)
yield from rec(v + 1)
acc.pop()
use[key] -= 1
yield from rec(0)
test_sdc_modulo_scheduling.py 72 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sdc-modulo-scheduling/. The authors are listed in prov/6XQDH6.jsonl.
import itertools
import random
from sdc_modulo_scheduling import (exact_min_ii, exact_schedule, is_valid, rec_mii, res_mii, sdc_modulo_schedule)
# m1 = acc * c, m2 = x[i] * y[i], a = m1 + m2, and acc of the next iteration is a.
ACC = (3, [(0, 2, 0), (1, 2, 0), (2, 0, 1)], [2, 2, 1], ["mul", "mul", "add"], {"mul": 1})
def random_loop(rng: random.Random, max_n: int):
n = rng.randint(2, max_n)
edges = [(u, v, 0) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.35]
for _ in range(rng.randint(1, 2)):
u, v = rng.randrange(n), rng.randrange(n)
if u >= v:
edges.append((u, v, rng.randint(1, 2)))
lat = [rng.randint(0, 2) for _ in range(n)]
kind = [rng.choice("ab") for _ in range(n)]
limits = {k: 1 for k in "ab" if rng.random() < 0.8}
return n, edges, lat, kind, limits
def test_accumulator_example():
n, edges, lat, kind, limits = ACC
assert res_mii(kind, limits) == 2 and rec_mii(n, edges, lat) == 3
ii, s = sdc_modulo_schedule(*ACC)
assert (ii, s) == (4, [0, 1, 3])
assert is_valid(n, edges, lat, kind, limits, ii, s)
assert exact_min_ii(*ACC, 6) == 3
t = exact_schedule(*ACC, 3)
assert is_valid(n, edges, lat, kind, limits, 3, t)
assert is_valid(n, edges, lat, kind, limits, 3, [1, 0, 3])
assert not is_valid(n, edges, lat, kind, limits, 3, [0, 1, 3])
def test_no_resource_limit_reaches_rec_mii():
rng = random.Random(21)
for _ in range(100):
n, edges, lat, kind, _ = random_loop(rng, 7)
ii, s = sdc_modulo_schedule(n, edges, lat, kind, {})
assert ii == rec_mii(n, edges, lat)
assert is_valid(n, edges, lat, kind, {}, ii, s)
def test_heuristic_against_exhaustive_search():
rng = random.Random(22)
worse = 0
for _ in range(150):
n, edges, lat, kind, limits = random_loop(rng, 5)
ii, s = sdc_modulo_schedule(n, edges, lat, kind, limits)
assert is_valid(n, edges, lat, kind, limits, ii, s)
best = exact_min_ii(n, edges, lat, kind, limits, ii)
assert max(res_mii(kind, limits), rec_mii(n, edges, lat)) <= best <= ii
worse += ii > best
assert worse < 150
def test_exact_search_against_bounded_enumeration():
rng = random.Random(23)
for _ in range(40):
n, edges, lat, kind, limits = random_loop(rng, 4)
ii = max(res_mii(kind, limits), rec_mii(n, edges, lat))
found = exact_schedule(n, edges, lat, kind, limits, ii)
horizon = 2 * ii + sum(lat) + 1
brute = any(is_valid(n, edges, lat, kind, limits, ii, list(p))
for p in itertools.product(range(horizon), repeat=n))
assert (found is not None) == brute
if found is not None:
assert is_valid(n, edges, lat, kind, limits, ii, found)
History
Rau (1994) gave iterative modulo scheduling for compilers, with the modulo reservation table, the bounds ResMII and RecMII, and an outer loop over . Cong and Zhang (2006) had shown that most HLS scheduling rules fit a system of difference constraints. Zhang and Liu (2013) combined the two for pipeline synthesis, with rules that cross iterations and an incremental repair when a slot is full. Canis, Brown and Anderson (2014) added backtracking in the LegUp system.
References
- Zhiru Zhang and Bin Liu, SDC-based modulo scheduling for pipeline synthesis, Proceedings of the IEEE/ACM International Conference on Computer-Aided Design, 211 to 218, 2013, the dependence and timing constraints across iterations, the modulo reservation table, the incremental scheduling of Algorithm 1 and the accumulator example
- Andrew Canis, Stephen D. Brown and Jason H. Anderson, Modulo SDC scheduling with recurrence minimization in high-level synthesis, Proceedings of the International Conference on Field Programmable Logic and Applications, 1 to 8, 2014, the backtracking modulo SDC scheduler and the restructuring of recurrences in LegUp
- B. Ramakrishna Rau, Iterative modulo scheduling, an algorithm for software pipelining loops, Proceedings of the 27th International Symposium on Microarchitecture, 63 to 74, 1994, the modulo reservation table, ResMII, RecMII and the iterative search over initiation intervals
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 6XQDH6 Edit this page History Report an error Markdown