Algorithm Search⌘K

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
Properties
deterministicnot exactofflineiterative
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 IIII 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 IIII cycles, an operation that starts at step tt uses its unit in slot t mod IIt \bmod II 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 sv−su≥ℓ(u)−II⋅dist(u,v)s_v - s_u \ge \ell(u) - II \cdot \mathrm{dist}(u, v). 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 IIII and starts again. The result always meets all rules, and it is not always the least IIII.

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 VV with a latency ℓ(v)≥0\ell(v) \ge 0 and a type k(v)k(v), and dependence edges (u,v)(u, v) with a distance dist(u,v)≥0\mathrm{dist}(u, v) \ge 0 in iterations. Edges with distance 0 form a graph with no cycle. Units of a limited type kk number aka_k and are pipelined: each accepts a new operation every cycle. A modulo schedule for IIII gives starts s:V→{0,1,…}s : V \to \{0, 1, \ldots\} with

  • sv+II⋅dist(u,v)≥su+ℓ(u)s_v + II \cdot \mathrm{dist}(u, v) \ge s_u + \ell(u) for each edge, since iteration i+disti + \mathrm{dist} starts II⋅distII \cdot \mathrm{dist} cycles after iteration ii;
  • for each limited type kk and each residue r∈{0,…,II−1}r \in \{0, \ldots, II - 1\}, at most aka_k operations of type kk have sv≡r(modII)s_v \equiv r \pmod{II}.

The goal is the least IIII that admits a modulo schedule, and then a short schedule for it. Two lower bounds hold (Rau, 1994):

ResMII=max⁡k⌈nkak⌉,RecMII=max⁡cycles c⌈∑u∈cℓ(u)∑e∈cdist(e)⌉,\mathrm{ResMII} = \max_k \left\lceil \frac{n_k}{a_k} \right\rceil, \qquad \mathrm{RecMII} = \max_{\text{cycles } c} \left\lceil \frac{\sum_{u \in c} \ell(u)}{\sum_{e \in c} \mathrm{dist}(e)} \right\rceil,

where nkn_k is the number of operations of type kk and the sums run over the edges of the cycle cc and their tails uu. This page does not treat the hardness of the exact problem; it solves it only by exhaustive search on small loops.

The algorithm

  1. SDC-MODULO-SCHEDULE(V, E, ℓ, k, a)
  2. 1II ← max(ResMII, RecMII)
  3. 2loop
  4. 3C ← { s_v − s_u ≥ ℓ(u) − II · dist(u, v) : (u, v) ∈ E }
  5. 4s ← the least solution of C with s ≥ 0
  6. 5MRT ← an empty table with II slots per limited type
  7. 6Q ← the operations of limited types, sorted by (s_v, v)
  8. 7for each v in Q do
  9. 8for t ← lo(v) to lo(v) + II − 1, where lo(v) is the least start of v that C allows now, do
  10. 9if MRT has no free unit of type k(v) in slot t mod II then try the next t
  11. 10if C with s_v = t added has a solution then
  12. 11add s_v = t to C; take a unit in slot t mod II; go to the next v
  13. 12if no t worked then this II fails; leave the for loop
  14. 13if this II failed then II ← II + 1 and go back to L3
  15. 14else 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: m1=acc⋅cm_1 = \mathrm{acc} \cdot c and m2=xi⋅yim_2 = x_i \cdot y_i with latency 2, and a=m1+m2a = m_1 + m_2 with latency 1. The edges are m1→am_1 \to a and m2→am_2 \to a with distance 0, and a→m1a \to m_1 with distance 1, since the next iteration multiplies the new sum. So ResMII=2\mathrm{ResMII} = 2 and RecMII=⌈(2+1)/1⌉=3\mathrm{RecMII} = \lceil (2 + 1)/1 \rceil = 3.

