Algorithm Search⌘K

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
Properties
deterministiciterative

The hyperplane method takes a perfect loop nest whose dependences have constant distance vectors and finds an integer time function t(i)=π⋅it(i) = \pi \cdot i with π⋅d≥1\pi \cdot d \ge 1 for every distance dd. All iterations with the same value of tt 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 tt. The method completes π\pi to a unimodular matrix TT and rewrites the nest as an outer sequential loop over tt 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 kk with iteration space P={i∈Zk:Ai+b≥0}P = \{i \in \mathbb{Z}^k : A i + b \ge 0\}, bounded, and a finite set DD of nonzero dependence distance vectors, each lexicographically positive. The body of one iteration runs as a unit.

Output. An integer vector π\pi with π⋅d≥1\pi \cdot d \ge 1 for every d∈Dd \in D, and a rewritten nest that runs the fronts Ft={i∈P:π⋅i=t}F_t = \{i \in P : \pi \cdot i = t\} in increasing tt, 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

  1. HYPERPLANE(space P = {i : A i + b >= 0}, distances D)
  2. 1pi_k <- 1
  3. 2for l <- k - 1 down to 1 do
  4. 3need <- 0
  5. 4for each d in D with d_1 = ... = d_(l-1) = 0 and d_l > 0 do
  6. 5rest <- pi_(l+1) d_(l+1) + ... + pi_k d_k
  7. 6need <- max(need, ceil((1 - rest) / d_l))
  8. 7pi_l <- need
  9. 8T <- the matrix with rows pi, e_1, ..., e_(k-1) ▷ det T = +-1
  10. 9for t <- tmin to tmax do ▷ bounds of y_1 by Fourier-Motzkin on {y : A T^(-1) y + b >= 0}
  11. 10parallel for (i_1, ..., i_(k-1)) in the bounds of front t do
  12. 11i_k <- t - (pi_1 i_1 + ... + pi_(k-1) i_(k-1)); BODY(i_1, ..., i_k)

Lines L1 to L7 build π\pi from the innermost loop outward. At level ll, the only distances that πl\pi_l can still fix are those whose first nonzero entry is at ll; for each of them, line L6 asks for the smallest πl\pi_l with πldl+rest≥1\pi_l d_l + \text{rest} \ge 1. 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 TT unimodular because πk=1\pi_k = 1. In the new coordinates y=Tiy = T i, the first coordinate is the time and the others are i1,…,ik−1i_1, \dots, i_{k-1}, so line L11 recovers iki_k from tt. The bounds of lines L9 and L10 come from Fourier-Motzkin elimination of the constraints rewritten with i=T−1yi = T^{-1} y.

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 (1,0)(1, 0), (0,1)(0, 1) and (1,−1)(1, -1). Line L1 sets π2=1\pi_2 = 1. At l=1l = 1, the distances that lead at level 1 are (1,0)(1, 0), with rest 00 and need ⌈1/1⌉=1\lceil 1/1 \rceil = 1, and (1,−1)(1, -1), with rest −1-1 and need ⌈2/1⌉=2\lceil 2/1 \rceil = 2. So π=(2,1)\pi = (2, 1) and t=2i+jt = 2i + j. The three distances get π⋅d=2,1,1\pi \cdot d = 2, 1, 1. With T=(2110)T = \begin{pmatrix} 2 & 1 \\ 1 & 0 \end{pmatrix}, the inverse is i=y2i = y_2 and j=t−2y2j = t - 2 y_2, and the bounds 1≤i≤41 \le i \le 4, 1≤t−2i≤51 \le t - 2i \le 5 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]
tt front tt 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 t=7t = 7, the differences between the iterations are (1,−2)(1, -2) and (2,−4)(2, -4), which are not distances, so the three iterations are independent. A brute-force search over π∈{0,…,4}2\pi \in \{0, \dots, 4\}^2 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 d∈Dd \in D with first nonzero entry at level ll. If l=kl = k, then π⋅d=dk≥1\pi \cdot d = d_k \ge 1. Otherwise π⋅d=πldl+r\pi \cdot d = \pi_l d_l + r, where rr is the value of rest in line L5 for this dd, and line L6 gives πl≥(1−r)/dl\pi_l \ge (1 - r)/d_l, so πldl+r≥1\pi_l d_l + r \ge 1. 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. TT has determinant ±1\pm 1: moving its first row to the bottom gives a lower triangular matrix with ones on the diagonal. So y=Tiy = T i 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 y1=ty_1 = t outermost.

