Algorithm Search⌘K

Algorithmcore

Force-directed scheduling

Also called Paulin-Knight scheduling, time-constrained force-directed scheduling.

Paulin and Knight's scheduler that fixes, one at a time, the operation and step with the least force, so the use of each unit type is balanced over steps.

Time
O(V^2 L (E + V L)) worst
Space
O(V L + E) extra
Where
E = the number of data edges; L = the latency bound in steps; V = the number of operations
Properties
deterministicnot exactofflineiterative
Origin
Pierre G. Paulin, John P. Knight, 1989

Force-directed scheduling (FDS) is a heuristic of high-level synthesis. It schedules the operations of a data flow graph within a fixed latency so that few functional units are needed. It starts from the time frames of ASAP and ALAP scheduling, and it treats each operation as if its start were spread evenly over its frame. Adding these spreads gives, for each unit type and step, the expected number of operations in that step, the distribution graph. FDS then fixes one operation at one step at a time, the choice that lowers the peaks of the distribution graphs the most, which Paulin and Knight called the least force. The result always meets the precedences and the latency bound. It is not always the schedule with the fewest units.

In plain words

You must fit a set of operations into a fixed number of clock steps, and you want to buy as few adders and multipliers as possible. That means the multiplies should not all fall into the same step. At the start, most operations can still move. For each operation, pretend that it is spread over all the steps it could use, a little bit in each. Add these bits up for each step, and you see where the crowd is. Now try each operation in each of its possible steps, and see how much the crowd moves toward the empty steps. Take the best move, fix it, and see which other operations lose freedom because of it. Repeat until every operation is fixed.

The problem

The input is a data flow graph G=(V,E)G = (V, E) with no cycle, a unit type k(v)k(v) and a delay δ(v)≥1\delta(v) \ge 1 for each operation, and a latency bound LL. A schedule tt starts each vv at a step t(v)≥1t(v) \ge 1, with t(v)≥t(u)+δ(u)t(v) \ge t(u) + \delta(u) for each edge (u,v)(u, v) and t(v)+δ(v)−1≤Lt(v) + \delta(v) - 1 \le L. Operation vv uses the steps t(v)t(v) to t(v)+δ(v)−1t(v) + \delta(v) - 1. The number of units of type kk that tt needs is the largest number of operations of type kk that use one step. The goal is a schedule that needs few units in total, the time-constrained form of the high-level synthesis scheduling problem. That problem is NP-hard, and FDS does not solve it exactly.

The algorithm

The time frame of vv is [a(v),b(v)][a(v), b(v)], its ASAP and its ALAP start, given the operations fixed so far. If each start in the frame has the same chance, the chance that vv uses step jj is

Pv(j)=#{s∈[a(v),b(v)]:s≤j≤s+δ(v)−1}b(v)−a(v)+1.P_v(j) = \frac{\#\{ s \in [a(v), b(v)] : s \le j \le s + \delta(v) - 1 \}}{b(v) - a(v) + 1}.

The distribution graph of type kk is DGk(j)=∑v:k(v)=kPv(j)\mathrm{DG}_k(j) = \sum_{v : k(v) = k} P_v(j). If a trial choice changes the frame of some operation uu and so changes PuP_u to Pu′P'_u, the force of the change on uu is ∑jDGk(u)(j) (Pu′(j)−Pu(j))\sum_j \mathrm{DG}_{k(u)}(j)\, (P'_u(j) - P_u(j)). The total force of starting vv at ss is the sum of these forces over vv itself (the self force) and over all other operations whose frames shrink (the predecessor and successor forces). A negative force moves probability from crowded steps to empty ones.

  1. FORCE-DIRECTED-SCHEDULE(G, k, δ, L)
  2. 1fixed ← ∅; frames ← TIME-FRAMES(G, δ, L, fixed)
  3. 2if frames is "infeasible" then return "infeasible"
  4. 3loop
  5. 4for each v not in fixed whose frame is one step [s, s] do fixed(v) ← s
  6. 5if every v is in fixed then return fixed
  7. 6for each type k and step j do DG_k(j) ← Σ over v with k(v) = k of P_v(j)
  8. 7for each v not in fixed and each s in the frame of v do
  9. 8frames' ← TIME-FRAMES(G, δ, L, fixed with v at s)
  10. 9F(v, s) ← Σ over u with frames'(u) ≠ frames(u) of Σ_j DG_{k(u)}(j) (P'_u(j) - P_u(j))
  11. 10(v, s) ← the pair with the least F(v, s), the first one in the order of v and s on a tie
  12. 11fixed(v) ← s; frames ← TIME-FRAMES(G, δ, L, fixed)