At II=3II = 3 the rows are sa−sm1≥2s_a - s_{m_1} \ge 2, sa−sm2≥2s_a - s_{m_2} \ge 2 and sm1−sa≥1−3s_{m_1} - s_a \ge 1 - 3, so sa=sm1+2s_a = s_{m_1} + 2 exactly. The least solution is (0,0,2)(0, 0, 2), so line L6 orders m1m_1 before m2m_2. Line L11 fixes m1m_1 at 0, in slot 0, which forces sa=2s_a = 2. For m2m_2, start 0 has a full slot, and starts 1 and 2 would need sa≥3s_a \ge 3. So II=3II = 3 fails. At II=4II = 4, m1m_1 goes to 0, m2m_2 to 1, and aa to 3, a valid schedule.

The least IIII is 3: the schedule sm1=1s_{m_1} = 1, sm2=0s_{m_2} = 0, sa=3s_a = 3 uses slots 1 and 0 and meets sm1+3≥sa+1s_{m_1} + 3 \ge s_a + 1. The greedy order fixed m1m_1 at its earliest start, which left no room for m2m_2 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 II≥ResMIIII \ge \mathrm{ResMII}, by counting residues, and II≥RecMIIII \ge \mathrm{RecMII}, by adding the rows around a cycle. For II≥RecMIIII \ge \mathrm{RecMII} the rows of L3 have no positive cycle, so line L4 always succeeds.
  • Valid output. After each fixing step, the rows of CC with the fixed starts still have a solution, and the table never holds more than aka_k operations of type kk in a slot. The returned schedule meets every edge and every slot limit.
  • Full period of candidates. The starts of vv that keep CC feasible form an interval of integers that begins at lo(v)lo(v). 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 IIII 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 IIII above the exhaustive optimum on 2 of them. On all 150 the exhaustive optimum equalled max⁡(ResMII,RecMII)\max(\mathrm{ResMII}, \mathrm{RecMII}). 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 IIII, 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 VV with latency ℓ(v)≥0\ell(v) \ge 0 and type k(v)k(v), and edges (u,v)(u, v) with distance dist(u,v)≥0\mathrm{dist}(u, v) \ge 0. Every cycle of edges has a total distance of at least 1. A limited type kk has ak≥1a_k \ge 1 pipelined units. For an integer II≥1II \ge 1, a modulo schedule is a vector s∈Z≥0Vs \in \mathbb{Z}_{\ge 0}^V with

  • (D) sv−su≥ℓ(u)−II⋅dist(u,v)s_v - s_u \ge \ell(u) - II \cdot \mathrm{dist}(u, v) for each edge (u,v)(u, v);
  • (M) for each limited type kk and each r∈{0,…,II−1}r \in \{0, \ldots, II - 1\}, at most aka_k operations vv of type kk have sv mod II=rs_v \bmod II = r.

Let CIIC_{II} be the rows (D). A fixing step adds the two rows sv≥ts_v \ge t and sv≤ts_v \le t. 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 SS of rows sv−su≥ws_v - s_u \ge w with integer ww, lower bounds sv≥λvs_v \ge \lambda_v and upper bounds sv≤μvs_v \le \mu_v, all integers.

  • (F1) SS has a real solution exactly when it has an integer solution, since its matrix is totally unimodular and its data are integers.
  • (F2) If SS has a solution, it has a least one, componentwise, and it is integral. The longest path computation from the lower bounds finds it, and SS is feasible exactly when that computation ends with no positive cycle and the result meets every upper bound. This is the test that least_solution makes.

Lemma 1 (lower bounds)

Every modulo schedule for IIII has II≥ResMIIII \ge \mathrm{ResMII} and II≥RecMIIII \ge \mathrm{RecMII}.

Proof. Fix a limited type kk with nkn_k operations. By (M), each of the IIII residues holds at most aka_k of them, and every operation has one residue, so nk≤ak⋅IIn_k \le a_k \cdot II, which gives II≥⌈nk/ak⌉II \ge \lceil n_k / a_k \rceil. Now fix a cycle cc 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

0≥∑(u,v)∈cℓ(u)−II⋅∑(u,v)∈cdist(u,v).0 \ge \sum_{(u, v) \in c} \ell(u) - II \cdot \sum_{(u, v) \in c} \mathrm{dist}(u, v).