The fronts keep every dependence. A dependence from ii to i+di + d has t(i+d)=t(i)+π⋅d≥t(i)+1t(i + d) = t(i) + \pi \cdot d \ge t(i) + 1, 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 kk and iteration space P={i∈Zk:Ai+b≥0}P = \{i \in \mathbb{Z}^k : A i + b \ge 0\}, a bounded set. DD is a finite set of nonzero distance vectors, each lexicographically positive: for each d∈Dd \in D there is a level ℓ(d)\ell(d) with d1=⋯=dℓ(d)−1=0d_1 = \dots = d_{\ell(d) - 1} = 0 and dℓ(d)>0d_{\ell(d)} > 0. Every dependence of the nest goes from an iteration ii to the iteration i+di + d for some d∈Dd \in D, or stays inside one iteration. The body of one iteration runs as a unit, with its statements in text order.

The algorithm computes π\pi by lines L1 to L7:

πk=1,πl=max⁡(0, max⁡d∈D, ℓ(d)=l⌈1−∑m>lπmdmdl⌉)(l=k−1,…,1),\pi_k = 1, \qquad \pi_l = \max\Bigl(0,\ \max_{d \in D,\ \ell(d) = l} \Bigl\lceil \frac{1 - \sum_{m > l} \pi_m d_m}{d_l} \Bigr\rceil\Bigr) \quad (l = k - 1, \dots, 1),

with the inner maximum taken as 00 when no dd leads at ll. It then forms the matrix TT with the rows π,e1,…,ek−1\pi, e_1, \dots, e_{k-1} (line L8) and runs the fronts Ft={i∈P:π⋅i=t}F_t = \{i \in P : \pi \cdot i = t\} in increasing tt, each front in any order or in parallel (lines L9 to L11).

Lemma 1: every distance gets a positive time difference

Claim. π⋅d≥1\pi \cdot d \ge 1 for every d∈Dd \in D.

Proof. Let l=ℓ(d)l = \ell(d). Then π⋅d=πldl+∑m>lπmdm\pi \cdot d = \pi_l d_l + \sum_{m > l} \pi_m d_m, because the entries before ll are 00.

If l=kl = k, then d=(0,…,0,dk)d = (0, \dots, 0, d_k) with dk≥1d_k \ge 1, and π⋅d=dk≥1\pi \cdot d = d_k \ge 1.

If l<kl < k, write r=∑m>lπmdmr = \sum_{m > l} \pi_m d_m. The values πm\pi_m for m>lm > l are fixed before level ll is processed, so rr is the value that line L5 computes. Line L6 makes πl≥⌈(1−r)/dl⌉≥(1−r)/dl\pi_l \ge \lceil (1 - r)/d_l \rceil \ge (1 - r)/d_l. Multiplying by dl>0d_l > 0 gives πldl≥1−r\pi_l d_l \ge 1 - r, so π⋅d=πldl+r≥1\pi \cdot d = \pi_l d_l + r \ge 1. □\square

So a time function exists whenever every distance is lexicographically positive, which holds for every real dependence. The construction also gives πl≥0\pi_l \ge 0 for all ll and πk=1\pi_k = 1.

Lemma 2: the matrix is unimodular

Claim. det⁡T=±1\det T = \pm 1, and the inverse map is il=yl+1i_l = y_{l+1} for l<kl < k and ik=y1−∑l<kπlyl+1i_k = y_1 - \sum_{l < k} \pi_l y_{l+1}.

Proof. Move the first row of TT to the bottom. This is a cyclic permutation of the rows and changes the determinant by the factor (−1)k−1(-1)^{k-1}. The result has the rows e1,…,ek−1,πe_1, \dots, e_{k-1}, \pi, which is lower triangular with diagonal 1,…,1,πk=11, \dots, 1, \pi_k = 1, so its determinant is 11. Hence det⁡T=(−1)k−1\det T = (-1)^{k-1}.

For the inverse: y=Tiy = T i means y1=π⋅iy_1 = \pi \cdot i and yl+1=ily_{l+1} = i_l for l<kl < k. Then y1=∑l<kπlyl+1+πkiky_1 = \sum_{l < k} \pi_l y_{l+1} + \pi_k i_k with πk=1\pi_k = 1, which gives the formula for iki_k. All coefficients are integers, so ii is an integer vector exactly when yy is. □\square

So i↦Tii \mapsto T i is a bijection from PP onto Q={y∈Zk:AT−1y+b≥0}Q = \{y \in \mathbb{Z}^k : A T^{-1} y + b \ge 0\}, and i∈Fti \in F_t exactly when Ti∈QT i \in Q has first coordinate tt.

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 QQ exactly once, in lexicographic order of yy.