TIME-FRAMES is the pair of passes of ASAP and ALAP scheduling, with the start of each fixed operation as both a lower and an upper bound. It reports "infeasible" when the bounds clash. All values here are exact fractions, so the comparison on line L10 and the tie rule do not depend on rounding.

Example

Take the differential equation example of Paulin and Knight with L=4L = 4 and unit delays. The operations v1,v2,v3,v6,v7,v8v_1, v_2, v_3, v_6, v_7, v_8 are multiplies and v4,v5,v9,v10,v11v_4, v_5, v_9, v_{10}, v_{11} are ALU operations, with the edges v1→v3v_1 \to v_3, v2→v3v_2 \to v_3, v3→v4v_3 \to v_4, v4→v5v_4 \to v_5, v6→v7v_6 \to v_7, v7→v5v_7 \to v_5, v8→v9v_8 \to v_9 and v10→v11v_{10} \to v_{11}. The frames are on the ASAP and ALAP page. The first distribution graphs are:

step 1 2 3 4
DGmul\mathrm{DG}_{\text{mul}} 17/6 7/3 5/6 0
DGalu\mathrm{DG}_{\text{alu}} 1/3 1 2 5/3

For example, DGmul(1)=1+1+12+13\mathrm{DG}_{\text{mul}}(1) = 1 + 1 + \tfrac12 + \tfrac13, from v1v_1 and v2v_2, which must start at step 1, v6v_6 with frame [1,2][1, 2], and v8v_8 with frame [1,3][1, 3]. Some first forces:

operation frame force at each start in the frame
v6v_6 [1,2][1, 2] 1/4, −1
v8v_8 [1,3][1, 3] 5/6, 11/18, −19/18
v11v_{11} [2,4][2, 4] −4/3, 0, 1/9

The force of v11v_{11} at step 2 is its self force, 1⋅23−2⋅13−53⋅13=−591 \cdot \tfrac23 - 2 \cdot \tfrac13 - \tfrac53 \cdot \tfrac13 = -\tfrac59, plus the force on v10v_{10}, whose frame shrinks from [1,3][1, 3] to [1,1][1, 1], 13⋅23−1⋅13−2⋅13=−79\tfrac13 \cdot \tfrac23 - 1 \cdot \tfrac13 - 2 \cdot \tfrac13 = -\tfrac79. The sum −43-\tfrac43 is the least force of all, so line L11 fixes v11v_{11} at step 2, and v10v_{10} is fixed at step 1 in the next round. The next choices are v8v_8 at step 3 with force −76-\tfrac76, and v6v_6 at step 2 with force −12-\tfrac12. Then all frames have one step, and the schedule is

step multiplies ALU operations
1 v1,v2v_1, v_2 v10v_{10}
2 v3,v6v_3, v_6 v11v_{11}
3 v7,v8v_7, v_8 v4v_4
4 v5,v9v_5, v_9

It needs 2 multipliers and 2 ALUs. A search over all schedules shows that 4 units in total is the least for L=4L = 4, so FDS is optimal here. At L=5L = 5 and L=6L = 6, it finds schedules with 2 multipliers and 1 ALU.

Correctness

