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.
- Solves
- High-level synthesis
- 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
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- 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 with no cycle, a unit type and a delay for each operation, and a latency bound . A schedule starts each at a step , with for each edge and . Operation uses the steps to . The number of units of type that needs is the largest number of operations of type 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 is , 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 uses step is
The distribution graph of type is . If a trial choice changes the frame of some operation and so changes to , the force of the change on is . The total force of starting at is the sum of these forces over 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.
FORCE-DIRECTED-SCHEDULE(G, k, δ, L)- 1
fixed ← ∅; frames ← TIME-FRAMES(G, δ, L, fixed) - 2
if frames is "infeasible" then return "infeasible" - 3
loop - 4
for each v not in fixed whose frame is one step [s, s] do fixed(v) ← s - 5
if every v is in fixed then return fixed - 6
for each type k and step j do DG_k(j) ← Σ over v with k(v) = k of P_v(j) - 7
for each v not in fixed and each s in the frame of v do - 8
frames' ← TIME-FRAMES(G, δ, L, fixed with v at s) - 9
F(v, s) ← Σ over u with frames'(u) ≠ frames(u) of Σ_j DG_{k(u)}(j) (P'_u(j) - P_u(j)) - 10
(v, s) ← the pair with the least F(v, s), the first one in the order of v and s on a tie - 11
fixed(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 and unit delays. The operations are multiplies and are ALU operations, with the edges , , , , , , and . The frames are on the ASAP and ALAP page. The first distribution graphs are:
| step | 1 | 2 | 3 | 4 |
|---|---|---|---|---|
| 17/6 | 7/3 | 5/6 | 0 | |
| 1/3 | 1 | 2 | 5/3 |
For example, , from and , which must start at step 1, with frame , and with frame . Some first forces:
| operation | frame | force at each start in the frame |
|---|---|---|
| 1/4, −1 | ||
| 5/6, 11/18, −19/18 | ||
| −4/3, 0, 1/9 |
The force of at step 2 is its self force, , plus the force on , whose frame shrinks from to , . The sum is the least force of all, so line L11 fixes at step 2, and is fixed at step 1 in the next round. The next choices are at step 3 with force , and at step 2 with force . Then all frames have one step, and the schedule is
| step | multiplies | ALU operations |
|---|---|---|
| 1 | ||
| 2 | ||
| 3 | ||
| 4 |
It needs 2 multipliers and 2 ALUs. A search over all schedules shows that 4 units in total is the least for , so FDS is optimal here. At and , 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 exactly when some schedule that meets the fixed starts and starts 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 rounds and returns a schedule that meets all precedences and the latency bound . It reports "infeasible" exactly when 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 . 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 is a map with , for each edge , and . For a partial map of fixed starts, a schedule meets when for every in its domain. TIME-FRAMES computes, in topological order, , replaced by when is fixed and reported as a clash when . It computes in reverse order in the same way, with a clash when . It reports "infeasible" on a clash or when some .
Lemma 1 (frames bound every schedule). Every schedule for that meets has for all . So if TIME-FRAMES reports "infeasible", no such schedule exists.
Proof. By induction in topological order: and for each edge, so is at least the unfixed value of . If is fixed, , which is then at least that value, so no clash happens and . The upper bound is the same argument in reverse order. If a schedule exists, it lies in every frame, so no clash happens and .
Lemma 2 (the frame bounds are schedules). If TIME-FRAMES does not report "infeasible", then and are schedules for that meet .
Proof. For : , and for each edge, by construction when is free, and because that value when is fixed. For the latency, by construction, and . So is a schedule, and it meets since for fixed . For : for each edge, in the same way, , and .
Lemma 3 (frames are exact). If TIME-FRAMES does not report "infeasible", then for every and every with , some schedule for that meets has .
Proof. Let be the largest over the paths from to , with the sum of the delays of the vertices of , or if there is no path. Put . Then .
Precedence. For an edge , by Lemma 2, and when . So .
Upper bounds. For every edge , , so along a path from to , . Hence when . Also . So , and . Also .
Fixed starts. Let be fixed with . Then , since is set to , is set to , and the bounds do not clash. So .
Lemma 4 (the loop invariant). At the start of each round of line L3, TIME-FRAMES on the current did not report "infeasible", and every schedule that meets the current is a schedule for . In each round, every trial of line L8 succeeds, and the round adds at least one operation to .
Proof. At the first round, line L2 returned unless the frames exist. Line L4 fixes at where its frame is . By Lemma 1, every schedule that meets has , so the set of schedules that meet 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 is free, and its frame has at least one step. For each such and each in its frame, Lemma 3 gives a schedule that meets and has , so by Lemma 1 TIME-FRAMES on 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 , with frames that exist.
Theorem. If is less than the critical path length, FDS returns "infeasible" on line L2, and no schedule exists. Otherwise it stops after at most rounds and returns a schedule for . The output depends only on the input.
Proof. With empty, the frames are the ASAP and ALAP schedules. By the ASAP and ALAP correctness proof, they exist exactly when 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 rounds all operations are fixed, and line L5 returns . At that point, the frames exist, so by Lemma 3 some schedule meets . Since fixes every operation, that schedule is itself, and it is a schedule for . 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.
Complexity
There are at most rounds, since each one fixes an operation. A round has at most trials. A trial runs TIME-FRAMES in time and then sums over at most changed frames, each over steps for unit delays, so it costs . The total is time for unit delays, and space for the graph, the frames and the distribution graphs. Each delay adds a factor 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 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 , , , and , and . The first least force is , for at step 2. It forces and into step 1, and the final schedule needs 2 units. The schedule 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 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.
# 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
- 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
- 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.
| 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 CDK7W8 Edit this page History Report an error Markdown