Algorithmadvanced
Iterative modulo scheduling
Also called Rau modulo scheduling.
Software pipelines a loop by trying initiation intervals from a lower bound up, placing operations in a modulo reservation table with backtracking.
- Solves
- Instruction scheduling
- Time
- O(n^3 log D + I (n e + B n (n + e + P w))) worst
- Space
- O(n^2 + e + n w) extra
- Where
- B = the budget ratio; D = the sum of the positive delays; I = the number of values of II tried; P = the largest II tried; e = the number of dependence edges; n = the number of operations; w = the length of the longest reservation table
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- B. Ramakrishna Rau, 1994
Iterative modulo scheduling is an algorithm for the central step of software pipelining: it chooses a start time for each operation of a loop body so that a new iteration can start every cycles. Software pipelining is the general technique, with its prologue, kernel, epilogue and register renaming. This page is only about the choice of and , as Rau (1994) gave it. It starts at the lower bound and tries each in turn. For one , it places the operations one at a time, by priority, into a modulo reservation table with rows. When an operation finds no free row in its window, it takes a slot anyway and pushes out the operations that are in the way. These are placed again later, and a budget limits the number of steps. The result is always legal. It is not always the least , but on most loops it is equal to MII.
In plain words
Picture a loop that starts a new pass every few clock ticks. Each pass must do the same steps at the same offsets, so every step has a fixed seat in a short repeating table, one row per tick. Two steps that need the same unit cannot sit in the same row. The method seats the most urgent steps first. If a step finds every seat it could take already full, it sits down anyway and makes the others stand up and look for new seats. After too many moves it gives up and tries again with a longer table, which has more seats. The first table length that works gives the speed of the loop.
The problem
The input is a loop body with operations and a machine. Each operation has a reservation table, a list of pairs : in each iteration, uses one unit of resource in cycle . Resource has units. Each dependence edge has a delay and a distance : operation of iteration starts at least cycles after operation of iteration . Edges with distance 0 form no cycle, as described on the loop-carried dependence page.
The output is an and starts that form a legal modulo schedule:
- every edge has ;
- for each resource and each slot , at most table entries of fall in cycles .
Then iteration can start at cycle , and the overlapped run keeps every dependence and every unit limit. The goal is a small . Finding the least one is NP-hard in general, so the algorithm is a heuristic.
The algorithm
ITERATIVE-MODULO-SCHEDULE(G, machine, ratio)- 1
MII <- max(1, ResMII, RecMII) - 2
for II <- MII, MII + 1, ... do - 3
if ITERATIVE-SCHEDULE(II, ratio * n) returns t then return (II, t) ITERATIVE-SCHEDULE(II, budget)- 4
if some operation alone overfills the table then fail; H <- HeightR at II; t, MRT <- empty - 5
while some operation is unscheduled and budget > 0 do - 6
v <- the unscheduled operation of greatest H(v), the lowest index on ties - 7
Estart <- max(0, max over scheduled predecessors p of t(p) + delta(p, v) - II * d(p, v)) - 8
s <- the first time in Estart .. Estart + II - 1 at which v fits in the MRT - 9
if there is none then s <- Estart if v was never scheduled or Estart > prev(v), else prev(v) + 1 - 10
unschedule the operations that hold the slots that v needs at s, until v fits - 11
unschedule each scheduled successor w of v with t(w) < s + delta(v, w) - II * d(v, w) - 12
t(v) <- s; prev(v) <- s; put v in the MRT; budget <- budget - 1 - 13
if all operations are scheduled then return t else fail
The bounds (line L1). If the tables hold entries of resource , then . For RecMII, give each edge the weight . A cycle of weight makes impossible, so is the least with no positive cycle, that is . Rau finds it with the MinDist matrix, the all-pairs longest path weights, which Floyd-Warshall computes in . A positive cycle shows up as a positive diagonal entry. The weights only shrink as grows, so a binary search over from 0 to the sum of the positive delays finds RecMII.
Priority (line L4). is the longest weight of a path from , and at least 0. It measures how far the rest of the iteration reaches beyond , counted at this . With no positive cycle, Bellman-Ford rounds reach it. The check before it rejects an at which some operation alone uses one row of the table too often, such as a divide that holds the multiplier at offsets 0 and 2 when .
One step (lines L6 to L12). The earliest start of line L7 uses only the predecessors that are scheduled now. The window of line L8 has times, so it tries every row of the table once. If all rows are full, line L9 forces a time. The rule with makes an operation that comes back to the same move one cycle later each time, so that it does not push out the same operations again and again. Line L10 makes room in the table. Line L11 pushes out the successors whose dependence on the new time breaks. Predecessors cannot break, since .
The budget (line L5). Each step costs one unit, and the budget is ratio times . When it runs out, the attempt fails and line L2 tries . Rau chose the ratio by measurement. The code uses 3.
Example
The loop computes acc = acc * c + x[i] * y[i] and steps i. The machine has one memory unit, one multiplier and one ALU, each pipelined, so each table is one entry at offset 0.
| index | name | operation | resource | edges out (delay, distance) |
|---|---|---|---|---|
| 0 | lx |
x = load x[i] |
mem | to m2 (2, 0), to inc (0, 0) |
| 1 | ly |
y = load y[i] |
mem | to m2 (2, 0), to inc (0, 0) |
| 2 | m1 |
p = acc * c |
mul | to a (2, 0) |
| 3 | m2 |
q = x * y |
mul | to a (2, 0) |
| 4 | a |
acc = p + q |
alu | to m1 (1, 1) |
| 5 | inc |
i = i + 1 |
alu | to lx (1, 1), to ly (1, 1), to itself (1, 1) |
The edges into inc with delay 0 keep the loads before the write of i. Two operations use each resource, so . The cycle m1, a has delay and distance 1, so , and at Floyd-Warshall finds a positive diagonal. So . At the heights are 4 for lx and ly, 2 for m1, m2 and inc, and 0 for a. The budget is steps. The steps are:
| step | op | Estart | first free time in the window | time | pushed out | why |
|---|---|---|---|---|---|---|
| 1 | lx |
0 | 0 | 0 | none | |
| 2 | ly |
0 | 1 | 1 | none | memory row 0 is full |
| 3 | m1 |
0 | 0 | 0 | none | |
| 4 | m2 |
3 | 4 | 4 | none | multiplier row 0 holds m1 |
| 5 | inc |
1 | 1 | 1 | none | |
| 6 | a |
6 | 6 | 6 | m1 |
m1 at 0 breaks |
| 7 | m1 |
4 | 5 | 5 | a |
a at 6 breaks |
| 8 | a |
7 | 8 | 8 | m1 |
m1 at 5 breaks |
| 9 | m1 |
6 | 6 | 6 | none |
Line L11 does all the pushing here: each time a or m1 moves, the recurrence moves the other one. After 9 steps every operation is placed, with , so the result is optimal. The modulo reservation table is:
| row | mem | mul | alu |
|---|---|---|---|
| 0 | lx (0) |
m1 (6) |
|
| 1 | ly (1) |
m2 (4) |
inc (1) |
| 2 | a (8) |
One iteration spans cycles 0 to 8, in three stages of three cycles. For 100 iterations the pipelined loop takes cycles. Without overlap, the best schedule of one iteration takes 6 cycles (lx and m1 at 0, ly and inc at 1, m2 at 3, a at 5), so 600 cycles.
Correctness
Theorem. If ITERATIVE-MODULO-SCHEDULE returns , then is a legal modulo schedule for , and , where is the least of any legal modulo schedule.
The full proof is in the proof file. The lower bound comes from two sums. Each resource has units in each of rows, so . Around a cycle the starts cancel, so the edge constraints add up to . For the schedule, the key invariant of line L5 is that the scheduled operations already form a legal partial schedule: the table rows are within their limits, and every edge between two scheduled operations holds. Line L7 makes the edges from scheduled predecessors hold, line L10 keeps the table rows within limits, and line L11 removes every successor whose edge would break. Self-loops hold at every . So when every operation is scheduled, the schedule is legal. Each attempt stops within its budget.
Proof: MII is a lower bound on the initiation interval, and iterative modulo scheduling returns a legal modulo schedulefull
We prove four things. Every legal modulo schedule has (Theorem 1). Line L1 computes and exactly (Lemmas 2 to 4). Each call of ITERATIVE-SCHEDULE stops, and when it succeeds its result is a legal modulo schedule (Theorem 5). A legal modulo schedule gives a legal overlapped run of any number of iterations (Theorem 6). The search over is a heuristic: we do not claim that the returned is the least one.
Setup
The loop body has operations . Operation has a reservation table , a list of pairs with : in iteration , holds one unit of resource in cycle . Resource has units. An edge has a delay and a distance . The edges of distance 0 form no cycle.
For an integer , a modulo schedule is a map from operations to integers . It is legal if
- (D) for every edge , and
- (R) for every resource and every slot , the number of pairs with and is at most .
Let be the number of entries in all tables. For a cycle of edges, let and be the sums of its delays and distances. Every cycle has , since the edges of distance 0 form no cycle. Define
with the maximum over all cycles , simple or not, and .
Part 1. The lower bound
Theorem 1. If is a legal modulo schedule for , then .
Proof. by definition.
Resources. Fix . By (R), each of the slots holds at most of the entries of , and each entry falls in exactly one slot. So , that is . As is an integer, . This holds for every , so .
Recurrences. Fix a cycle with and . Adding (D) over the edges of gives
The first sum telescopes to . So , and as , , hence . With , this gives .
So the least of any legal modulo schedule, the optimum, is at least MII, and the that the algorithm returns is at least the optimum, once Theorem 5 shows that it is legal.
Part 2. Computing MII
res_mii counts the entries of each resource and returns the largest , which is by definition. For RecMII, give each edge the weight and call a cycle positive if its weight is .
Lemma 2. For , there is no positive cycle at if and only if . In particular, "no positive cycle" holds for all from on, and for no smaller .
Proof. There is no positive cycle iff for every cycle, iff for every cycle (as ), iff for every cycle (as is an integer). With , this is .
Lemma 3. min_dist returns a matrix with some diagonal entry if and only if there is a positive cycle.
Proof. Two invariants of the Floyd-Warshall loop, in the max-plus form of the code.
(a) Every finite entry is the weight of some walk from to with at least one edge. True at the start, where is the weight of the heaviest edge from to . An update sets , the weight of the two walks joined at .
(b) After the round for , for every walk from to with at least one edge whose inner vertices are distinct, are different from and , and are at most . (A walk with is a cycle through .) Before the first round, such a walk has no inner vertex and is one edge, and the claim holds. In the round for , a walk that has as an inner vertex splits at into from to and from to , whose inner vertices are distinct, are at most and do not contain . By the claim for round , and when the update for runs, since entries never decrease. So after the update . A walk without as an inner vertex is covered by round .
If there is a positive cycle, there is a positive simple cycle: a closed walk splits into simple cycles whose weights add up to its weight, so one of them is positive. A simple cycle through its vertex satisfies the condition of (b), so after the last round its weight . Conversely, if , by (a) it is the weight of a closed walk, which splits into simple cycles, one of them positive.
Lemma 4. rec_mii returns .
Proof. Let . At , every cycle has , since and . So by Lemma 2. The binary search keeps the invariant . It holds at the start with . If the test at finds a positive cycle (Lemma 3), then by Lemma 2 and keeps it. Otherwise and keeps it. The interval shrinks in each step, and at the end .
Part 3. One attempt at a fixed II
Fix and a budget . By Lemma 2, there is no positive cycle at . In particular, every self-loop has , so (D) holds for it for every value of . The code leaves self-loops out of the lists preds and succs.
Heights (line L4). height_r runs Bellman-Ford rounds of from . As there is no positive cycle, the values are bounded by the longest simple path weights, and rounds reach the fixed point. The heights only fix the order of line L6. The proof below does not use them, so any order gives a legal result.
The check before line L4. The attempt fails at once if some operation alone does not satisfy (R) at , which is the same as at every start, since a shift of the start shifts all slots of by the same amount modulo . Otherwise every operation fits into an empty table.
The state is the partial map on the scheduled set , the map , and the table , which maps each pair to a list of operations.
Invariant. Before each step of the loop of line L5:
- (I1) lists each once for each entry with , and nothing else;
- (I2) every list has at most items;
- (I3) every edge with and has ;
- (I4) for every .
Theorem 5. Each call of ITERATIVE-SCHEDULE stops after at most steps. If it returns , then is a legal modulo schedule for .
Proof. Initialization. and are empty, so (I1) to (I4) hold.
Unscheduling keeps (I1) to (I4). unschedule(w) removes from and removes exactly its entries from the table, so (I1) holds. Lists only get shorter, and constraints between members of only disappear.
Maintenance. Let be the operation of line L6 and the scheduled set at that moment. Line L7 sets , and every later choice satisfies : line L8 takes , and line L9 takes or , the latter only when . So .
Resources. If line L8 found , then _fits says that every list that needs, with new entries, has at most items, so adding keeps (I2). If line L9 chose , line L10 removes items from each such list while it has more than items. Each removal makes the list shorter, and by the check before line L4, so the loop stops with at most items. Removing an operation never lengthens another list. So after line L10, adding the entries of keeps (I2), and line L12 adds exactly these entries, so (I1) holds.
Dependences. After lines L10 and L11 the scheduled set is . For an edge with , : , so . For an edge with , : line L11 removed every with , so . Edges between two members of held before by (I3). So (I3) holds with , and (I4) holds as .
Termination. Each step decreases the budget by 1, and the loop stops when the budget is 0 or holds all operations. Line L10 stops as shown, and lines L6 to L8 and L11 are finite.
Result. The call returns only when holds all operations. Then (I1) and (I2) give (R), (I3) and the remark on self-loops give (D), and (I4) gives .
Corollary. If modulo_schedule returns , then is a legal modulo schedule for , and for the least of any legal modulo schedule.
Proof. The loop of line L2 starts at MII, computed exactly by Lemma 4, so every attempt has and Theorem 5 applies to the one that returns. Theorem 1 gives , and because is legal. The loop of line L2 is finite, since it stops at max_ii, so modulo_schedule stops: it returns or raises an error.
Part 4. The overlapped run
Theorem 6. Let be a legal modulo schedule for , and run iterations , with operation of iteration starting at cycle . Then for every edge and every with , . And in every cycle , at most units of each resource are in use.
Proof. by (D). For resources, an entry of in iteration uses in cycle , which is congruent to modulo . So all uses of in cycle come from entries in the slot . Two uses in cycle from the same entry would have , so , the same use. So the uses of in cycle are at most the number of entries in slot , which is at most by (R).
Complexity
The model is the word RAM. Let , , , , , and be as in the front matter, with a constant number of units per resource.
- Line L1. ResMII takes . The binary search for RecMII runs Floyd-Warshall times, at each.
- Line L4. The check takes , and the heights take at most rounds over the edges, .
- Lines L6 to L12, per step. Line L6 scans operations, line L7 and line L11 scan edges, and line L8 tests at most times at each. Every operation that lines L10 and L11 remove was placed by an earlier step, so all removals cost per step on average.
- One attempt. At most steps: .
So the run costs time. The space is for MinDist, for the edges and for the table. The Python code computes the tests of line L8 with dictionaries, which keeps these bounds.
Properties
- Always legal. Every returned schedule meets every dependence with its distance and every row limit of the table.
- Not exact. The returned can be larger than the least one: the budget can run out, and the order of line L6 can block a better choice. The least can also be larger than MII.
- Usually optimal in practice. On 150 random loops of at most 5 operations in the tests, the returned equalled the exhaustive optimum on all of them, and the optimum was above MII on 3. In a larger run with 300 loops of up to 6 operations, it equalled the optimum on 298. These are measurements on small random loops, not bounds.
- Deterministic. The order of line L6, the scan of line L8 and the removal order are fixed.
- General resources. A table may use several resources at several offsets, as for a divide that holds a unit for many cycles.
- Blind to registers. It does not look at the lifetimes of values, so it can need many registers.
Variants and improvements
- Lifetime-sensitive scheduling. Huff (1993) places each operation early or late inside its slack to keep values short. Swing modulo scheduling (Llosa et al. 1996) orders the operations by recurrences and places each one next to its scheduled neighbors, without backtracking. It is the pipeliner of GCC.
- No backtracking. Lam (1988) schedules the strongly connected components first and raises when an operation finds no slot.
- Constraint and integer programming. SDC-based modulo scheduling keeps the dependences as a system of difference constraints, and an integer program gives the least for small loops.
- Faster RecMII. The ratio is a minimum cycle ratio problem. With all distances 1 it is a maximum mean cycle, which Karp's algorithm solves in .
When to use it
Use it to pipeline inner loops for VLIW, EPIC and DSP processors, where it is a standard method with a simple implementation and schedules close to MII. Prefer swing modulo scheduling when registers are few, since it keeps lifetimes short. Prefer an integer program for small, hot loops where the least is worth a long compile. In high-level synthesis, SDC-based modulo scheduling handles timing rules that are not plain dependences. For code with branches and no loop, use trace scheduling or superblock scheduling.
Pitfalls
- Missing the successor check. If line L11 is left out, the schedule can break a dependence. In the example, step 6 puts
aat 6 whilem1stays at 0, and then the next iteration multiplies the oldacc. Line L11 must push out every scheduled successor whose edge the new time breaks. - Forcing the same time again. If line L9 always takes Estart, an operation that is pushed out and comes back with the same Estart pushes out the same operations, which then push it out again, until the budget is gone. Take when .
- The wrong earliest start. If line L7 reads the old times of operations that are not scheduled, or leaves out , the start of an operation on a recurrence is too late or too early. Use only the scheduled predecessors, with the weight .
- No check of a single operation. If line L4 does not reject an operation that alone overfills a row, line L10 cannot make room for it, even when it empties the table. Reject that at once.
- Rounding down. If line L1 rounds or down, the first attempts run at an that no schedule can meet. Three loads on two memory ports need , and a cycle with delay 5 and distance 2 needs .
- A window of the wrong size. If line L8 tries fewer than times, it misses free rows. More than times only repeats rows at later times.
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/iterative-modulo-scheduling/. The authors are listed in prov/PJN90C.jsonl.
"""Iterative modulo scheduling (Rau 1994) of the body of a loop.
A loop body is given by
- n: the number of operations, numbered 0 .. n-1;
- res[v]: the reservation table of operation v, a list of pairs
(resource, offset): v holds one unit of the resource in cycle
t(v) + offset of its iteration;
- edges: a list of (u, v, delay, distance): operation v of iteration
i + distance starts at least delay cycles after operation u of
iteration i starts;
- machine: a dict from each resource to its number of units.
A modulo schedule for an initiation interval II gives each operation a
start t(v) >= 0 such that every edge has
t(v) + II * distance >= t(u) + delay, and for each resource r and slot k
in 0 .. II-1, at most machine[r] uses of r fall in cycles congruent to k
modulo II. Iteration i then starts at cycle i * II.
Precondition: offsets >= 0, distances >= 0, every resource of a table is
in machine with at least one unit, and the edges of distance 0 form no
cycle (check_loop raises ValueError otherwise).
modulo_schedule returns (II, t, MII) with MII = max(1, ResMII, RecMII).
The result is always a legal modulo schedule and II >= MII. It is a
heuristic: II may be larger than the least possible one.
Cost: with e edges, D the sum of the positive delays and w the longest
reservation table, RecMII takes O(n^3 log D) by binary search with
Floyd-Warshall. One attempt at a given II takes O(n e) for the heights
and O(budget (n + e + II w)) for the steps, budget = budget_ratio * n.
"""
NEG = float("-inf")
def check_loop(n, res, edges, machine):
if len(res) != n:
raise ValueError("one reservation table per operation")
for v in range(n):
for r, off in res[v]:
if machine.get(r, 0) < 1 or off < 0:
raise ValueError("bad reservation (%r, %r) of operation %d" % (r, off, v))
succ = [[] for _ in range(n)]
indeg = [0] * n
for u, v, delay, dist in edges:
if not (0 <= u < n and 0 <= v < n) or dist < 0:
raise ValueError("bad edge %r" % ((u, v, delay, dist),))
if dist == 0:
succ[u].append(v)
indeg[v] += 1
stack = [v for v in range(n) if indeg[v] == 0]
seen = 0
while stack:
u = stack.pop()
seen += 1
for v in succ[u]:
indeg[v] -= 1
if indeg[v] == 0:
stack.append(v)
if seen != n:
raise ValueError("the edges of distance 0 form a cycle")
def res_mii(n, res, machine):
"""max over resources r of ceil(uses of r / units of r)."""
uses = {}
for v in range(n):
for r, _ in res[v]:
uses[r] = uses.get(r, 0) + 1
return max([-(-u // machine[r]) for r, u in uses.items()], default=0)
def min_dist(n, edges, ii):
"""M[i][j]: the largest sum of delay - ii * distance over the walks from
i to j with at least one edge that Floyd-Warshall builds; -inf if there
is none. Some M[i][i] > 0 exactly when some cycle has a positive sum."""
m = [[NEG] * n for _ in range(n)]
for u, v, delay, dist in edges:
m[u][v] = max(m[u][v], delay - ii * dist)
for k in range(n):
mk = m[k]
for i in range(n):
a = m[i][k]
if a == NEG:
continue
mi = m[i]
for j in range(n):
if a + mk[j] > mi[j]:
mi[j] = a + mk[j]
return m
def has_positive_cycle(n, edges, ii):
m = min_dist(n, edges, ii)
return any(m[i][i] > 0 for i in range(n))
def rec_mii(n, edges):
"""The least II >= 0 such that no cycle has delay(C) > II * distance(C),
that is max(0, max over cycles C of ceil(delay(C) / distance(C)))."""
lo, hi = 0, sum(max(e[2], 0) for e in edges)
while lo < hi:
mid = (lo + hi) // 2
if has_positive_cycle(n, edges, mid):
lo = mid + 1
else:
hi = mid
return lo
def height_r(n, edges, ii):
"""HeightR(v): the longest sum of delay - ii * distance over paths from v,
at least 0. Bellman-Ford rounds; there is no positive cycle."""
h = [0] * n
for _ in range(n):
changed = False
for u, v, delay, dist in edges:
x = h[v] + delay - ii * dist
if x > h[u]:
h[u] = x
changed = True
if not changed:
break
return h
def _slots(v, s, res, ii):
need = {}
for r, off in res[v]:
key = (r, (s + off) % ii)
need[key] = need.get(key, 0) + 1
return need
def _fits(v, s, mrt, res, machine, ii):
return all(len(mrt.get(key, ())) + c <= machine[key[0]] for key, c in _slots(v, s, res, ii).items())
def iterative_schedule(n, res, edges, machine, ii, budget, log=None):
"""One attempt at II. Returns (t, mrt) or None. mrt maps (resource,
slot) to the list of operations that use it, once per use. If log is a
list, each step appends (op, estart, slot, displaced ops)."""
if not all(_fits(v, 0, {}, res, machine, ii) for v in range(n)):
return None
h = height_r(n, edges, ii) # @line L4
preds = [[] for _ in range(n)]
succs = [[] for _ in range(n)]
for u, v, delay, dist in edges:
if u != v:
preds[v].append((u, delay - ii * dist))
succs[u].append((v, delay - ii * dist))
t, prev, mrt = {}, {}, {}
def unschedule(w):
for key, c in _slots(w, t[w], res, ii).items():
for _ in range(c):
mrt[key].remove(w)
del t[w]
while len(t) < n and budget > 0: # @line L5
v = max((w for w in range(n) if w not in t), key=lambda w: (h[w], -w)) # @line L6
estart = max([0] + [t[p] + wt for p, wt in preds[v] if p in t]) # @line L7
s = next((x for x in range(estart, estart + ii) if _fits(v, x, mrt, res, machine, ii)), None) # @line L8
out = []
if s is None:
s = estart if v not in prev or estart > prev[v] else prev[v] + 1 # @line L9
for key, c in _slots(v, s, res, ii).items():
while len(mrt.get(key, ())) + c > machine[key[0]]:
out.append(mrt[key][0])
unschedule(mrt[key][0]) # @line L10
for w, wt in succs[v]:
if w in t and t[w] < s + wt:
out.append(w)
unschedule(w) # @line L11
t[v] = s # @line L12
prev[v] = s
for key, c in _slots(v, s, res, ii).items():
mrt.setdefault(key, []).extend([v] * c)
budget -= 1
if log is not None:
log.append((v, estart, s, out))
if len(t) < n:
return None
return t, mrt # @line L13
def modulo_schedule(n, res, edges, machine, budget_ratio=3, max_ii=None, log=None):
"""Returns (II, t, MII). Tries II = MII, MII + 1, ... up to max_ii and
raises RuntimeError if every attempt runs out of budget."""
check_loop(n, res, edges, machine)
mii = max(1, res_mii(n, res, machine), rec_mii(n, edges)) # @line L1
if max_ii is None:
max_ii = mii + sum(max(e[2], 0) for e in edges) + sum(len(r) for r in res) + n
for ii in range(mii, max_ii + 1): # @line L2
if log is not None:
log.append(("II", ii))
got = iterative_schedule(n, res, edges, machine, ii, budget_ratio * n, log)
if got is not None:
return ii, got[0], mii # @line L3
raise RuntimeError("no schedule up to II = %d" % max_ii)
def stages(t, ii):
"""stage(v) = t(v) div II, and the number of stages SC."""
st = {v: s // ii for v, s in t.items()}
return st, 1 + max(st.values(), default=0)
test_iterative_modulo_scheduling.py 239 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-modulo-scheduling/. The authors are listed in prov/PJN90C.jsonl.
import random
import pytest
import iterative_modulo_scheduling as ims
# acc = acc * c + x[i] * y[i], with i = i + 1
NAMES = ["lx", "ly", "m1", "m2", "a", "inc"]
RES = [[("mem", 0)], [("mem", 0)], [("mul", 0)], [("mul", 0)], [("alu", 0)], [("alu", 0)]]
EDGES = [
(0, 3, 2, 0), (1, 3, 2, 0), (2, 4, 2, 0), (3, 4, 2, 0), (4, 2, 1, 1),
(5, 0, 1, 1), (5, 1, 1, 1), (5, 5, 1, 1), (0, 5, 0, 0), (1, 5, 0, 0),
]
MACHINE = {"mem": 1, "mul": 1, "alu": 1}
def ceil_div(a, b):
return -(-a // b)
def legal(n, res, edges, machine, ii, t):
"""Every edge holds and no slot of the modulo reservation table is over
its number of units."""
if sorted(t) != list(range(n)) or min(t.values(), default=0) < 0:
return False
for u, v, delay, dist in edges:
if t[v] + ii * dist < t[u] + delay:
return False
use = {}
for v in range(n):
for r, off in res[v]:
key = (r, (t[v] + off) % ii)
use[key] = use.get(key, 0) + 1
return all(c <= machine[key[0]] for key, c in use.items())
def flat_ok(n, res, edges, machine, ii, t, iters):
"""Run iters overlapped iterations, iteration i from cycle i * II, and
check every unit in every cycle and every dependence between iterations."""
start = {(v, i): i * ii + t[v] for v in range(n) for i in range(iters)}
busy = {}
for (v, i), s in start.items():
for r, off in res[v]:
busy[(r, s + off)] = busy.get((r, s + off), 0) + 1
if any(c > machine[r] for (r, _), c in busy.items()):
return False
for u, v, delay, dist in edges:
for i in range(iters - dist):
if start[(v, i + dist)] < start[(u, i)] + delay:
return False
return True
def oracle_res_mii(n, res, machine):
best = 0
for r in machine:
uses = sum(1 for v in range(n) for x, _ in res[v] if x == r)
best = max(best, ceil_div(uses, machine[r]))
return best
def oracle_rec_mii(n, edges):
"""max over simple cycles of ceil(delay / distance), by enumeration of
the simple cycles from their least vertex."""
out = [[] for _ in range(n)]
for u, v, delay, dist in edges:
out[u].append((v, delay, dist))
best = 0
def walk(start, x, on, delay, dist):
nonlocal best
for y, d1, d2 in out[x]:
if y == start:
assert dist + d2 >= 1
best = max(best, ceil_div(delay + d1, dist + d2))
elif y > start and y not in on:
on.add(y)
walk(start, y, on, delay + d1, dist + d2)
on.discard(y)
for s in range(n):
walk(s, s, {s}, 0, 0)
return best
def feasible(n, res, edges, machine, ii):
"""Exact test: is there any legal modulo schedule at ii? Enumerate the
slots k(v) = t(v) mod ii that fit the table; then t(v) = k(v) + ii q(v)
and the edges are difference constraints on the integers q(v)."""
k = [0] * n
use = {}
def diff_ok():
cons = [(u, v, ceil_div(delay - ii * dist - k[v] + k[u], ii)) for u, v, delay, dist in edges]
q = [0] * n
for _ in range(n + 1):
changed = False
for u, v, c in cons:
if q[u] + c > q[v]:
q[v] = q[u] + c
changed = True
if not changed:
return True
return False
def rec(j):
if j == n:
return diff_ok()
for x in range(ii):
keys = [(r, (x + off) % ii) for r, off in res[j]]
for key in keys:
use[key] = use.get(key, 0) + 1
if all(use[key] <= machine[key[0]] for key in keys):
k[j] = x
if rec(j + 1):
for key in keys:
use[key] -= 1
return True
for key in keys:
use[key] -= 1
return False
return rec(0)
def random_loop(rng, n):
machine = {"mem": 1, "alu": rng.choice([1, 2]), "mul": 1}
res = []
for _ in range(n):
r = rng.choice(["mem", "alu", "mul"])
if r == "mul" and rng.random() < 0.3:
res.append([("mul", 0), ("mul", 1)])
else:
res.append([(r, 0)])
edges = []
for _ in range(rng.randint(0, 2 * n)):
u, v = rng.randrange(n), rng.randrange(n)
dist = 0 if u < v and rng.random() < 0.6 else rng.randint(1, 3)
edges.append((u, v, rng.randint(-1, 4), dist))
return n, res, edges, machine
def test_example():
n = len(NAMES)
assert ims.res_mii(n, RES, MACHINE) == 2
assert ims.rec_mii(n, EDGES) == 3
assert ims.height_r(n, EDGES, 3) == [4, 4, 2, 2, 0, 2]
log = []
ii, t, mii = ims.modulo_schedule(n, RES, EDGES, MACHINE, log=log)
assert (ii, mii) == (3, 3)
assert {NAMES[v]: s for v, s in t.items()} == {"lx": 0, "ly": 1, "m1": 6, "m2": 4, "a": 8, "inc": 1}
steps = [(NAMES[v], e, s, [NAMES[w] for w in out]) for v, e, s, out in log[1:]]
assert steps == [
("lx", 0, 0, []), ("ly", 0, 1, []), ("m1", 0, 0, []), ("m2", 3, 4, []), ("inc", 1, 1, []),
("a", 6, 6, ["m1"]), ("m1", 4, 5, ["a"]), ("a", 7, 8, ["m1"]), ("m1", 6, 6, []),
]
assert ims.stages(t, ii) == ({0: 0, 1: 0, 2: 2, 3: 1, 4: 2, 5: 0}, 3)
assert legal(n, RES, EDGES, MACHINE, ii, t)
assert flat_ok(n, RES, EDGES, MACHINE, ii, t, 6)
assert not feasible(n, RES, EDGES, MACHINE, 2) and feasible(n, RES, EDGES, MACHINE, 3)
def test_random_loops_against_oracles():
rng = random.Random(21)
for _ in range(600):
n, res, edges, machine = random_loop(rng, rng.randint(1, 7))
rm = ims.res_mii(n, res, machine)
cm = ims.rec_mii(n, edges)
assert rm == oracle_res_mii(n, res, machine)
assert cm == oracle_rec_mii(n, edges)
ii, t, mii = ims.modulo_schedule(n, res, edges, machine)
assert mii == max(1, rm, cm) and ii >= mii
assert legal(n, res, edges, machine, ii, t)
_, sc = ims.stages(t, ii)
assert flat_ok(n, res, edges, machine, ii, t, sc + 3)
def test_mii_bounds_the_optimum():
rng = random.Random(22)
hit = 0
for _ in range(150):
n, res, edges, machine = random_loop(rng, rng.randint(1, 5))
ii, t, mii = ims.modulo_schedule(n, res, edges, machine)
best = next(x for x in range(1, ii + 1) if feasible(n, res, edges, machine, x))
assert mii <= best <= ii
if not feasible(n, res, edges, machine, mii):
assert best > mii
hit += ii == best
assert hit >= 140
def test_small_budget_still_legal():
rng = random.Random(23)
worse = 0
for _ in range(200):
n, res, edges, machine = random_loop(rng, rng.randint(2, 7))
ii, t, mii = ims.modulo_schedule(n, res, edges, machine, budget_ratio=1)
assert ii >= mii and legal(n, res, edges, machine, ii, t)
worse += ii > ims.modulo_schedule(n, res, edges, machine)[0]
assert worse > 0
def test_self_conflicting_table():
# a divide that holds the multiplier in cycles 0 and 2 cannot run at II = 2
res = [[("mul", 0), ("mul", 2)], [("alu", 0)]]
machine = {"mul": 1, "alu": 1}
assert ims.res_mii(2, res, machine) == 2
assert ims.iterative_schedule(2, res, [], machine, 2, 6) is None
ii, t, _ = ims.modulo_schedule(2, res, [], machine)
assert ii == 3 and legal(2, res, [], machine, 3, t)
assert not feasible(2, res, [], machine, 2)
def test_rounding_up():
# three loads on two memory ports: II = 1 would need three ports
res = [[("mem", 0)]] * 3
machine = {"mem": 2}
assert ims.res_mii(3, res, machine) == 2
assert not feasible(3, res, [], machine, 1)
# a recurrence of delay 5 over distance 2 needs II = 3, not 2
edges = [(0, 1, 3, 0), (1, 0, 2, 2)]
assert ims.rec_mii(2, edges) == 3
assert not feasible(2, [[("alu", 0)], [("alu", 0)]], edges, {"alu": 2}, 2)
def test_input_checks():
with pytest.raises(ValueError):
ims.modulo_schedule(2, [[("alu", 0)], [("alu", 0)]], [(0, 1, 1, 0), (1, 0, 1, 0)], {"alu": 1})
with pytest.raises(ValueError):
ims.modulo_schedule(1, [[("alu", 0)]], [(0, 0, 1, 0)], {"alu": 1})
with pytest.raises(ValueError):
ims.modulo_schedule(1, [[("fpu", 0)]], [], {"alu": 1})
with pytest.raises(ValueError):
ims.modulo_schedule(1, [[("alu", 0)]], [(0, 0, 1, -1)], {"alu": 1})
assert ims.modulo_schedule(0, [], [], {"alu": 1}) == (1, {}, 1)
ii, t, _ = ims.modulo_schedule(1, [[("alu", 0)]], [(0, 0, 4, 1)], {"alu": 1})
assert (ii, t) == (4, {0: 0})
History
Rau and Glaeser (1981) scheduled one iteration at a fixed interval with resources reserved modulo that interval, for a machine designed to make this easy. Lam (1988) built modulo scheduling into the compiler of the Warp machine, with bounds from resources and recurrences and modulo variable expansion. At Cydrome, Rau and others built the Cydra 5 and its compiler around modulo scheduling with rotating registers. Huff (1993) added slack scheduling to keep lifetimes short. Rau (1994) gave iterative modulo scheduling, with HeightR, the budget and the displacement of operations, and a long journal version in 1996. Llosa and others gave swing modulo scheduling in 1996, and Zhang and Liu carried the modulo reservation table into high-level synthesis in 2013.
References
- B. Ramakrishna Rau, Iterative modulo scheduling, an algorithm for software pipelining loops, Proceedings of the 27th Annual International Symposium on Microarchitecture, 1994, 63-74, the bounds ResMII and RecMII with the MinDist matrix, the priority HeightR, and the procedures IterativeSchedule and FindTimeSlot with the earliest start Estart and a budget of BudgetRatio times the number of operations
- B. Ramakrishna Rau, Iterative modulo scheduling, International Journal of Parallel Programming 24(1), 1996, 3-64, the journal version of the algorithm with its measurements
- Monica Lam, Software pipelining, an effective scheduling technique for VLIW machines, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation, 1988, 318-328, modulo scheduling with lower bounds from resources and recurrences, the scheduling of strongly connected components first, and modulo variable expansion
- Richard A. Huff, Lifetime-sensitive modulo scheduling, Proceedings of the ACM SIGPLAN Conference on Programming Language Design and Implementation, 1993, 258-267, MinDist as all-pairs longest paths with arc costs of latency minus distance times II, and slack scheduling that places operations early or late to keep lifetimes short
- Josep Llosa, Antonio González, Eduard Ayguadé and Mateo Valero, Swing modulo scheduling, a lifetime-sensitive approach, Proceedings of the Conference on Parallel Architectures and Compilation Techniques, 1996, 80-86, the order of the operations by recurrences and the placement of each operation next to its scheduled neighbors
- Vicki H. Allan, Reese B. Jones, Randall M. Lee and Stephen J. Allan, Software pipelining, ACM Computing Surveys 27(3), 1995, 367-432, the survey of modulo scheduling methods, with iterative modulo scheduling among them
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 PJN90C Edit this page History Report an error Markdown