What is proved: TIME-FRAMES returns frames that are exact, that is, a step is in the frame of vv exactly when some schedule that meets the fixed starts and LL starts vv there. So every trial on line L8 succeeds, the frames never become empty, and each round fixes at least one more operation. FDS stops after at most VV rounds and returns a schedule that meets all precedences and the latency bound LL. It reports "infeasible" exactly when LL is less than the critical path length. It is deterministic.

What is not proved: FDS is not optimal. The force is a local, greedy estimate, and FDS comes with no proved bound on its distance from the optimum. The full proof gives the proved part.

Proof: Force-directed scheduling stops with a schedule that meets the latency boundfull

This proof covers what FDS guarantees: it stops, and its output is a valid schedule for the latency bound LL. It does not claim that the schedule needs the fewest units, which is false in general (see the Pitfalls on the page).

We use the notation of the page. A schedule for LL is a map tt with t(v)≥1t(v) \ge 1, t(v)≥t(u)+δ(u)t(v) \ge t(u) + \delta(u) for each edge (u,v)(u, v), and t(v)+δ(v)−1≤Lt(v) + \delta(v) - 1 \le L. For a partial map ϕ\phi of fixed starts, a schedule meets ϕ\phi when t(v)=ϕ(v)t(v) = \phi(v) for every vv in its domain. TIME-FRAMES computes, in topological order, a(v)=max⁡(1,max⁡(u,v)a(u)+δ(u))a(v) = \max(1, \max_{(u,v)} a(u) + \delta(u)), replaced by ϕ(v)\phi(v) when vv is fixed and reported as a clash when ϕ(v)<a(v)\phi(v) < a(v). It computes b(v)=min⁡(L+1,min⁡(v,w)b(w))−δ(v)b(v) = \min(L + 1, \min_{(v,w)} b(w)) - \delta(v) in reverse order in the same way, with a clash when ϕ(v)>b(v)\phi(v) > b(v). It reports "infeasible" on a clash or when some a(v)>b(v)a(v) > b(v).

Lemma 1 (frames bound every schedule). Every schedule tt for LL that meets ϕ\phi has a(v)≤t(v)≤b(v)a(v) \le t(v) \le b(v) for all vv. So if TIME-FRAMES reports "infeasible", no such schedule exists.

Proof. By induction in topological order: t(v)≥1t(v) \ge 1 and t(v)≥t(u)+δ(u)≥a(u)+δ(u)t(v) \ge t(u) + \delta(u) \ge a(u) + \delta(u) for each edge, so t(v)t(v) is at least the unfixed value of a(v)a(v). If vv is fixed, t(v)=ϕ(v)t(v) = \phi(v), which is then at least that value, so no clash happens and t(v)=a(v)t(v) = a(v). The upper bound is the same argument in reverse order. If a schedule exists, it lies in every frame, so no clash happens and a(v)≤t(v)≤b(v)a(v) \le t(v) \le b(v). □\square

Lemma 2 (the frame bounds are schedules). If TIME-FRAMES does not report "infeasible", then aa and bb are schedules for LL that meet ϕ\phi.

Proof. For aa: a(v)≥1a(v) \ge 1, and for each edge, a(v)≥a(u)+δ(u)a(v) \ge a(u) + \delta(u) by construction when vv is free, and because ϕ(v)≥\phi(v) \ge that value when vv is fixed. For the latency, b(v)+δ(v)−1≤Lb(v) + \delta(v) - 1 \le L by construction, and a(v)≤b(v)a(v) \le b(v). So aa is a schedule, and it meets ϕ\phi since a(v)=ϕ(v)a(v) = \phi(v) for fixed vv. For bb: b(v)≤b(w)−δ(v)b(v) \le b(w) - \delta(v) for each edge, in the same way, b(v)+δ(v)−1≤Lb(v) + \delta(v) - 1 \le L, and b(v)≥a(v)≥1b(v) \ge a(v) \ge 1. □\square

Lemma 3 (frames are exact). If TIME-FRAMES does not report "infeasible", then for every vv and every ss with a(v)≤s≤b(v)a(v) \le s \le b(v), some schedule for LL that meets ϕ\phi has t(v)=st(v) = s.