The total distance DcD_c is at least 1, so II≥∑ℓ(u)/DcII \ge \sum \ell(u) / D_c, and as IIII is an integer, II≥⌈∑ℓ(u)/Dc⌉II \ge \lceil \sum \ell(u) / D_c \rceil. □\square

Lemma 2 (the rows of L3 are feasible)

If II≥RecMIIII \ge \mathrm{RecMII}, then CIIC_{II} with s≥0s \ge 0 has a solution, so line L4 succeeds. If II<RecMIIII < \mathrm{RecMII}, then CIIC_{II} has none.

Proof. Read CIIC_{II} as a graph with an arc u→vu \to v of weight w=ℓ(u)−II⋅dist(u,v)w = \ell(u) - II \cdot \mathrm{dist}(u, v). A cycle cc has weight ∑ℓ(u)−II⋅Dc\sum \ell(u) - II \cdot D_c, which is at most 0 exactly when II≥∑ℓ(u)/DcII \ge \sum \ell(u) / D_c. So all cycles have weight at most 0 exactly when II≥RecMIIII \ge \mathrm{RecMII}. With no positive cycle, the longest path from a source joined to every node with weight 0 gives a solution with s≥0s \ge 0. With a positive cycle, the sum argument of Lemma 1 shows that no solution exists. □\square

So the least IIII with no positive cycle, which the implementation finds by trying II=1,2,…II = 1, 2, \ldots, is RecMII\mathrm{RecMII}. Since a cycle weight only falls when IIII grows, a binary search also works.

Lemma 3 (the feasible starts of one operation form an interval)

Let SS be a feasible system of the form in (F2), and let vv be an operation. Let T={t∈Z:S with sv=t is feasible}T = \{t \in \mathbb{Z} : S \text{ with } s_v = t \text{ is feasible}\}. Then TT is a set of consecutive integers, and its least element is lo(v)lo(v), the value of vv in the least solution of SS.

Proof. The real solutions of SS form a convex set PP. Its image under s↦svs \mapsto s_v is a convex subset of R\mathbb{R}, an interval JJ. Take an integer t∈Jt \in J. Then SS with the two rows sv≥ts_v \ge t and sv≤ts_v \le t has a real solution, and these rows are bounds of the form in (F1), so it has an integer solution. Hence T=J∩ZT = J \cap \mathbb{Z}, a set of consecutive integers. Let xx be the least solution of SS. Then xv∈Tx_v \in T, and every solution yy has yv≥xvy_v \ge x_v, so no t<xvt < x_v is in TT. □\square

Theorem 1 (the candidates of L8 cover every residue that can work)

When line L7 handles vv with the current system SS, write lo=lo(v)lo = lo(v). If some t∈Tt \in T has a free unit of type k(v)k(v) in slot t mod IIt \bmod II, then line L8 reaches such a tt and line L11 fixes vv.

Proof. Let t∗∈Tt^* \in T have a free slot. By Lemma 3, TT is a set of consecutive integers that starts at lolo, so it holds every integer from lolo to t∗t^*. Let t′=lo+((t∗−lo) mod II)t' = lo + ((t^* - lo) \bmod II). Then lo≤t′≤t∗lo \le t' \le t^*, so t′∈Tt' \in T, and t′≡t∗(modII)t' \equiv t^* \pmod{II}, so t′t' has the same free slot. Also t′≤lo+II−1t' \le lo + II - 1, so line L8 tries t′t' 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 TT, by (F2). So the scan fixes the first candidate in lo,…,lo+II−1lo, \ldots, lo + II - 1 that is in TT and has a free slot, and t′t' is such a candidate. □\square

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 (II,s)(II, s), then ss is a modulo schedule for IIII.

Proof. We keep this invariant: the current system SS, which is CIIC_{II} with s≥0s \ge 0 and the rows added on line L11, is feasible, and the table holds, for each limited type kk and residue rr, the number of fixed operations of type kk with residue rr, which is at most aka_k.

At the start, SS is feasible by Lemma 2, since II≥RecMIIII \ge \mathrm{RecMII} on line L1 and IIII only grows, and the table is empty. On line L11, the system with sv=ts_v = t added was found feasible on line L10, and the slot of tt had fewer than aka_k entries on line L9, so after one more entry it holds at most aka_k. Every limited operation is fixed once, since line L6 lists each of them once.

