Algorithmadvanced
Lamport hyperplane method
Finds a linear time function such that all iterations on one hyperplane can run in parallel, for loops with uniform dependences.
- Time
- O(D k + N k) worst
- Space
- O(k) extra
- Where
- D = the number of distance vectors; N = the number of iterations; k = the depth of the loop nest
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
The hyperplane method takes a perfect loop nest whose dependences have constant distance vectors and finds an integer time function with for every distance . All iterations with the same value of lie on one hyperplane, and no dependence joins two of them, so each hyperplane, a front, can run as one parallel step. The fronts run in increasing . The method completes to a unimodular matrix and rewrites the nest as an outer sequential loop over and inner loops that are all parallel, with bounds from Fourier-Motzkin elimination. Lamport introduced it in 1974 for the parallel computers of that time; the same fronts come out of loop skewing followed by interchange, and they are the wavefronts of a stencil.
In plain words
Picture a grid of tasks in which each task needs results from a few nearby tasks that come before it. You want to do many tasks at the same moment. Give each task a time: a weighted sum of its row and column numbers. Choose the weights so that every task's time is larger than the time of every task it needs. Then all tasks with the same time can run together, because none of them needs another one of them. On a grid, the tasks with the same time lie on a slanted line, and the lines sweep across the grid one after the other. The method gives a simple rule to pick the weights, starting from the innermost loop.
The problem
Input. A perfect nest of depth with iteration space , bounded, and a finite set of nonzero dependence distance vectors, each lexicographically positive. The body of one iteration runs as a unit.
Output. An integer vector with for every , and a rewritten nest that runs the fronts in increasing , each front as a parallel loop.
A dependence with a distance that is not constant, or a nest with statements between the loop headers, is outside the method. The distances come from a dependence test.
The algorithm
HYPERPLANE(space P = {i : A i + b >= 0}, distances D)- 1
pi_k <- 1 - 2
for l <- k - 1 down to 1 do - 3
need <- 0 - 4
for each d in D with d_1 = ... = d_(l-1) = 0 and d_l > 0 do - 5
rest <- pi_(l+1) d_(l+1) + ... + pi_k d_k - 6
need <- max(need, ceil((1 - rest) / d_l)) - 7
pi_l <- need - 8
T <- the matrix with rows pi, e_1, ..., e_(k-1) ▷ det T = +-1 - 9
for t <- tmin to tmax do ▷ bounds of y_1 by Fourier-Motzkin on {y : A T^(-1) y + b >= 0} - 10
parallel for (i_1, ..., i_(k-1)) in the bounds of front t do - 11
i_k <- t - (pi_1 i_1 + ... + pi_(k-1) i_(k-1)); BODY(i_1, ..., i_k)
Lines L1 to L7 build from the innermost loop outward. At level , the only distances that can still fix are those whose first nonzero entry is at ; for each of them, line L6 asks for the smallest with . Distances that lead at a deeper level already have their value, and distances that lead at an outer level will be fixed there. Line L8 adds the unit rows, which makes unimodular because . In the new coordinates , the first coordinate is the time and the others are , so line L11 recovers from . The bounds of lines L9 and L10 come from Fourier-Motzkin elimination of the constraints rewritten with .
Example
The stencil
for i = 1 to 4:
for j = 1 to 5:
A[i][j] = A[i-1][j] + A[i][j-1] + A[i-1][j+1]
has the distances , and . Line L1 sets . At , the distances that lead at level 1 are , with rest and need , and , with rest and need . So and . The three distances get . With , the inverse is and , and the bounds , give:
for t = 3 to 13:
parallel for i = max(1, ceil((t - 5) / 2)) to min(4, floor((t - 1) / 2)):
j = t - 2i
A[i][j] = A[i-1][j] + A[i][j-1] + A[i-1][j+1]
| front | front | ||
|---|---|---|---|
| 3 | (1,1) | 9 | (2,5), (3,3), (4,1) |
| 4 | (1,2) | 10 | (3,4), (4,2) |
| 5 | (1,3), (2,1) | 11 | (3,5), (4,3) |
| 6 | (1,4), (2,2) | 12 | (4,4) |
| 7 | (1,5), (2,3), (3,1) | 13 | (4,5) |
| 8 | (2,4), (3,2) |
The 20 iterations fall into 11 fronts, of at most 3 iterations each. In the front , the differences between the iterations are and , which are not distances, so the three iterations are independent. A brute-force search over finds no valid time function with fewer than 11 fronts for this nest.
Correctness
The full proof is in proofs/correctness.md. It has three steps.
The time function is valid. Take with first nonzero entry at level . If , then . Otherwise , where is the value of rest in line L5 for this , and line L6 gives , so . So a time function exists as soon as all distances are lexicographically positive, which every real dependence distance is.
The rewritten nest visits each iteration once, front by front. has determinant : moving its first row to the bottom gives a lower triangular matrix with ones on the diagonal. So is a bijection of the integer points, and the Fourier-Motzkin bounds scan the integer points of the transformed space exactly once, in lexicographic order, with outermost.
The fronts keep every dependence. A dependence from to has , so its sink is in a strictly later front. No dependence joins two iterations of one front, so they can run in any order or at the same time, and by Theorem 1 of the legality page the result equals that of the original nest.
Proof: The constructed time function puts every dependence between fronts, so the fronts can run in parallelfull
Setting
The nest has depth and iteration space , a bounded set. is a finite set of nonzero distance vectors, each lexicographically positive: for each there is a level with and . Every dependence of the nest goes from an iteration to the iteration for some , or stays inside one iteration. The body of one iteration runs as a unit, with its statements in text order.
The algorithm computes by lines L1 to L7:
with the inner maximum taken as when no leads at . It then forms the matrix with the rows (line L8) and runs the fronts in increasing , each front in any order or in parallel (lines L9 to L11).
Lemma 1: every distance gets a positive time difference
Claim. for every .
Proof. Let . Then , because the entries before are .
If , then with , and .
If , write . The values for are fixed before level is processed, so is the value that line L5 computes. Line L6 makes . Multiplying by gives , so .
So a time function exists whenever every distance is lexicographically positive, which holds for every real dependence. The construction also gives for all and .
Lemma 2: the matrix is unimodular
Claim. , and the inverse map is for and .
Proof. Move the first row of to the bottom. This is a cyclic permutation of the rows and changes the determinant by the factor . The result has the rows , which is lower triangular with diagonal , so its determinant is . Hence .
For the inverse: means and for . Then with , which gives the formula for . All coefficients are integers, so is an integer vector exactly when is.
So is a bijection from onto , and exactly when has first coordinate .
Lemma 3: the scan visits each iteration once, front by front
Claim. The nest of lines L9 to L11, with bounds from Fourier-Motzkin elimination, visits every point of exactly once, in lexicographic order of .
Proof. Let be the real projection of the real polyhedron of onto the coordinates . Fourier-Motzkin elimination of gives a system of inequalities whose real solution set is exactly . The loop at level runs, for fixed integers , over the integers with : its lower bound is the ceiling of the largest lower bound and its upper bound is the floor of the smallest upper bound. Every integer point of projects into each , so each of its coordinates is in the range of its loop, and the point is visited. At level the system is the original one, so a visited point satisfies all constraints of and is in . The loops run each coordinate in increasing order, so the points come in lexicographic order, and no point comes twice. A range can be empty for some outer values, when the real projection has no integer point above them; then the inner loop runs zero times, which loses nothing.
By Lemma 2, the visited correspond one to one to the iterations of , and the outer coordinate is constant on each front and increases from front to front.
Theorem: the fronts keep every dependence, and a front has none inside it
Claim. Run the fronts in increasing , and the iterations of each front in any order or at the same time. Then every dependence pair runs in its original order, two iterations of one front never depend on each other, and the final state equals the state of the original nest.
Proof. Take a dependence from iteration to iteration . Then for some , and by Lemma 1. So is in a strictly later front than , and the front of runs to completion first. In particular, no dependence joins two distinct iterations of one front, in either direction. A dependence inside one iteration keeps its order, because the body runs as a unit in text order.
Inside a front, the iterations touch disjoint sets of elements that any of them writes: if two of them touched one element and one wrote it, the one that runs first in the original order would be the source of a dependence to the other, which we just excluded. So any order or interleaving of the iterations of one front gives the same state after the front. By induction over the fronts, the state after each front is the state that the original nest has after running exactly the iterations of the fronts so far, in its own order; this follows from Theorem 1 of the loop transformation legality page, since every dependence pair keeps its order. After the last front, by Lemma 3, every iteration has run once, and the final states agree.
What the construction does not promise
The number of fronts is not minimal in general. The construction always sets , so that is unimodular with the simple inverse above. For the single distance on the box it gives , and all 16 iterations get different times, while , which is also valid, gives 4 fronts of 4 iterations. The correctness proof above holds for any integer with , given a scan of the fronts; only Lemma 2 uses .
Complexity
Building looks at each distance once, at its leading level, and computes rest in : time. The scan does work per iteration for the bounds and for , so in total. The Fourier-Motzkin elimination is done once for the nest; its cost depends on and on the number of constraints, not on or , and it can grow fast with , but loop nests are shallow. The extra space is for and the indices. The number of fronts is the number of distinct values of over , at most on a box with bounds , since every .
Properties
- Exact legality, no search. The construction always succeeds on lexicographically positive distances and needs no linear program.
- Nonnegative coefficients. Every and .
- One parallel level. The result has one sequential loop and parallel loops, with a barrier between fronts.
- Not minimal. The number of fronts is not always the smallest possible, as shown below.
Variants and improvements
- Fewer fronts. Choosing to minimize the number of fronts is an integer program: minimize the spread of over subject to . The construction can be far from it. For the single distance on the box , it gives and 16 fronts of one iteration, a sequential nest, while gives 4 fronts of 4 iterations: the inner loop is already parallel. The implementation contains a brute-force search over small for such comparisons. A real compiler solves a linear program with a rounding step, or an integer program in fixed dimension.
- Completion of any . When but the entries of have greatest common divisor 1, a unimodular completion still exists, through the Hermite normal form; unimodular transformations describes the code generation.
- Skewing and interchange. For two loops, is skewing by followed by interchange, as on the loop skewing page.
- Affine schedules. Allowing a different time function per statement, with a constant term, and dependences that are not uniform, gives the affine scheduling problem. Feautrier's scheduling solves it with linear programming, one dimension or several.
- Tiled wavefronts. On a fully permutable band, tiling first and then running the tiles by a time function gives fronts of tiles, with much less synchronization than fronts of single iterations.
When to use it
Use it for a perfect nest with uniform dependences in which no loop is parallel by itself, such as a Gauss-Seidel sweep or a dynamic programming table filled from its upper and left neighbours. The fronts give parallelism of about the size of a cross-section of the space. If some loop already carries no dependence, a DOALL loop over it is simpler and has no barriers. If the dependences are not uniform, or the nest is not perfect, use the polyhedral model. On machines where a barrier is expensive, tile first.
Pitfalls
- Floor instead of ceiling in line L6. With a floor, can be and two dependent iterations land in the same front.
- A wrong filter in line L4. Line L6 divides by , which is safe only when . A distance with must not enter line L6 at level : it leads at an outer level, and it gets its value there. Skipping a distance that does lead at leaves it without a check, and its can be or negative.
- A zero distance in . A dependence inside one iteration has and can never get . Line L4 must see only nonzero distances; the order inside the body is kept by running each iteration as a unit.
- Box bounds in lines L9 and L10. The fronts are slanted, so the bounds of the original loops are wrong for them. Copying them visits points outside the space or misses some.
- Sign of the last index in line L11. ; with a plus sign the body runs at the wrong iteration.
- Expecting balance. In the example, the first and last fronts have one iteration each. The parallel run takes at least one step per front, however many processors there are, and the small fronts near the corners leave most processors idle.
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/lamport-hyperplane-method/. The authors are listed in prov/RCRHT9.jsonl.
"""Lamport's hyperplane method for a perfect loop nest with constant distances.
A loop nest of depth k is given by its iteration space, a list of affine
constraints (a, b) that mean a . i + b >= 0, and by the list of its nonzero
dependence distance vectors. The method finds an integer time function pi
with pi . d >= 1 for every distance d. All iterations i with the same value
t = pi . i form one front; the fronts run in increasing t, and the
iterations of one front can run in parallel.
The code follows the page: time_function builds pi from the innermost
level outward (lines L1 to L7), hyperplane_matrix completes pi to a
unimodular matrix T (line L8), and wavefronts scans the transformed space
with Fourier-Motzkin bounds (lines L9 to L11).
"""
from fractions import Fraction
from itertools import product
from math import ceil, floor
def lex_positive(d):
"""True when the first nonzero entry of d is positive."""
for x in d:
if x != 0:
return x > 0
return False
def leading_level(d):
"""Index of the first nonzero entry of d."""
for l, x in enumerate(d):
if x != 0:
return l
raise ValueError("zero vector has no leading level")
def time_function(distances, k=None):
"""Return pi with pi[k-1] = 1, pi[l] >= 0 and pi . d >= 1 for every d.
Every distance must be lexicographically positive. Level l (from the
innermost outward) gets the smallest nonnegative pi[l] that makes
pi . d >= 1 for every d whose first nonzero entry is at l.
"""
distances = [tuple(d) for d in distances]
if k is None:
if not distances:
raise ValueError("give k when there are no distances")
k = len(distances[0])
for d in distances:
if len(d) != k:
raise ValueError("distance of the wrong length")
if not lex_positive(d):
raise ValueError("distance %r is not lexicographically positive" % (d,))
pi = [0] * k
pi[k - 1] = 1 # @line L1
for l in range(k - 2, -1, -1): # @line L2
need = 0 # @line L3
for d in distances: # @line L4
if leading_level(d) != l:
continue
rest = sum(pi[m] * d[m] for m in range(l + 1, k)) # @line L5
need = max(need, ceil(Fraction(1 - rest, d[l]))) # @line L6
pi[l] = need # @line L7
return pi
def check_time_function(pi, distances):
"""True when pi . d >= 1 for every distance d."""
return all(sum(p * x for p, x in zip(pi, d)) >= 1 for d in distances)
def hyperplane_matrix(pi):
"""Rows pi, e_1, ..., e_{k-1}: unimodular when pi[k-1] = 1."""
k = len(pi)
if pi[k - 1] != 1:
raise ValueError("the last entry of pi must be 1")
rows = [list(pi)] + [[1 if c == l else 0 for c in range(k)] for l in range(k - 1)] # @line L8
return rows
def inverse_map(pi, y):
"""The iteration i with T i = y, for T = hyperplane_matrix(pi)."""
k = len(pi)
i = [0] * k
for l in range(k - 1):
i[l] = y[l + 1]
i[k - 1] = y[0] - sum(pi[l] * y[l + 1] for l in range(k - 1)) # @line L11
return tuple(i)
def box(bounds):
"""Constraints of the box lo_l <= i_l <= hi_l."""
k = len(bounds)
cons = []
for l, (lo, hi) in enumerate(bounds):
e = [0] * k
e[l] = 1
cons.append((tuple(e), -lo))
cons.append((tuple(-x for x in e), hi))
return cons
def _norm(cons):
return [(tuple(Fraction(x) for x in a), Fraction(b)) for a, b in cons]
def _eliminate(cons, v):
"""Fourier-Motzkin: remove variable v from the constraints."""
pos = [c for c in cons if c[0][v] > 0]
neg = [c for c in cons if c[0][v] < 0]
out = [c for c in cons if c[0][v] == 0]
for ap, bp in pos:
for an, bn in neg:
sp, sn = -an[v], ap[v]
a = tuple(sp * x + sn * y for x, y in zip(ap, an))
out.append((a, sp * bp + sn * bn))
seen, res = set(), []
for c in out:
if c not in seen:
seen.add(c)
res.append(c)
return res
def scan(constraints, k):
"""All integer points of {y : a . y + b >= 0}, in lexicographic order.
The space must be bounded. Level v uses the constraints with the
variables after v eliminated, so its bounds are exact for real points;
an empty inner range makes the recursion skip the outer value.
"""
levels = [None] * k
cur = _norm(constraints)
for v in range(k - 1, -1, -1):
levels[v] = [c for c in cur if any(x != 0 for x in c[0][:v + 1]) or c[1] < 0]
cur = _eliminate(cur, v)
if any(b < 0 for a, b in cur):
return
y = [0] * k
def rec(v):
lo, hi = None, None
for a, b in levels[v]:
s = b + sum(a[u] * y[u] for u in range(v))
if a[v] > 0:
t = ceil(-s / a[v])
lo = t if lo is None else max(lo, t)
elif a[v] < 0:
t = floor(s / -a[v])
hi = t if hi is None else min(hi, t)
elif s < 0:
return
if lo is None or hi is None:
raise ValueError("the space is not bounded")
for x in range(lo, hi + 1):
y[v] = x
if v == k - 1:
yield tuple(y)
else:
yield from rec(v + 1)
yield from rec(0)
def wavefronts(constraints, k, pi):
"""List of (t, front) in increasing t; front lists the iterations with pi . i = t.
The space {i : a . i + b >= 0} is mapped by T = hyperplane_matrix(pi),
i = S y, so a constraint becomes (a S) . y + b >= 0. The scan in y
runs y_1 = t outermost (L9); inside a front, i_1, ..., i_{k-1} are
the remaining loops (L10) and i_k is computed (L11).
"""
hyperplane_matrix(pi)
# Columns of S = T^{-1}: i_l = y_{l+1} for l < k - 1, i_{k-1} = y_0 - sum pi_l y_{l+1}.
S = [[0] * k for _ in range(k)]
for l in range(k - 1):
S[l][l + 1] = 1
S[k - 1][0] = 1
for l in range(k - 1):
S[k - 1][l + 1] = -pi[l]
ycons = []
for a, b in constraints:
ay = tuple(sum(a[r] * S[r][c] for r in range(k)) for c in range(k))
ycons.append((ay, b))
fronts = []
for y in scan(ycons, k):
i = inverse_map(pi, y)
if fronts and fronts[-1][0] == y[0]:
fronts[-1][1].append(i) # @line L10
else:
fronts.append((y[0], [i])) # @line L9
return fronts
def fewest_fronts(distances, points, max_coeff=3):
"""Brute-force search over pi in [0, max_coeff]^k with pi . d >= 1.
Returns (number of fronts, pi) with the fewest distinct values of
pi . i over the given points. A comparison tool for small nests, not
part of Lamport's method.
"""
points = list(points)
k = len(points[0])
best = None
for pi in product(range(max_coeff + 1), repeat=k):
if not check_time_function(pi, distances):
continue
n = len({sum(p * x for p, x in zip(pi, i)) for i in points})
if best is None or n < best[0]:
best = (n, list(pi))
return best
test_lamport_hyperplane_method.py 249 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lamport-hyperplane-method/. The authors are listed in prov/RCRHT9.jsonl.
import random
from fractions import Fraction
from itertools import product
from lamport_hyperplane_method import (
box,
check_time_function,
fewest_fronts,
hyperplane_matrix,
inverse_map,
lex_positive,
scan,
time_function,
wavefronts,
)
# A nest: k, constraints, and statements. A statement is (write, reads);
# an access is (array, offsets) and touches array[i + offsets].
def points_of(constraints, k, bounds):
"""Brute-force list of the integer points of the space, in lexicographic order."""
pts = []
for i in product(*[range(lo, hi + 1) for lo, hi in bounds]):
if all(sum(a * x for a, x in zip(ai, i)) + b >= 0 for ai, b in constraints):
pts.append(i)
return pts
def elem(acc, i):
return (acc[0], tuple(x + o for x, o in zip(i, acc[1])))
def instances(points, stmts):
"""Statement instances in the original order: (iteration, statement index)."""
return [(i, s) for i in points for s in range(len(stmts))]
def true_dependences(points, stmts):
"""All pairs (source, sink) of instances that touch one element, one of them a write."""
inst = instances(points, stmts)
deps = []
for x in range(len(inst)):
i, s = inst[x]
w1 = elem(stmts[s][0], i)
r1 = {elem(r, i) for r in stmts[s][1]}
for y in range(x + 1, len(inst)):
j, t = inst[y]
w2 = elem(stmts[t][0], j)
r2 = {elem(r, j) for r in stmts[t][1]}
if w1 == w2 or w1 in r2 or w2 in r1:
deps.append((inst[x], inst[y]))
return deps
def start_value(e):
name, idx = e
return (ord(name) % 7 + 3 * sum((p + 2) * v for p, v in enumerate(idx))) % 101
def run(order, stmts):
"""Run the iterations in the given order; each iteration runs its statements in text order."""
mem = {}
for i in order:
for s, (w, reads) in enumerate(stmts):
vals = [mem.get(elem(r, i), start_value(elem(r, i))) for r in reads]
mem[elem(w, i)] = (sum((n + 1) * v for n, v in enumerate(vals)) * 3 + s + 1) % 1000003
return mem
def random_nest(rnd, k):
bounds = [(rnd.randint(0, 2), 0) for _ in range(k)]
bounds = [(lo, lo + rnd.randint(1, 3)) for lo, _ in bounds]
cons = box(bounds)
if k >= 2 and rnd.random() < 0.4:
# A triangular space: i_1 - i_0 + c >= 0.
a = [0] * k
a[0], a[1] = -1, 1
cons.append((tuple(a), rnd.randint(0, 2)))
stmts = []
for _ in range(rnd.randint(1, 2)):
arr = rnd.choice("AB")
w = (arr, tuple(0 for _ in range(k)))
reads = []
for _ in range(rnd.randint(1, 3)):
reads.append((rnd.choice("AB"), tuple(rnd.randint(-2, 1) for _ in range(k))))
stmts.append((w, reads))
return bounds, cons, stmts
def distances_of(deps):
out = set()
for (i, _), (j, _) in deps:
d = tuple(b - a for a, b in zip(i, j))
if any(d):
out.add(d)
return sorted(out)
def det(m):
m = [[Fraction(x) for x in row] for row in m]
n, s = len(m), Fraction(1)
for c in range(n):
p = next((r for r in range(c, n) if m[r][c] != 0), None)
if p is None:
return Fraction(0)
if p != c:
m[c], m[p] = m[p], m[c]
s = -s
s *= m[c][c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
m[r] = [x - f * y for x, y in zip(m[r], m[c])]
return s
def test_stencil_example():
# A[i][j] = A[i-1][j] + A[i][j-1] + A[i-1][j+1] has distances (1,0), (0,1), (1,-1).
D = [(1, 0), (0, 1), (1, -1)]
pi = time_function(D)
assert pi == [2, 1]
fr = wavefronts(box([(1, 4), (1, 5)]), 2, pi)
assert len(fr) == 11
assert [t for t, _ in fr] == list(range(3, 14))
assert fr[0][1] == [(1, 1)]
assert sorted(p for _, f in fr for p in f) == points_of(box([(1, 4), (1, 5)]), 2, [(1, 4), (1, 5)])
def test_construction_on_random_distances():
rnd = random.Random(11)
for _ in range(400):
k = rnd.randint(1, 4)
D = []
for _ in range(rnd.randint(1, 5)):
while True:
d = tuple(rnd.randint(-3, 3) for _ in range(k))
if lex_positive(d):
break
D.append(d)
pi = time_function(D)
assert pi[-1] == 1 and all(p >= 0 for p in pi)
assert check_time_function(pi, D)
# Each entry is as small as the construction allows: lowering one outer
# entry by 1 breaks some distance that leads at that level.
for l in range(k - 1):
if pi[l] > 0:
q = list(pi)
q[l] -= 1
leading_here = [d for d in D if d[l] != 0 and not any(d[:l])]
assert not check_time_function(q, leading_here)
T = hyperplane_matrix(pi)
assert abs(det(T)) == 1
for _ in range(5):
y = tuple(rnd.randint(-5, 5) for _ in range(k))
i = inverse_map(pi, y)
assert tuple(sum(a * x for a, x in zip(row, i)) for row in T) == y
def test_rejects_bad_distances():
for D in ([(0, 0)], [(-1, 2)], [(0, -1)]):
try:
time_function(D)
except ValueError:
pass
else:
raise AssertionError("accepted %r" % (D,))
def test_scan_matches_brute_force():
rnd = random.Random(5)
for _ in range(150):
k = rnd.randint(1, 3)
bounds, cons, _ = random_nest(rnd, k)
assert list(scan(cons, k)) == points_of(cons, k, bounds)
def check_schedule(fronts, points, deps):
"""Fronts cover every point once, and every dependence goes to a later front."""
flat = [p for _, f in fronts for p in f]
assert sorted(flat) == sorted(points) and len(flat) == len(set(flat))
ts = [t for t, _ in fronts]
assert ts == sorted(set(ts))
when = {p: t for t, f in fronts for p in f}
ok_order = all(when[i] < when[j] or i == j for (i, _), (j, _) in deps)
no_inner = all(when[i] != when[j] or i == j for (i, _), (j, _) in deps)
return ok_order and no_inner
def test_random_nests_legal_and_parallel_fronts():
rnd = random.Random(2024)
tried = 0
while tried < 120:
k = rnd.randint(1, 3)
bounds, cons, stmts = random_nest(rnd, k)
points = points_of(cons, k, bounds)
if not points:
continue
tried += 1
deps = true_dependences(points, stmts)
D = distances_of(deps)
pi = time_function(D, k)
fronts = wavefronts(cons, k, pi)
for t, f in fronts:
assert all(sum(p * x for p, x in zip(pi, i)) == t for i in f)
# Legality and no dependence between two points of one front.
assert check_schedule(fronts, points, deps)
# Running each front in a random order gives the original final state.
want = run(points, stmts)
for rep in range(3):
order = []
for _, f in fronts:
g = list(f)
rnd.shuffle(g)
order.extend(g)
assert run(order, stmts) == want
# The brute-force best pi never needs more fronts than the construction.
best = fewest_fronts(D, points, 3)
assert best is not None and best[0] <= len(fronts)
assert check_time_function(best[1], D)
def test_checker_rejects_a_bad_time_function():
# Columns of the stencil (pi = (0, 1)) put (1, 2) and (2, 1) in one front,
# though (2, 1) reads A[1][2].
stmts = [(("A", (0, 0)), [("A", (-1, 0)), ("A", (0, -1)), ("A", (-1, 1))])]
cons = box([(1, 3), (1, 3)])
points = points_of(cons, 2, [(1, 3), (1, 3)])
deps = true_dependences(points, stmts)
assert distances_of(deps) == [(0, 1), (1, -1), (1, 0)]
bad = {}
for i in points:
bad.setdefault(i[1], []).append(i)
fronts = sorted(bad.items())
assert not check_schedule(fronts, points, deps)
order = [p for _, f in fronts for p in f]
assert run(order, stmts) != run(points, stmts)
if __name__ == "__main__":
test_stencil_example()
test_construction_on_random_distances()
test_rejects_bad_distances()
test_scan_matches_brute_force()
test_random_nests_legal_and_parallel_fronts()
test_checker_rejects_a_bad_time_function()
print("ok")
History
Leslie Lamport's 1974 paper in the Communications of the ACM studied when the iterations of a Fortran DO loop nest can run at the same time on a parallel or array machine. It gave two methods. The coordinate method finds a loop whose iterations can run in parallel. The hyperplane method finds a linear function of the loop indices whose level sets, hyperplanes in the iteration space, can run in parallel, and it changes the loop indices so that this function becomes the outer loop. Michael Wolfe showed in 1986 that the same wavefronts come from loop skewing followed by loop interchange, which put the method into the vocabulary of restructuring compilers. Wolf and Lam in 1991 described it as a unimodular transformation whose first row has a positive product with every dependence vector. Feautrier's work on affine schedules in 1992 generalized it to non-uniform dependences and one time function per statement.
References
- Leslie Lamport, The parallel execution of DO loops, Communications of the ACM 17(2), 1974, 83-93, the hyperplane method (a linear function of the loop indices whose level sets can run at the same time, and the change of loop indices that makes it the outer loop) and the coordinate method
- Michael Wolfe, Loop skewing, the wavefront method revisited, International Journal of Parallel Programming 15(4), 1986, 279-293, the wavefront method obtained as loop skewing followed by loop interchange, and its relation to Lamport's hyperplanes
- Michael E. Wolf and Monica S. Lam, A loop transformation theory and an algorithm to maximize parallelism, IEEE Transactions on Parallel and Distributed Systems 2(4), 1991, 452-471, wavefront transformations as unimodular matrices whose first row has a positive product with every dependence vector, and the completion of that row to a unimodular matrix
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 RCRHT9 Edit this page History Report an error Markdown