Proof. Let g(x)g(x) be the largest δ(p)−δ(x)\delta(p) - \delta(x) over the paths pp from vv to xx, with δ(p)\delta(p) the sum of the delays of the vertices of pp, or −∞-\infty if there is no path. Put t(x)=max⁡(a(x),s+g(x))t(x) = \max(a(x), s + g(x)). Then t(v)=max⁡(a(v),s)=st(v) = \max(a(v), s) = s.

Precedence. For an edge (x,y)(x, y), a(y)≥a(x)+δ(x)a(y) \ge a(x) + \delta(x) by Lemma 2, and g(y)≥g(x)+δ(x)g(y) \ge g(x) + \delta(x) when g(x)>−∞g(x) > -\infty. So t(y)≥t(x)+δ(x)t(y) \ge t(x) + \delta(x).

Upper bounds. For every edge (x,y)(x, y), b(x)≤b(y)−δ(x)b(x) \le b(y) - \delta(x), so along a path pp from vv to xx, b(x)≥b(v)+δ(p)−δ(x)b(x) \ge b(v) + \delta(p) - \delta(x). Hence s+g(x)≤b(v)+g(x)≤b(x)s + g(x) \le b(v) + g(x) \le b(x) when g(x)>−∞g(x) > -\infty. Also a(x)≤b(x)a(x) \le b(x). So t(x)≤b(x)t(x) \le b(x), and t(x)+δ(x)−1≤Lt(x) + \delta(x) - 1 \le L. Also t(x)≥a(x)≥1t(x) \ge a(x) \ge 1.

Fixed starts. Let xx be fixed with ϕ(x)=c\phi(x) = c. Then a(x)=b(x)=ca(x) = b(x) = c, since a(x)a(x) is set to cc, b(x)b(x) is set to cc, and the bounds do not clash. So c=a(x)≤t(x)≤b(x)=cc = a(x) \le t(x) \le b(x) = c. □\square

Lemma 4 (the loop invariant). At the start of each round of line L3, TIME-FRAMES on the current ϕ\phi did not report "infeasible", and every schedule that meets the current ϕ\phi is a schedule for LL. In each round, every trial of line L8 succeeds, and the round adds at least one operation to ϕ\phi.

Proof. At the first round, line L2 returned unless the frames exist. Line L4 fixes vv at ss where its frame is [s,s][s, s]. By Lemma 1, every schedule that meets ϕ\phi has t(v)=st(v) = s, so the set of schedules that meet ϕ\phi does not change, and by Lemma 3 it is not empty, so the frames with the new fixings exist and are the same. If line L5 does not return, some vv is free, and its frame has at least one step. For each such vv and each ss in its frame, Lemma 3 gives a schedule that meets ϕ\phi and has t(v)=st(v) = s, so by Lemma 1 TIME-FRAMES on ϕ∪{v↦s}\phi \cup \{v \mapsto s\} does not report "infeasible". So every trial on line L8 succeeds, line L10 has at least one candidate, and line L11 adds a new operation to ϕ\phi, with frames that exist. □\square

Theorem. If LL is less than the critical path length, FDS returns "infeasible" on line L2, and no schedule exists. Otherwise it stops after at most ∣V∣|V| rounds and returns a schedule for LL. The output depends only on the input.

Proof. With ϕ\phi empty, the frames are the ASAP and ALAP schedules. By the ASAP and ALAP correctness proof, they exist exactly when LL is at least the critical path length, and otherwise no schedule exists. By Lemma 4, each round fixes a new operation, so after at most ∣V∣|V| rounds all operations are fixed, and line L5 returns ϕ\phi. At that point, the frames exist, so by Lemma 3 some schedule meets ϕ\phi. Since ϕ\phi fixes every operation, that schedule is ϕ\phi itself, and it is a schedule for LL. The forces are computed in exact arithmetic, and line L10 breaks ties by a fixed order, so every step is a function of the input. ■\blacksquare

Complexity