Proof. Let QvQ_v be the real projection of the real polyhedron of QQ onto the coordinates y1,…,yvy_1, \dots, y_v. Fourier-Motzkin elimination of yk,…,yv+1y_k, \dots, y_{v+1} gives a system of inequalities whose real solution set is exactly QvQ_v. The loop at level vv runs, for fixed integers y1,…,yv−1y_1, \dots, y_{v-1}, over the integers yvy_v with (y1,…,yv)∈Qv(y_1, \dots, y_v) \in Q_v: 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 QQ projects into each QvQ_v, so each of its coordinates is in the range of its loop, and the point is visited. At level kk the system is the original one, so a visited point satisfies all constraints of QQ and is in QQ. 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. □\square

By Lemma 2, the visited yy correspond one to one to the iterations of PP, and the outer coordinate y1=ty_1 = t 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 tt, 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 ii to iteration j≠ij \ne i. Then j=i+dj = i + d for some d∈Dd \in D, and π⋅j=π⋅i+π⋅d≥π⋅i+1\pi \cdot j = \pi \cdot i + \pi \cdot d \ge \pi \cdot i + 1 by Lemma 1. So jj is in a strictly later front than ii, and the front of ii 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. □\square

What the construction does not promise

The number of fronts is not minimal in general. The construction always sets πk=1\pi_k = 1, so that TT is unimodular with the simple inverse above. For the single distance (1,−3)(1, -3) on the box 1≤i,j≤41 \le i, j \le 4 it gives π=(4,1)\pi = (4, 1), and all 16 iterations get different times, while π=(1,0)\pi = (1, 0), which is also valid, gives 4 fronts of 4 iterations. The correctness proof above holds for any integer π\pi with π⋅d≥1\pi \cdot d \ge 1, given a scan of the fronts; only Lemma 2 uses πk=1\pi_k = 1.

Complexity

Building π\pi looks at each distance once, at its leading level, and computes rest in O(k)O(k): O(Dk)O(D k) time. The scan does O(k)O(k) work per iteration for the bounds and for iki_k, so O(Nk)O(N k) in total. The Fourier-Motzkin elimination is done once for the nest; its cost depends on kk and on the number of constraints, not on NN or DD, and it can grow fast with kk, but loop nests are shallow. The extra space is O(k)O(k) for π\pi and the indices. The number of fronts is the number of distinct values of π⋅i\pi \cdot i over PP, at most ∑lπl(Ul−Ll)+1\sum_l \pi_l (U_l - L_l) + 1 on a box with bounds Ll≤il≤UlL_l \le i_l \le U_l, since every πl≥0\pi_l \ge 0.

Properties

  • Exact legality, no search. The construction always succeeds on lexicographically positive distances and needs no linear program.
  • Nonnegative coefficients. Every πl≥0\pi_l \ge 0 and πk=1\pi_k = 1.
  • One parallel level. The result has one sequential loop and k−1k - 1 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 π\pi to minimize the number of fronts is an integer program: minimize the spread of π⋅i\pi \cdot i over PP subject to π⋅d≥1\pi \cdot d \ge 1. The construction can be far from it. For the single distance (1,−3)(1, -3) on the box 1≤i,j≤41 \le i, j \le 4, it gives π=(4,1)\pi = (4, 1) and 16 fronts of one iteration, a sequential nest, while π=(1,0)\pi = (1, 0) gives 4 fronts of 4 iterations: the inner loop is already parallel. The implementation contains a brute-force search over small π\pi for such comparisons. A real compiler solves a linear program with a rounding step, or an integer program in fixed dimension.
  • Completion of any π\pi. When πk≠1\pi_k \ne 1 but the entries of π\pi 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, t=fi+jt = f i + j is skewing by ff 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, πldl+rest\pi_l d_l + \text{rest} can be 00 and two dependent iterations land in the same front.
  • A wrong filter in line L4. Line L6 divides by dld_l, which is safe only when dl>0d_l > 0. A distance with dl<0d_l < 0 must not enter line L6 at level ll: it leads at an outer level, and it gets its value there. Skipping a distance that does lead at ll leaves it without a check, and its π⋅d\pi \cdot d can be 00 or negative.
  • A zero distance in DD. A dependence inside one iteration has d=0d = 0 and can never get π⋅d≥1\pi \cdot d \ge 1. 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. ik=t−∑l<kπlili_k = t - \sum_{l<k} \pi_l i_l; 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.

lamport_hyperplane_method.pyI0RawGitHub
# 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

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

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
  • History with a source
  • a scene preset for the example