Algorithmintro
ASAP and ALAP scheduling
Also called as soon as possible scheduling, as late as possible scheduling, operation mobility.
Schedules each operation of a data flow graph at its earliest or latest step under precedence, which gives the mobility of each operation.
- Solves
- High-level synthesis
- Time
- O(V + E) worst
- Space
- O(V + E) extra
- Where
- E = the number of data edges; V = the number of operations
- Model
- Word RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- James E. Kelley Jr., Morgan R. Walker, 1959
ASAP and ALAP scheduling give each operation of a data flow graph a start step when there is no limit on the number of functional units. The as soon as possible (ASAP) schedule starts every operation at the first step after all its inputs are ready. The as late as possible (ALAP) schedule starts every operation at the last step that still lets all the operations after it end by a latency bound . Both schedules are one pass of a DAG longest path computation in topological order, so each takes time. The difference ALAP minus ASAP is the mobility of an operation, and the interval between them is its time frame. High-level synthesis uses the ASAP schedule for the least latency, and uses the time frames as the input of resource-constrained schedulers such as force-directed scheduling.
In plain words
A program for hardware is a set of operations, such as multiplies and adds. Some operations need the result of others. A clock step is the unit of time, and each operation takes one or more steps. If you have as many adders and multipliers as you want, you can start each operation as soon as its inputs are ready. That is the ASAP schedule, and its length is the shortest possible. If you must finish by some step, you can also start each operation as late as possible, so that the work after it still fits. That is the ALAP schedule. An operation whose two start steps are the same is on the critical path and has no freedom. An operation with a gap between them can move inside that gap.
The problem
The input is a data flow graph with no cycles. Each operation has a delay in control steps. An edge means that reads the result of , so a schedule must have . Operation uses the steps to . The schedule meets the latency bound when for all . The output is the ASAP schedule , the ALAP schedule for a given , and the mobility . The algorithm has no limit on the number of units. With such a limit, the problem is NP-hard (see the high-level synthesis page).
The algorithm
ASAP(G, δ)- 1
order ← a topological order of G ▷ fails if G has a cycle - 2
for each v in order do - 3
t_S(v) ← max(1, max over edges (u, v) of t_S(u) + δ(u)) - 4
return t_S ALAP(G, δ, L)- 5
for each v in the reverse of order do - 6
t_L(v) ← min(L + 1, min over edges (v, w) of t_L(w)) - δ(v) - 7
if t_L(v) < 1 for some v then return "infeasible" - 8
return t_L MOBILITY(G, δ, L)- 9
return t_L(v) - t_S(v) for each v
Line L3 takes the latest end of an input, so is the largest total delay of a path that ends just before . Line L6 is the mirror image: is the largest total delay of a path that starts at , with counted. The value on line L6 stands for a sink after the last step. Line L7 fails exactly when is less than the length of the critical path.
Example
Take the differential equation example of Paulin and Knight, one loop step of a solver for . It has six multiplies and five ALU operations, all with delay 1. With , one loop step computes , , , and the test .
| op | computes | ASAP | ALAP at | mobility |
|---|---|---|---|---|
| 1 | 1 | 0 | ||
| 1 | 1 | 0 | ||
| 2 | 2 | 0 | ||
| 3 | 3 | 0 | ||
| 4 | 4 | 0 | ||
| 1 | 2 | 1 | ||
| 2 | 3 | 1 | ||
| 1 | 3 | 2 | ||
| 2 | 4 | 2 | ||
| 1 | 3 | 2 | ||
| 2 | 4 | 2 |
The ASAP schedule ends at step 4, so the least latency is 4, and the chain is critical. At , line L6 gives , and ALAP reports "infeasible". At , every mobility grows by 2: the five critical operations get mobility 2, and get 3, and the rest get 4. The ASAP schedule puts four multiplies at step 1, while the ALAP schedule at puts three ALU operations at step 4. Neither is a good use of hardware, which is why resource-constrained schedulers move the operations inside their frames.
A multicycle case. A multiply of delay 2 feeds an add, and a second add stands alone. ASAP gives the starts and a latency of 3. At , ALAP gives . At , it gives . At , it fails.
Correctness
Every schedule that meets starts each operation between its ASAP and its ALAP step, by induction along the topological order for the lower bound and along the reverse order for the upper bound. Both and are themselves schedules, so they are the earliest and the latest schedule, one operation at a time. The time frame is exact: for every step with , some schedule that meets starts at . The ASAP schedule has latency equal to the critical path length, and line L7 fails exactly when is smaller. The full proof gives the details.
Proof: ASAP and ALAP are the pointwise earliest and latest schedules, and the frames are exactfull
We use the notation of the page. has no cycle, every , and a schedule for is a map with , for every edge , and for every .
For a path , let . Let be the largest over paths that end at , and let be the largest over paths that start at . The one-vertex path gives and . The critical path length is , which is also .
Lemma 1 (closed forms). Lines L1 to L4 give . Lines L5 and L6 give .
Proof. Line L1 succeeds because has no cycle. In topological order, all predecessors of are done before . By induction, line L3 gives . A longest path ending at is either alone, with , or a longest path ending at a predecessor followed by the edge , with . So the right side is . The ALAP case is the same argument on the reverse graph: line L6 gives .
Lemma 2 (bounds). Every schedule for has for every .
Proof. Let end at . The edges give , so . Taking the largest such path gives . Now let start at . In the same way , and , so . Taking the largest path gives .
Lemma 3 (both are schedules). is a schedule for every , with latency exactly . is a schedule for exactly when , and line L7 fails exactly when .
Proof. Line L3 gives and for every edge. The last step used is by Lemma 1. Line L6 gives for every edge , and . So meets all conditions except possibly . By Lemma 1, , which is at least 1 exactly when . If , no schedule exists at all, since a schedule has latency at least that of by Lemma 2.
Theorem 1. If , and are schedules for , and for every , is the least and is the largest value of over all schedules for . If , ALAP returns "infeasible" and no schedule exists. Line L9 returns .
Proof. Lemmas 2 and 3. The mobility is nonnegative because is a schedule and Lemma 2 applies to it.
Theorem 2 (the frames are exact). Let , let be an operation and let . Then some schedule for has .
Proof. For each , let be the largest over paths from to , or if there is none. So . Put . Then .
Precedence. Let be an edge. Then by line L3. If , the path to followed by the edge gives . So both terms of are at least the matching term of plus , and .
Range. . For the latency, by Theorem 1. If , take a path from to with . Then , because followed by a longest path from is a path from . So . In both cases , so .
Fixed starts. The variant on the page with fixed starts is the same pair of passes with extra lower and upper bounds on some operations. The correctness proof of force-directed scheduling shows that its frames are exact too.
Termination. Each line runs over a finite list, and no line repeats.
Complexity
Line L1 is Kahn's algorithm in time. Lines L2 and L3 look at each edge once, from its head, and lines L5 and L6 look at each edge once, from its tail. So each schedule takes time and space for the adjacency lists. Mobility costs one ASAP and one ALAP pass. A new latency bound needs only a new ALAP pass.
Properties
- Exact. Both schedules are optimal for what they compute, and the result is fully determined by the graph, the delays and .
- Pointwise extremes. No schedule starts an operation earlier than ASAP or later than ALAP.
- No resources. The schedules can use any number of units in one step. The number of units that they need is only a result.
- Shift with . Raising by raises every ALAP step by and leaves ASAP unchanged.
Variants and improvements
- Fixed starts. If some operations must start at given steps, apply the same two passes with raised to the fixed value and lowered to it. This is how force-directed scheduling updates the frames after each decision, and the frames stay exact.
- Chaining. If several fast operations fit into one step, the passes work on delays in time units and pack them into steps with a cycle time, as in static timing analysis.
- Timing constraints. Minimum and maximum distances between operations give a graph with cycles. Then the earliest starts are longest paths in a graph with no positive cycle, computed by Bellman-Ford style relaxation.
- List scheduling. List scheduling adds unit limits and uses the mobility, or the ALAP step, as the priority of the ready operations.
When to use it
Use ASAP to find the least latency of a data flow graph, and ALAP to find how much each operation can move under a latency bound. Use both as the first step of a resource-constrained scheduler, to bound the search, to order the operations, or to fix the critical ones. Do not use the ASAP or ALAP schedule as the final schedule when the number of units matters.
Pitfalls
- Off by one. With steps numbered from 1 and using to , the ALAP start is minus the path delay from . Many write-ups use steps from 0, and mixing the two forms gives a frame that is one step off.
- Cycles. A data flow graph of a loop body has a back edge from one iteration to the next. Remove it, or treat it as a timing constraint, before the passes, or the topological order does not exist.
- Infeasible bound. If is less than the critical path length, the ALAP formula gives starts below 1. Check for this, as line L7 does, and do not use those values.
- Mobility is not freedom of all operations at once. Two operations on one path can each move within their frames, but not always at the same time. Moving one may shrink the frame of the other.
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/asap-alap-scheduling/. The authors are listed in prov/5S0Z4R.jsonl.
"""ASAP and ALAP schedules of a data flow graph.
Operations are 0 .. n-1. Operation v takes delay[v] >= 1 control steps.
An edge (u, v) says that v reads the result of u, so v may start only
after u ends: t(v) >= t(u) + delay[u]. Steps are numbered from 1, and an
operation that starts at step t uses the steps t .. t + delay[v] - 1.
A schedule meets the latency bound L when every operation ends by step L.
"""
from typing import Optional
def topological_order(n: int, edges: list[tuple[int, int]]) -> list[int]:
"""Kahn's algorithm. Raises ValueError on a cycle."""
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 asap(n: int, delay: list[int], edges: list[tuple[int, int]]) -> list[int]:
"""The earliest start step of each operation."""
pred: list[list[int]] = [[] for _ in range(n)]
for (u, v) in edges:
pred[v].append(u)
t = [0] * n
order = topological_order(n, edges) # @line L1
for v in order: # @line L2
t[v] = max([1] + [t[u] + delay[u] for u in pred[v]]) # @line L3
return t # @line L4
def alap(n: int, delay: list[int], edges: list[tuple[int, int]], latency: int) -> Optional[list[int]]:
"""The latest start step of each operation with every operation done by
step latency. None if the latency is shorter than the critical path."""
succ: list[list[int]] = [[] for _ in range(n)]
for (u, v) in edges:
succ[u].append(v)
t = [0] * n
order = topological_order(n, edges)
for v in reversed(order): # @line L5
t[v] = min([latency + 1] + [t[w] for w in succ[v]]) - delay[v] # @line L6
if any(x < 1 for x in t): # @line L7
return None
return t # @line L8
def latency_of(start: list[int], delay: list[int]) -> int:
"""The last step that the schedule uses."""
return max((s + dl - 1 for s, dl in zip(start, delay)), default=0)
def mobility(n: int, delay: list[int], edges: list[tuple[int, int]], latency: int) -> Optional[list[int]]:
"""ALAP minus ASAP for each operation, or None if the latency is too short."""
late = alap(n, delay, edges, latency)
if late is None:
return None
early = asap(n, delay, edges)
return [b - a for a, b in zip(early, late)] # @line L9
test_asap_alap_scheduling.py 113 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/asap-alap-scheduling/. The authors are listed in prov/5S0Z4R.jsonl.
import itertools
import random
import pytest
from asap_alap_scheduling import alap, asap, latency_of, mobility, topological_order
# The differential equation example (Paulin and Knight): v1 .. v11 are 0 .. 10.
DIFFEQ_N = 11
DIFFEQ_EDGES = [(0, 2), (1, 2), (2, 3), (3, 4), (5, 6), (6, 4), (7, 8), (9, 10)]
def random_dag(rng, n, p=0.35, most=3):
delay = [rng.randint(1, most) for _ in range(n)]
edges = [(u, v) for u in range(n) for v in range(u + 1, n) if rng.random() < p]
perm = list(range(n))
rng.shuffle(perm) # hide the numbering order from the code under test
return delay_perm(delay, perm), [(perm[u], perm[v]) for (u, v) in edges]
def delay_perm(delay, perm):
out = [0] * len(delay)
for i, x in enumerate(delay):
out[perm[i]] = x
return out
def longest_from_sources(n, delay, edges, v):
"""The largest delay sum of a path that ends just before v, by walking all paths."""
pred = [[] for _ in range(n)]
for (a, b) in edges:
pred[b].append(a)
return max([0] + [delay[u] + longest_from_sources(n, delay, edges, u) for u in pred[v]])
def longest_to_sinks(n, delay, edges, v):
"""The largest delay sum of a path that starts at v, with v."""
succ = [[] for _ in range(n)]
for (a, b) in edges:
succ[a].append(b)
return delay[v] + max([0] + [longest_to_sinks(n, delay, edges, w) for w in succ[v]])
def feasible_schedules(n, delay, edges, latency):
for t in itertools.product(range(1, latency + 1), repeat=n):
if all(t[v] >= t[u] + delay[u] for (u, v) in edges) and latency_of(list(t), delay) <= latency:
yield t
def test_diffeq():
d = [1] * DIFFEQ_N
assert asap(DIFFEQ_N, d, DIFFEQ_EDGES) == [1, 1, 2, 3, 4, 1, 2, 1, 2, 1, 2]
assert alap(DIFFEQ_N, d, DIFFEQ_EDGES, 4) == [1, 1, 2, 3, 4, 2, 3, 3, 4, 3, 4]
assert mobility(DIFFEQ_N, d, DIFFEQ_EDGES, 4) == [0, 0, 0, 0, 0, 1, 1, 2, 2, 2, 2]
assert alap(DIFFEQ_N, d, DIFFEQ_EDGES, 3) is None
assert mobility(DIFFEQ_N, d, DIFFEQ_EDGES, 6) == [2] * 5 + [3, 3, 4, 4, 4, 4]
def test_multicycle():
# a two-step multiply feeds an add; a lone add can go anywhere
delay = [2, 1, 1]
edges = [(0, 1)]
assert asap(3, delay, edges) == [1, 3, 1]
assert alap(3, delay, edges, 3) == [1, 3, 3]
assert alap(3, delay, edges, 5) == [3, 5, 5]
assert alap(3, delay, edges, 2) is None
assert latency_of(asap(3, delay, edges), delay) == 3
def test_cycle_rejected():
with pytest.raises(ValueError):
topological_order(3, [(0, 1), (1, 2), (2, 0)])
with pytest.raises(ValueError):
asap(2, [1, 1], [(0, 1), (1, 0)])
def test_against_longest_paths():
rng = random.Random(5301)
for _ in range(300):
n = rng.randint(1, 9)
delay, edges = random_dag(rng, n)
early = asap(n, delay, edges)
cp = latency_of(early, delay)
assert cp == max(longest_to_sinks(n, delay, edges, v) for v in range(n))
for v in range(n):
assert early[v] == 1 + longest_from_sources(n, delay, edges, v)
assert alap(n, delay, edges, cp - 1) is None
for latency in (cp, cp + 2):
late = alap(n, delay, edges, latency)
for v in range(n):
assert late[v] == latency + 1 - longest_to_sinks(n, delay, edges, v)
assert latency_of(late, delay) == latency
def test_extremes_of_all_schedules():
rng = random.Random(5302)
for _ in range(120):
n = rng.randint(1, 5)
delay, edges = random_dag(rng, n, most=2)
early = asap(n, delay, edges)
cp = latency_of(early, delay)
for latency in (cp, cp + 1):
late = alap(n, delay, edges, latency)
sched = list(feasible_schedules(n, delay, edges, latency))
assert tuple(early) in sched and tuple(late) in sched
for v in range(n):
starts = {t[v] for t in sched}
# the frame [ASAP, ALAP] is exactly the set of starts that some schedule uses
assert starts == set(range(early[v], late[v] + 1))
assert not list(feasible_schedules(n, delay, edges, cp - 1))
History
The earliest and latest start times of the jobs of a project are the forward and backward passes of the critical path method of Kelley and Walker (1959), and the slack of a job is the mobility of this page. High-level synthesis of the 1980s used the ASAP schedule for the least latency and the ALAP schedule as a priority. Paulin and Knight (1989) used the interval between the two as the time frame of an operation, the base of force-directed scheduling. De Micheli's book (1994) presents both schedules as scheduling without resource constraints.
References
- Giovanni De Micheli, Synthesis and Optimization of Digital Circuits, McGraw-Hill, 1994, Chapter 5, Scheduling Algorithms (the sections on scheduling without resource constraints, ASAP and ALAP, and mobility)
- 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 of the operations from the ASAP and ALAP schedules, and the differential equation example
- James E. Kelley Jr. and Morgan R. Walker, Critical-path planning and scheduling, Papers presented at the Eastern Joint IRE-AIEE-ACM Computer Conference, December 1959, the earliest and latest start times of the jobs of a project (general locator)
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 5S0Z4R Edit this page History Report an error Markdown