There are at most VV rounds, since each one fixes an operation. A round has at most VLVL trials. A trial runs TIME-FRAMES in O(V+E)O(V + E) time and then sums over at most VV changed frames, each over O(L)O(L) steps for unit delays, so it costs O(E+VL)O(E + VL). The total is O(V2L(E+VL))O(V^2 L (E + VL)) time for unit delays, and O(VL+E)O(VL + E) space for the graph, the frames and the distribution graphs. Each delay δ(v)>1\delta(v) > 1 adds a factor δ(v)\delta(v) to the work for its probabilities. Exact fractions make each arithmetic step cost more than a machine operation.

Properties

  • Always feasible. The schedule meets the precedences and the latency bound.
  • Not exact. The schedule may need more units than the best one.
  • Deterministic. With exact arithmetic and the tie rule of line L10, the same input gives the same schedule.
  • Global view. Each choice looks at the effect on all operations whose frames change, not only on the one being fixed. This is the main difference from list scheduling, which decides step by step.

Variants and improvements

  • Force-directed list scheduling. For a fixed number of units of each type, Paulin and Knight run list scheduling step by step, and when too many operations are ready, they defer those whose deferral has the least force. This is the resource-constrained form.
  • Unit costs. Weight each distribution graph by the area of its unit type, so that a crowd of multipliers costs more than a crowd of adders.
  • Registers and buses. Add distribution graphs for the values that are live in each step, or for the bus transfers, so that the forces also balance storage.
  • Look ahead. Compute the force of a trial with the frames after one more step of propagation, at more cost per trial.
  • Exact methods. For small graphs, a 0-1 integer programming model, with one variable for each operation and start step, gives the optimum and can check the quality of FDS.

When to use it

Use FDS when the latency is fixed, for example by a throughput target, and the goal is to need few units. It suits graphs where its VLVL trials per round are affordable, and it handles many unit types at once. When the unit counts are fixed and the latency should be small, use list scheduling or force-directed list scheduling. When an optimum is needed and the graph is small, use an exact method.

Pitfalls

  • Not optimal. Take one unit type, five unit-delay operations, the edges v1→v3v_1 \to v_3, v2→v3v_2 \to v_3, v2→v4v_2 \to v_4, v3→v5v_3 \to v_5 and v4→v5v_4 \to v_5, and L=5L = 5. The first least force is −109-\tfrac{10}{9}, for v3v_3 at step 2. It forces v1v_1 and v2v_2 into step 1, and the final schedule (1,1,2,4,5)(1, 1, 2, 4, 5) needs 2 units. The schedule (1,2,3,4,5)(1, 2, 3, 4, 5) needs only 1. In a measured run with the random generator of the tests, on 750 instances with at most 6 operations and latencies from the critical path length to 2 more, FDS needed one unit more than the optimum on 16 of them, and was optimal on the rest. This is a measurement on small random graphs, not a bound.
  • Rounding. Probabilities like 1/31/3 in floating point can turn a tie into a strict inequality, so two runs on different machines can give different schedules. Use exact fractions or a fixed tolerance.
  • Stale frames. After a choice, the frames of other operations shrink. The distribution graphs must be rebuilt from the new frames before the next round, or the forces are computed for a state that no longer exists.
  • Negative forces are relative. Force values are only compared with each other. A positive least force does not mean that the choice is bad.

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.

force_directed_scheduling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/force-directed-scheduling/. The authors are listed in prov/CDK7W8.jsonl.

"""Force-directed scheduling (Paulin and Knight) under a latency bound.

Operations are 0 .. n-1, each with a unit type kind[v] (for example
"mul" or "alu") and a delay delay[v] >= 1 in control steps. An edge (u, v)
means t(v) >= t(u) + delay[u]. Steps are 1 .. latency, and an operation
that starts at t uses the steps t .. t + delay[v] - 1. All probabilities
are exact fractions, so the ties and the result do not depend on rounding.
"""

from fractions import Fraction
from typing import Hashable, Optional

Frames = list[tuple[int, int]]