On line L14 every limited operation is fixed, and SS is feasible, so its least solution ss exists by (F2). It meets (D), since CII⊆SC_{II} \subseteq S, and s≥0s \ge 0. Each limited vv has svs_v equal to its fixed value tvt_v, so the operations of type kk with residue rr are exactly the fixed ones that the table counts, and (M) holds. Operations of unlimited types have no slot limit. □\square

For fixed IIII, the function exact_schedule returns a modulo schedule exactly when one exists.

Proof. Each s∈Z≥0Vs \in \mathbb{Z}_{\ge 0}^V is written in one way as sv=rv+II⋅qvs_v = r_v + II \cdot q_v with rv∈{0,…,II−1}r_v \in \{0, \ldots, II - 1\} and qv∈Z≥0q_v \in \mathbb{Z}_{\ge 0}. Condition (M) depends only on rr, and _residues lists exactly the vectors rr that meet (M), since it skips a value of rvr_v only when its slot is already full. For fixed rr, a row of (D) with weight ww reads rv+IIqv−ru−IIqu≥wr_v + II q_v - r_u - II q_u \ge w, that is, qv−qu≥(w−rv+ru)/IIq_v - q_u \ge (w - r_v + r_u)/II. As qv−quq_v - q_u is an integer, this holds exactly when qv−qu≥⌈(w−rv+ru)/II⌉q_v - q_u \ge \lceil (w - r_v + r_u)/II \rceil. These rows are difference constraints with integer weights, and with q≥0q \ge 0 they have an integer solution exactly when the longest path computation succeeds, by (F2). So for each rr the search finds a qq exactly when some schedule has residues rr, and it returns s=r+II⋅qs = r + II \cdot q, which meets (D) and (M). If it finds none for every rr, no schedule exists. □\square

Then exact_min_ii returns the least IIII in its range with a schedule, since it tries IIII upward from max⁡(ResMII,RecMII)\max(\mathrm{ResMII}, \mathrm{RecMII}), and Lemma 1 shows that no smaller IIII has one.

What is not claimed

  • The heuristic IIII 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 IIII. 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 max⁡(ResMII,RecMII)\max(\mathrm{ResMII}, \mathrm{RecMII}) 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 1+∑vℓ(v)1 + \sum_v \ell(v) longest path runs, or from a binary search over IIII, since a positive cycle at some IIII stays positive at every smaller IIII. For one IIII, line L10 runs at most IIII times for each of at most VV operations, and each run is Bellman-Ford in O(V(V+E))O(V (V + E)) time. So one IIII costs O(II⋅V2(V+E))O(II \cdot V^2 (V + E)), and II values of IIII, each at most PP, cost O(IPV2(V+E))O(I P V^2 (V + E)). Space is O(V+E)O(V + E) for the rows and the table, plus O(II)O(II) 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 IIII 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 CC 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 IIII 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 sv+II⋅dists_v + II \cdot \mathrm{dist} with sus_u, 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 rr, writing sv=rv+II⋅qvs_v = r_v + II \cdot q_v turns the rows into difference constraints on the integers qvq_v, so feasibility is one longest path run. The tests use this as the reference.
  • Non-pipelined units. A unit busy for dd cycles takes dd consecutive slots modulo IIII in the table.

When to use it

Use it to pipeline inner loops in HLS when the throughput target is a small IIII 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 IIII. For signal processing graphs with no control flow, retiming and folding give the classic alternative.

Pitfalls

  • Not exact. Do not report the returned IIII as the least one, unless it equals max⁡(ResMII,RecMII)\max(\mathrm{ResMII}, \mathrm{RecMII}).
  • Distance 0 cycles. A cycle of edges with distance 0 has no schedule for any IIII. Check the input before computing RecMII.
  • Residues of negative starts. If starts may be negative, use a residue in {0,…,II−1}\{0, \ldots, II - 1\}, 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.

sdc_modulo_scheduling.pyI0RawGitHub
# 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 IIII. 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

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

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