def _order(n: int, edges: list[tuple[int, int]]) -> list[int]:
    succ: list[list[int]] = [[] for _ in range(n)]
    indeg = [0] * n
    for (u, v) in edges:
        succ[u].append(v)
        indeg[v] += 1
    order, ready = [], [v for v in range(n) if indeg[v] == 0]
    while ready:
        u = ready.pop()
        order.append(u)
        for v in succ[u]:
            indeg[v] -= 1
            if indeg[v] == 0:
                ready.append(v)
    if len(order) < n:
        raise ValueError("the data flow graph has a cycle")
    return order


def time_frames(n: int, delay: list[int], edges: list[tuple[int, int]], latency: int,
                fixed: dict[int, int]) -> Optional[Frames]:
    """The frame [ASAP, ALAP] of each operation when the operations in fixed
    must start at the given steps. None if no schedule meets all of it."""
    pred: list[list[int]] = [[] for _ in range(n)]
    succ: list[list[int]] = [[] for _ in range(n)]
    for (u, v) in edges:
        pred[v].append(u)
        succ[u].append(v)
    order = _order(n, edges)
    lo = [0] * n
    for v in order:
        lo[v] = max([1] + [lo[u] + delay[u] for u in pred[v]])
        if v in fixed:
            if fixed[v] < lo[v]:
                return None
            lo[v] = fixed[v]
    hi = [0] * n
    for v in reversed(order):
        hi[v] = min([latency + 1] + [hi[w] for w in succ[v]]) - delay[v]
        if v in fixed:
            if fixed[v] > hi[v]:
                return None
            hi[v] = fixed[v]
    if any(lo[v] > hi[v] for v in range(n)):
        return None
    return list(zip(lo, hi))


def occupancy(frame: tuple[int, int], d: int) -> dict[int, Fraction]:
    """The probability that the operation uses each step, when each start in
    its frame has the same probability."""
    lo, hi = frame
    p = Fraction(1, hi - lo + 1)
    out: dict[int, Fraction] = {}
    for s in range(lo, hi + 1):
        for t in range(s, s + d):
            out[t] = out.get(t, Fraction(0)) + p
    return out


def distribution_graphs(n: int, kind: list[Hashable], delay: list[int], frames: Frames) -> dict:
    """DG[k][t]: the expected number of operations of type k that use step t."""
    dg: dict = {}
    for v in range(n):
        row = dg.setdefault(kind[v], {})
        for t, p in occupancy(frames[v], delay[v]).items():
            row[t] = row.get(t, Fraction(0)) + p
    return dg


def force(n: int, kind, delay, edges, latency, fixed, frames: Frames, dg, v: int, s: int) -> Optional[Fraction]:
    """The total force of starting v at step s: the self force of v plus the
    forces of the other operations whose frames shrink as a result."""
    new = time_frames(n, delay, edges, latency, {**fixed, v: s})  # @line L8
    if new is None:
        return None
    total = Fraction(0)
    for j in range(n):
        if new[j] == frames[j]:
            continue
        before = occupancy(frames[j], delay[j])
        after = occupancy(new[j], delay[j])
        row = dg[kind[j]]
        for t in set(before) | set(after):
            total += row.get(t, Fraction(0)) * (after.get(t, Fraction(0)) - before.get(t, Fraction(0)))  # @line L9
    return total


def force_directed_schedule(n: int, kind: list[Hashable], delay: list[int], edges: list[tuple[int, int]],
                            latency: int, trace: Optional[list] = None) -> Optional[list[int]]:
    """A start step for each operation with all precedences met and every
    operation done by step latency, or None if the latency is too short.
    If trace is a list, each fixing (v, s, force) is appended to it."""
    fixed: dict[int, int] = {}
    frames = time_frames(n, delay, edges, latency, fixed)  # @line L1
    if frames is None:  # @line L2
        return None
    while True:  # @line L3
        for v in range(n):  # @line L4: an operation whose frame has one step is fixed at no cost
            if v not in fixed and frames[v][0] == frames[v][1]:
                fixed[v] = frames[v][0]
        if len(fixed) == n:  # @line L5
            return [fixed[v] for v in range(n)]
        dg = distribution_graphs(n, kind, delay, frames)  # @line L6
        best = None
        for v in range(n):  # @line L7
            if v in fixed:
                continue
            for s in range(frames[v][0], frames[v][1] + 1):
                f = force(n, kind, delay, edges, latency, fixed, frames, dg, v, s)
                assert f is not None  # every step of a frame extends to a schedule
                if best is None or f < best[0]:  # @line L10: the first least force wins a tie
                    best = (f, v, s)
        f, v, s = best
        if trace is not None:
            trace.append((v, s, f))
        fixed[v] = s  # @line L11
        frames = time_frames(n, delay, edges, latency, fixed)
        assert frames is not None


def resource_usage(n: int, kind: list[Hashable], delay: list[int], start: list[int]) -> dict:
    """The number of units of each type that the schedule needs: the largest
    number of operations of that type that use one step."""
    use: dict = {}
    for v in range(n):
        for t in range(start[v], start[v] + delay[v]):
            use[(kind[v], t)] = use.get((kind[v], t), 0) + 1
    out: dict = {}
    for (k, _), c in use.items():
        out[k] = max(out.get(k, 0), c)
    return out
test_force_directed_scheduling.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/force-directed-scheduling/. The authors are listed in prov/CDK7W8.jsonl.

import itertools
import random
from fractions import Fraction as F

from force_directed_scheduling import (distribution_graphs, force, force_directed_schedule, resource_usage,
                                       time_frames)

# The differential equation example (Paulin and Knight): v1 .. v11 are 0 .. 10.
KIND = ["mul", "mul", "mul", "alu", "alu", "mul", "mul", "mul", "alu", "alu", "alu"]
EDGES = [(0, 2), (1, 2), (2, 3), (3, 4), (5, 6), (6, 4), (7, 8), (9, 10)]
N = 11


def feasible(n, delay, edges, latency, start):
    return (all(start[v] >= start[u] + delay[u] for (u, v) in edges)
            and all(1 <= start[v] and start[v] + delay[v] - 1 <= latency for v in range(n)))


def all_schedules(n, delay, edges, latency):
    frames = time_frames(n, delay, edges, latency, {})
    for t in itertools.product(*[range(a, b + 1) for a, b in frames]):
        if feasible(n, delay, edges, latency, t):
            yield list(t)


def units(n, kind, delay, start):
    return sum(resource_usage(n, kind, delay, start).values())


def random_dfg(rng, n):
    kind = [rng.choice("ma") for _ in range(n)]
    delay = [rng.choice([1, 1, 2]) for _ in range(n)]
    edges = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < 0.35]
    return kind, delay, edges


def test_diffeq_first_forces():
    d = [1] * N
    frames = time_frames(N, d, EDGES, 4, {})
    dg = distribution_graphs(N, KIND, d, frames)
    assert dg["mul"] == {1: F(17, 6), 2: F(7, 3), 3: F(5, 6)}
    assert dg["alu"] == {1: F(1, 3), 2: F(1), 3: F(2), 4: F(5, 3)}
    want = {5: [F(1, 4), F(-1)], 7: [F(5, 6), F(11, 18), F(-19, 18)], 10: [F(-4, 3), F(0), F(1, 9)]}
    for v, forces in want.items():
        lo, hi = frames[v]
        assert [force(N, KIND, d, EDGES, 4, {}, frames, dg, v, s) for s in range(lo, hi + 1)] == forces


def test_diffeq_schedules():
    d = [1] * N
    trace = []
    s = force_directed_schedule(N, KIND, d, EDGES, 4, trace)
    assert s == [1, 1, 2, 3, 4, 2, 3, 3, 4, 1, 2]
    assert trace == [(10, 2, F(-4, 3)), (7, 3, F(-7, 6)), (5, 2, F(-1, 2))]
    assert resource_usage(N, KIND, d, s) == {"mul": 2, "alu": 2}
    assert min(units(N, KIND, d, t) for t in all_schedules(N, d, EDGES, 4)) == 4
    for latency, want in ((5, {"mul": 2, "alu": 1}), (6, {"mul": 2, "alu": 1})):
        s = force_directed_schedule(N, KIND, d, EDGES, latency)
        assert feasible(N, d, EDGES, latency, s)
        assert resource_usage(N, KIND, d, s) == want
    assert force_directed_schedule(N, KIND, d, EDGES, 3) is None


def test_not_optimal():
    # one unit type; FDS first starts v3 at step 2, which puts v1 and v2 both at step 1
    kind = ["a"] * 5
    d = [1] * 5
    edges = [(0, 2), (1, 2), (1, 3), (2, 4), (3, 4)]
    trace = []
    s = force_directed_schedule(5, kind, d, edges, 5, trace)
    assert s == [1, 1, 2, 4, 5]
    assert trace == [(2, 2, F(-10, 9)), (3, 4, F(-4, 9))]
    assert units(5, kind, d, s) == 2
    assert units(5, kind, d, [1, 2, 3, 4, 5]) == 1


def test_frames_are_exact():
    # every start in a frame belongs to some schedule that also meets the fixed starts
    rng = random.Random(5401)
    for _ in range(80):
        n = rng.randint(1, 5)
        kind, delay, edges = random_dfg(rng, n)
        cp = max(a + delay[v] - 1 for v, (a, _) in enumerate(time_frames(n, delay, edges, 99, {})))
        latency = cp + rng.randint(0, 2)
        sched = list(all_schedules(n, delay, edges, latency))
        fixed = {}
        for v in rng.sample(range(n), rng.randint(0, n)):
            fixed[v] = rng.randint(1, latency)
        frames = time_frames(n, delay, edges, latency, fixed)
        ok = [t for t in sched if all(t[v] == s for v, s in fixed.items())]
        if frames is None:
            assert not ok
            continue
        for v in range(n):
            assert {t[v] for t in ok} == set(range(frames[v][0], frames[v][1] + 1))


def test_against_exhaustive():
    rng = random.Random(5402)
    worse = 0
    for _ in range(250):
        n = rng.randint(1, 6)
        kind, delay, edges = random_dfg(rng, n)
        cp = max(a + delay[v] - 1 for v, (a, _) in enumerate(time_frames(n, delay, edges, 99, {})))
        assert force_directed_schedule(n, kind, delay, edges, cp - 1) is None
        for latency in (cp, cp + 1, cp + 2):
            s = force_directed_schedule(n, kind, delay, edges, latency)
            assert feasible(n, delay, edges, latency, s)
            best = min(units(n, kind, delay, t) for t in all_schedules(n, delay, edges, latency))
            got = units(n, kind, delay, s)
            assert got >= best
            worse += got > best
            assert s == force_directed_schedule(n, kind, delay, edges, latency)  # deterministic
    # a heuristic: it misses the optimum on some instances, but not on most
    assert 0 < worse < 75

History

Paulin and Knight (1989) gave force-directed scheduling in the HAL system for the behavioral synthesis of ASICs. They described the probabilities as a time frame, the distribution graphs as a load, and the change in load as a force, by analogy with a spring. They also gave the force-directed list scheduler for fixed unit counts, and they used the differential equation example that later became a common benchmark. De Micheli's book (1994) presents FDS as the main heuristic for scheduling under a latency bound.

References

  1. Pierre G. Paulin and John P. Knight, Force-directed scheduling for the behavioral synthesis of ASICs, IEEE Transactions on Computer-Aided Design 8(6), 661 to 679, 1989, the time frames, the distribution graphs, the self and the predecessor and successor forces, the differential equation example, and force-directed list scheduling
  2. Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 5, Scheduling Algorithms (the section on heuristic scheduling algorithms and force-directed scheduling)

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
  • at least three sources
  • a scene preset for the example