Algorithmresearch
Polyhedral scanning
Also called Quillere-Rajopadhye-Wilde algorithm, polyhedral code generation.
Generates loop nests that visit the integer points of a union of polyhedra in schedule order, by separating and projecting the polyhedra.
- Time
- O(s m P^(n+1) L) worst
- Space
- O(m P^n) extra
- Where
- L = the cost of one emptiness or implication test; P = the largest number of pieces at one level; m = the largest number of constraints of a polyhedron the generator builds; n = the number of scanning dimensions; s = the number of statements
- Model
- Word RAM
- Properties
- deterministicrecursive
- Evidence
- Proof sketchCode in 1 languages
Polyhedral scanning turns a set of polyhedra back into loops. A polyhedral compiler describes each statement by the integer points of its iteration domain and by a schedule that gives each point a time vector. After it changes the schedule, it must produce code that runs every point exactly once, in the lexicographic order of the time vectors. For one polyhedron, Ancourt and Irigoin (1991) found the loop bounds by Fourier-Motzkin elimination. For a union of polyhedra, one per statement, Quilleré, Rajopadhye and Wilde (2000) gave a recursive method: at each depth, project the polyhedra, split the projections into disjoint pieces, sort the pieces, and make one loop per piece. The CLooG tool of Bastoul (2004) and the code generator of isl are built on this method. It is the last step of every polyhedral compiler, after a scheduler such as Feautrier's or Pluto.
In plain words
Picture each statement as a set of dots on graph paper, and the schedule as the order in which we must touch the dots: row by row, and left to right inside each row. To write a loop for the rows, we need the lowest and highest row that has a dot. To get them, we flatten the shape onto one axis, like a shadow. When several shapes overlap, some rows have dots of one statement and some rows have dots of both. So we cut the rows into stretches where the same statements are present. Each stretch gets its own loop, and the stretches run from left to right. Inside each loop we do the same for the next axis. The result has no tests inside the loops, and every dot is touched once, in the right order.
The problem
Input. Integer parameters in a context , and statements . Statement has a domain , a polyhedron given by affine inequalities in its loop counters and , bounded for each , and an affine schedule .
Scanning space. Each instance becomes the point of , with the counters padded to the largest depth. The set of these points is a polyhedron in : the domain, plus the equalities and the zero padding. The schedule order is the lexicographic order of , where the text position of breaks ties.
Output. A loop nest that, for every , runs every instance with exactly once, in the lexicographic order of , and nothing else.
Loop bounds. A constraint with is a lower bound , and with an upper bound . A loop runs from the maximum of its lower bounds to the minimum of its upper bounds.
The algorithm
The generator is a recursive function of a list of polyhedra (each with the set of statements it stands for), a level and a context , the constraints that hold at that depth of the code. It starts with the polyhedra , level 1 and the context .
SCAN(polyhedra Q_1..Q_s, context C, level k)- 1
for each Q_i: Q'_i <- the shadow of Q_i on (x_1..x_k, N), by Fourier-Motzkin elimination of x_n down to x_(k+1); drop the empty ones - 2
separate the Q'_i into disjoint pieces R_1..R_r, each labeled with the set of statements whose Q'_i contains it - 3
sort the pieces so that, of two pieces that exist for the same outer values, the one with the smaller x_k comes first - 4
if no such order exists then make one loop over x_k from the least lower bound to the largest upper bound, and run inside it the part of each piece that contains x_k - 5
for each piece R in this order do - 6
guards <- the constraints of R without x_k that C does not imply - 7
bounds <- the constraints of R with x_k, minus those that the others and C imply - 8
if k = n then body <- the statements of the label of R, in text order - 9
else body <- SCAN({Q_i intersect R : i in the label of R}, C and R, k + 1) - 10
emit "if guards then for x_k = max(lower bounds) to min(upper bounds): body"
Fourier-Motzkin elimination. To remove , keep the constraints without and add, for each pair of a lower bound and an upper bound (with ), the combination . If appears in an equality, substitution is enough. The result is the rational shadow of the polyhedron. Each new constraint is divided by the greatest common divisor of its coefficients, and the constant is rounded down, which keeps the same integer points.
Separation. The pieces are built one polyhedron at a time. A new polyhedron splits each old piece into and the pieces of , and what is left of after all the old pieces becomes new pieces. The difference of two polyhedra is a union of polyhedra. With the constraints of , it is the disjoint union of
where is the integer complement of . Empty pieces are dropped. The emptiness tests and the tests "does imply " are linear programs, solved here with an exact simplex method over integer rows.
Sorting. Two pieces always differ by one constraint : one has and the other . If contains , this fixes their order along for all outer values. If it does not, the two pieces never exist for the same outer values. So pairs are either ordered or independent, and the test of line L3 is a pair of linear programs: "is there a point of and a point of with the same outer values and ?". A topological sort of this relation gives the order. Line L4 is a safety net of this implementation in case the relation has a cycle. It never fires on the tests.
Example
A triangle, interchanged. The nest for i = 0 to N: for j = 0 to i: S(i, j) with the schedule has and , so its points satisfy . Eliminating pairs the lower bound with the upper bound , and gives . The generator prints
for t1 = 0 to N:
for t2 = t1 to N:
i1 = t2
i2 = t1
S(i1, i2)
The last two lines are loops with a single iteration, from the equalities and .
Two statements, fused. Let run on and on , with the schedules and , a fusion of two loops. At level 1 the shadows are the two ranges. Separation gives three pieces: alone on , both on , and alone on . Inside the middle piece, level 2 separates from . The output is
for t1 = 0 to min(N, 1):
t2 = 0
i1 = t1
S1(i1)
for t1 = 2 to N:
t2 = 0
i1 = t1
S1(i1)
t2 = 1
i1 = t1
S2(i1)
for t1 = max(2, N + 1) to N + 2:
t2 = 1
i1 = t1
S2(i1)
There is no test inside any loop. For the middle loop is empty and the last one runs , as it should.
A skewed stencil. For for t = 0 to N: for i = 1 to N: S(t, i) with the skewed schedule , the generator gives for t1 = 0 to N: for t2 = t1 + 1 to t1 + N: with inside, under the guard , which the context does not imply.
Correctness
The full proof is in the proof page. It rests on four facts about the pieces at one level, for fixed values of the outer dimensions and the parameters.
- Cover. Every integer point of every has its first coordinates in the shadow , and so in some piece. Separation keeps every integer point of the union, because a point outside breaks some and so has .
- Disjointness. Two pieces have no integer point in common, so no point is visited twice.
- Labels. If a point of lies in the piece , then is in the label of , so the body of contains .
- Order. Inside one loop grows, and the sorted pieces visit increasing for the same outer values. By induction on , the whole nest visits the points in lexicographic order.
At the last level, a piece lies inside for each of its label, so a statement runs only at points of its domain.
Proof: The scanning code visits each integer point of each statement exactly once, in lexicographic orderfull
Setting. We use the notation of the page. All constraints have integer coefficients and are written with affine. For a set of constraints, a point of means an integer point that satisfies them, and is rationally empty if no rational point does. We treat a polyhedron as its set of constraints, so for two of them is the set of constraints of their intersection. Statement has the polyhedron in , made of its domain, the equalities , the zero padding and the context . For each the points of are exactly the vectors with , and this map is one to one, because is part of the vector. So it is enough to prove the claim below for the points of the .
Claim. For every integer , the generated code runs the pairs with a point of , each exactly once, and no other pair, in the lexicographic order of , where is compared by its text position.
Step 1: operations that keep the integer points
Lemma 1. Let be a set of constraints.
- Replacing by , where is the gcd of the entries of , keeps the points of and does not enlarge its rational set.
- Removing a constraint that the others imply on all rational points keeps the rational set, so it keeps the points.
- Every point of satisfies every constraint that Fourier-Motzkin elimination derives from , before or after step 1.
Proof. (1) At an integer , is an integer, and it is at least , so it is at least . Conversely , so the new constraint implies the old one at every rational point. (2) is clear. (3) A derived constraint is with , where and are constraints of , or where is an equality of . Both are nonnegative wherever the constraints of hold.
Let be the shadow of on computed at line L1. By Lemma 1, if is a point of , then with the same is a point of . Also is contained in the rational projection of , because each derived constraint holds on that projection and step 1 only shrinks it.
Step 2: separation
Let be the shadows at one call, each with the statement it stands for. Line L2 returns pieces with labels .
Lemma 2. The pieces satisfy:
- Cover and disjointness. Every point of is a point of exactly one piece, and pieces have no other points.
- Labels. A point of the piece is a point of if and only if .
- Separation. For two different pieces and , there is a constraint such that all rational points of one satisfy and all rational points of the other satisfy .
Proof. First, the difference. For constraint sets and , the pieces of are , with the rationally empty ones dropped; the loop also stops early when is rationally empty, and then no later has a point. A point of that is not a point of breaks some ; let be the first. Since is an integer there, , so the point lies in and in no other : for it has , and for it breaks . Points of lie in no . Any and with are separated by . Step 1 of Lemma 1, applied by the cleaning, keeps all of this, since it keeps points and only shrinks rational sets.
Now induct on the number of shadows inserted. With one shadow there is one piece. Suppose the claims hold for the pieces of and insert . Each old piece gives with label (if not rationally empty) and the pieces of with label . What is left of , the pieces of , gets the label .
(1) A point in some old piece , unique by induction, lies in if it is a point of , and else in exactly one piece of . It lies in no piece of what is left of , since those avoid every old piece. A point of in no old piece lies in exactly one piece of what is left of , by the property of the difference applied at each step.
(2) For a point of or of a piece of , the old labels are right by induction, and membership in is right by construction. A point in what is left of lies in no old piece, so by (1) for the old pieces it lies in no with .
(3) Two new pieces that come from different old pieces inherit their separating constraint. and a piece of are separated by . Two pieces of are separated as shown above. A piece of what is left of lies inside a piece of a difference by some old , so it satisfies for a constraint of , while every new piece inside satisfies . Two pieces of what is left of were split at some difference step by a constraint of the piece subtracted there.
Step 3: the order of the pieces
For pieces and at level , let be the rational set of pairs with , , the same and for .
Lemma 3. Either is empty, or on all of , or on all of . The test of line L3 finds which.
Proof. Take the constraint of Lemma 2(3), and say satisfies and satisfies . On , both points have the same . If , then and , so is empty. If , then , so . If , the same steps give . Line L3 tests the emptiness of , of and of with the simplex method, which is exact.
So line L3 builds a relation (" comes first") between every two pieces with . If it has no cycle, a topological sort gives an order. In that order, if two pieces before both have points over the same outer values , then , the relation holds as , and every point of there has a smaller than every point of there.
Step 4: one loop
Lemma 4. Let be a piece at level with the guards and bounds of lines L6 and L7, and let , , be an integer point that satisfies the context of the call. The loop of line L10 runs over exactly the integers such that is a point of , in increasing order.
Proof. The constraints of without are the guards, except those implied by , which hold at . Line L7 removes from the constraints with , together with , those implied by the others. By Lemma 1(2) the remaining set has the same rational points as all of them together with . Since satisfies all of , the kept bounds hold at exactly when all constraints of with hold. For an integer , with means , and with it means . So the integers with are those from the largest lower bound to the smallest upper bound. Both kinds of bounds exist: lies in a shadow, which lies in the rational projection of some , and that projection is bounded for each , because is.
Step 5: the induction
Invariant. A call gets a list of pairs , at most one per statement, such that every contains the constraints of . We prove, by induction on , that for every integer point of with the code of the call runs exactly the pairs with , a point of and , each once, in the lexicographic order of .
The pairs run. Take such a pair . By Step 1, is a point of the shadow , so by Lemma 2(1) it is a point of exactly one piece , and by Lemma 2(2) . By Lemma 4, the loop of runs exactly once, and the loops of the other pieces never reach , because they run only over their own points.
- If , the body runs the statements of , so runs once. Conversely, a statement runs at only when is a point of , so of by Lemma 2(2). At level there is nothing to eliminate, and by Lemma 1 the points of are the points of .
- If , the body is with . Every new contains , and satisfies ; the pruning of the new context keeps its rational set. By induction the body runs exactly the pairs with , a point of and of , and prefix . Every point with prefix is a point of , because only has constraints in . So these are all the pairs with prefix and . For , no point of has the prefix , because its shadow would contain , and Lemma 2(2) would put in .
So the call runs every pair once and no other pair.
The order. Inside one loop, grows, and for each the body runs its pairs in the order of by induction, or in text order at . Between two pieces before in the sorted order, Step 3 shows that every point of over has a smaller than every point of over . So the whole sequence is ordered by .
The fallback. If line L4 runs, the code runs in increasing order over a range that contains the ranges of all pieces, and for each runs the body of every piece whose range contains . By Lemma 4, that range is exactly the set of with a point of the piece, and by Lemma 2(1) at most one piece has this point. So the same argument applies, with the order coming from the single loop over .
Step 6: conclusion
The first call is , with pruned, which keeps its rational set. Every contains , and for the prefix is empty. The invariant gives the claim for every integer . The generator itself stops: the recursion has depth , each call makes finitely many pieces, and each linear program ends, because the simplex method uses a ratio test that cannot cycle.
Complexity
Fourier-Motzkin elimination of one variable can square the number of constraints, so can grow doubly exponentially with in the worst case. The implementation removes redundant constraints with linear programs to keep small. Separation of polyhedra can make a number of pieces that is exponential in . The generator calls itself at most times per piece and level, so it makes calls. Each call separates at most shadows against at most pieces, with tests each, and sorts with tests. The total is tests of cost , and the code holds loops of constraints each. In practice, for the loops of real programs, and stay small, and the size of the code is the main concern.
Properties
- No tests inside the loops. Each loop has exact bounds. Guards appear only where a piece does not exist for all outer values, and they sit outside the loop they guard.
- Rational shadows. The shadow from Fourier-Motzkin elimination is the rational one. For a polyhedron with a non-unimodular schedule, such as , the loop over also visits odd values, where the inner loop over is empty. The output is still correct, but it does wasted work.
- Code size. Separation can duplicate a statement many times, once per piece that contains it.
- Deterministic. The pieces and their order depend only on the input order of the statements and constraints.
Variants and improvements
- Strides. CLooG and isl detect equalities such as and turn them into loop steps,
for t = 0 to 2N step 2, instead of empty iterations. - Limits on separation. Bastoul's CLooG can stop separation below a given depth and use guards there, which trades a few tests for much smaller code. isl lets the user choose separation, isolation of full tiles, or unrolling per loop.
- Exact integer shadows. The projection of the omega test is exact on integers, as a union of polyhedra, and so avoids the empty iterations of rational shadows at the cost of more pieces.
- Tiled code. A tiled schedule uses , which is not affine. Code generators add a tile counter with and scan the larger polyhedron.
When to use it
Use polyhedral scanning whenever loops must be produced from a polyhedral description: after an affine scheduler, for loop tiling with parametric bounds, or to rewrite a nest under a unimodular transformation. For one perfect nest and a unimodular change, Fourier-Motzkin bounds alone are enough. For many statements with different domains, separation avoids tests in the inner loops.
Pitfalls
- Affine programs only. The domains, schedules and context must be affine in the counters and the parameters. Data-dependent bounds or subscripts leave the model.
- A legal schedule can still give slow code. Scanning makes the code follow the schedule, but separation can blow up the code size, and many small pieces near the borders cost branch and loop overhead.
- Integer holes. A rational shadow can contain integer values with no integer point above them. Without stride detection, the code runs empty loops there.
- Context matters. If the context of the parameters is too weak, the generator emits guards and pieces for parameter values that never occur, as in the guard of the stencil example.
- Ties. Points of two statements with the same time vector run in text order. If the schedule is not one to one, the counters themselves decide the order, which must then be legal too.
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/polyhedral-scanning/. The authors are listed in prov/19214B.jsonl.
"""Polyhedral scanning: loop nests that visit the integer points of a union
of polyhedra in lexicographic order.
Each statement S has a domain D_S and an affine schedule theta_S. Its
points in the scanning space are (theta_S(i), i, 0...), one dimension per
schedule entry and per loop counter, padded with zeros to a common length.
Visiting the union of these sets in lexicographic order runs the program in
schedule order.
At level k the generator projects every polyhedron on the first k + 1
dimensions by Fourier-Motzkin elimination, separates the projections into
disjoint pieces (the Quillere-Rajopadhye-Wilde method), sorts the pieces
along dimension k, and makes one loop per piece whose bounds are the
constraints of the piece on that dimension. Inside each loop it recurses on
the statements of the piece.
A constraint is a list of integers (a_0, ..., a_{v-1}, c) over the dimensions
and then the parameters, and means a . x + c >= 0. An exact simplex method
on integer rows decides emptiness and implication.
"""
from fractions import Fraction
from math import gcd, lcm
# ------------------------------------------------------- exact simplex method
def _reduce(row):
g = gcd(*row)
return [x // g for x in row] if g > 1 else row
def _update(row, pr, nz, p, k):
"""p * row - k * pr, touching only the nonzero places nz of pr."""
out = row[:] if p == 1 else [p * x for x in row]
for t in nz:
out[t] -= k * pr[t]
return out if p == 1 else _reduce(out)
def _pivot(rows, obj, basis, r, j):
pr, p = rows[r], rows[r][j]
nz = [t for t, y in enumerate(pr) if y]
for i in range(len(rows)):
k = rows[i][j]
if i != r and k:
rows[i] = _update(rows[i], pr, nz, p, k)
k = obj[j]
if k:
obj[:] = _update(obj, pr, nz, p, k)
basis[r] = j
def _run(rows, obj, basis, allowed, lexcols):
"""Maximize; obj[j] > 0 means column j improves. Dantzig's rule with a
lexicographic ratio test on the start basis columns, which cannot cycle;
after a fixed number of pivots, Bland's rule as a second guard. Returns
False if the problem is unbounded."""
cap = 50 * (len(rows) + len(obj))
steps = 0
while True:
steps += 1
if steps > cap:
j = next((j for j in allowed if obj[j] > 0), None)
else:
j = max(allowed, key=lambda j: obj[j], default=None)
if j is not None and obj[j] <= 0:
j = None
if j is None:
return True
leave = None
for r, row in enumerate(rows):
if row[j] <= 0:
continue
if leave is None:
leave = r
continue
a, b = row[j], rows[leave][j]
if steps > cap:
lhs, rhs = row[-1] * b, rows[leave][-1] * a
if lhs < rhs or (lhs == rhs and basis[r] < basis[leave]):
leave = r
continue
for t in [-1] + list(lexcols):
lhs, rhs = row[t] * b, rows[leave][t] * a
if lhs != rhs:
if lhs < rhs:
leave = r
break
if leave is None:
return False
_pivot(rows, obj, basis, leave, j)
def lp_max(c, A, b):
"""Maximize c.x subject to A x = b and x >= 0, with integer data, in
exact arithmetic. Returns the optimal x as Fractions, None if the system
is infeasible; raises ValueError if the problem is unbounded."""
m, n = len(A), len(c)
rows, basis = [], []
for i in range(m):
row = list(A[i]) + [b[i]]
if row[-1] < 0:
row = [-x for x in row]
art = [0] * m
art[i] = 1
rows.append(_reduce(row[:n] + art + row[n:]))
basis.append(n + i)
width = n + m + 1
den = lcm(*[rows[i][n + i] for i in range(m)]) if m else 1
obj = [0] * width
for i in range(m):
f = den // rows[i][n + i]
for t in range(width):
if not (n <= t < n + m):
obj[t] += f * rows[i][t]
_run(rows, obj, basis, range(n), range(n, n + m))
if obj[-1] != 0:
return None
for r in range(len(rows) - 1, -1, -1):
if basis[r] >= n:
j = next((j for j in range(n) if rows[r][j] != 0), None)
if j is None:
del rows[r], basis[r]
else:
if rows[r][j] < 0:
rows[r] = [-x for x in rows[r]]
_pivot(rows, [0] * width, basis, r, j)
obj = list(c) + [0] * m + [0]
for r in range(len(rows)):
k = obj[basis[r]]
if k:
p = rows[r][basis[r]]
obj = _reduce([p * x - k * y for x, y in zip(obj, rows[r])])
if not _run(rows, obj, basis, range(n), range(n, n + m)):
raise ValueError("unbounded")
x = [Fraction(0)] * n
for r, j in enumerate(basis):
if j < n:
x[j] = Fraction(rows[r][-1], rows[r][j])
return x
def _standard(rows, nv, obj):
"""{x free : rows} as A z = b, z >= 0, with x = p - q and one slack per row."""
m = len(rows)
A, b = [], []
for i, r in enumerate(rows):
line = []
for j in range(nv):
line += [r[j], -r[j]]
slack = [0] * m
slack[i] = -1
A.append(line + slack)
b.append(-r[-1])
c = []
for j in range(nv):
c += [-obj[j], obj[j]]
return c + [0] * m, A, b
def feasible(rows, nv):
"""Does {x in Q^nv : rows} have a point?"""
if any(not any(r[:-1]) and r[-1] < 0 for r in rows):
return False
rows = [r for r in rows if any(r[:-1])]
if not rows:
return True
c, A, b = _standard(rows, nv, [0] * nv)
return lp_max(c, A, b) is not None
def implied(rows, g, nv):
"""Does every rational point of the nonempty set {rows} satisfy g >= 0?"""
if not any(g[:-1]):
return g[-1] >= 0
c, A, b = _standard(rows, nv, g)
try:
x = lp_max(c, A, b)
except ValueError:
return False
if x is None:
return True
return sum(g[j] * (x[2 * j] - x[2 * j + 1]) for j in range(nv)) + g[-1] >= 0
# ------------------------------------------------- constraints and projection
def norm(row):
"""Divide by the gcd of the coefficients and round the constant down.
The integer points stay the same."""
g = gcd(*row[:-1])
if g <= 1:
return list(row)
return [x // g for x in row[:-1]] + [row[-1] // g]
def clean(rows):
"""Normalize, drop trivial rows, keep the tightest row per direction."""
best = {}
for r in rows:
r = norm(r)
if not any(r[:-1]):
if r[-1] < 0:
return [r]
continue
key = tuple(r[:-1])
if key not in best or r[-1] < best[key]:
best[key] = r[-1]
return [list(k) + [c] for k, c in best.items()]
def negate(g):
"""The integer complement of g >= 0, that is g <= -1."""
return [-x for x in g[:-1]] + [-g[-1] - 1]
def eliminate(rows, j):
"""Fourier-Motzkin elimination of variable j. With an equality on the
variable, substitution is enough."""
for r in rows:
if r[j] > 0 and [-x for x in r] in rows:
a = r[j]
return clean([[a * x - s[j] * y for x, y in zip(s, r)] if s[j] else s
for s in rows if s is not r and s != [-x for x in r]])
pos = [r for r in rows if r[j] > 0]
neg = [r for r in rows if r[j] < 0]
out = [r for r in rows if r[j] == 0]
for p in pos:
for q in neg:
a, b = p[j], -q[j]
out.append([b * x + a * y for x, y in zip(p, q)])
return clean(out)
def prune(rows, nv):
"""Remove the rows that the others imply."""
rows = clean(rows)
if len(rows) == 1 and not any(rows[0][:-1]):
return rows
k = 0
while k < len(rows):
rest = rows[:k] + rows[k + 1:]
if rest and implied(rest, rows[k], nv):
rows = rest
else:
k += 1
return rows
def project(rows, keep, n, nv):
"""The shadow of {rows} on the first `keep` dimensions (and the
parameters), by eliminating the dimensions n - 1, ..., keep."""
for j in range(n - 1, keep - 1, -1):
rows = eliminate(rows, j)
if len(rows) > 3 * nv:
rows = prune(rows, nv)
return rows
# ------------------------------------------------------------- separation
def difference(P, Q, nv):
"""P minus Q as disjoint pieces: P, q_1 >= 0, ..., q_{t-1} >= 0, q_t <= -1."""
out, acc = [], list(P)
for q in Q:
piece = acc + [negate(q)]
if feasible(piece, nv):
out.append(clean(piece))
acc = acc + [q]
if not feasible(acc, nv):
break
return out
def separate(polys, nv):
"""Disjoint pieces that cover the union of the polyhedra, each with the
set of polyhedra that contain it."""
pieces = []
for rows, lab in polys:
new, rest = [], [rows]
for prow, plab in pieces:
both = clean(prow + rows)
if feasible(both, nv):
new.append((both, plab | lab))
new += [(d, plab) for d in difference(prow, rows, nv)]
rest = [r2 for r in rest for r2 in difference(r, prow, nv)]
new += [(r, lab) for r in rest]
pieces = new
return pieces
def _pair(A, B, k, nv):
"""A and B in one space of nv + 1 variables: B's dimension k moves to
the new variable nv, the other dimensions and the parameters are shared."""
a = [r[:-1] + [0, r[-1]] for r in A]
b = []
for r in B:
s = r[:-1] + [r[k], r[-1]]
s[k] = 0
b.append(s)
return a + b
def sort_pieces(pieces, k, nv):
"""An order of the pieces such that two pieces that exist for the same
outer values come with the smaller x_k first, or None."""
m = len(pieces)
after = [set() for _ in range(m)]
indeg = [0] * m
for x in range(m):
for y in range(x + 1, m):
both = _pair(pieces[x][0], pieces[y][0], k, nv)
if not feasible(both, nv + 1):
continue # never at the same outer values
ge = [0] * (nv + 2)
ge[k], ge[nv] = 1, -1 # x_k(A) - x_k(B) >= 0
if not feasible(both + [ge], nv + 1):
after[x].add(y)
indeg[y] += 1
elif not feasible(both + [[-v for v in ge]], nv + 1):
after[y].add(x)
indeg[x] += 1
else:
return None
out, ready = [], [x for x in range(m) if indeg[x] == 0]
while ready:
x = min(ready)
ready.remove(x)
out.append(x)
for y in after[x]:
indeg[y] -= 1
if indeg[y] == 0:
ready.append(y)
return [pieces[x] for x in out] if len(out) == m else None
# --------------------------------------------------------- code generation
class Scop:
"""Statements with domains and schedules. Each statement is a dict with
'name', 'iters', 'domain' (affine dicts >= 0 over iters and params) and
'schedule' (a list of affine dicts). Affine dicts map names to integers;
the key "" is the constant."""
def __init__(self, params, context, stmts):
self.params, self.context, self.stmts = params, context, stmts
self.m = max(len(s["schedule"]) for s in stmts)
self.d = max(len(s["iters"]) for s in stmts)
self.dims = [f"t{k + 1}" for k in range(self.m)] + [f"i{k + 1}" for k in range(self.d)]
self.names = self.dims + params
self.n, self.nv = len(self.dims), len(self.names)
def row(self, aff, rename=None):
rename = rename or {}
r = [0] * (self.nv + 1)
for v, c in aff.items():
if v == "":
r[-1] += c
else:
r[self.names.index(rename.get(v, v))] += c
return r
def context_rows(self):
return [self.row(c) for c in self.context]
def polyhedron(self, s):
"""The points (theta(i), i, 0...) of statement s in the scanning space."""
S = self.stmts[s]
ren = {x: f"i{k + 1}" for k, x in enumerate(S["iters"])}
rows = [self.row(c, ren) for c in S["domain"]] + self.context_rows()
sched = S["schedule"] + [{}] * (self.m - len(S["schedule"]))
for k, th in enumerate(sched):
r = self.row(th, ren)
r[k] -= 1 # theta_k(i) - t_k = 0
rows += [r, [-x for x in r]]
for k in range(len(S["iters"]), self.d):
r = [0] * (self.nv + 1)
r[self.m + k] = 1 # i_k = 0 below the statement's depth
rows += [r, [-x for x in r]]
return clean(rows)
def scan(scop):
"""The loop nest for the scop: a list of nodes for codegen at level 0."""
polys = [(scop.polyhedron(s), frozenset([s])) for s in range(len(scop.stmts))]
ctx = prune(scop.context_rows(), scop.nv) if scop.context else []
return codegen(polys, 0, ctx, scop.n, scop.nv)
def codegen(polys, k, ctx, n, nv):
projs = []
for rows, lab in polys:
q = prune(project(rows, k + 1, n, nv), nv) # @line L1
if feasible(q, nv):
projs.append((q, lab))
pieces = separate(projs, nv) # @line L2
order = sort_pieces(pieces, k, nv) # @line L3
parts = []
for rows, lab in (order if order is not None else pieces): # @line L5
guards = [r for r in rows if r[k] == 0 and not implied(ctx, r, nv)] if ctx else \
[r for r in rows if r[k] == 0] # @line L6
bounds = prune([r for r in rows if r[k] != 0] + ctx, nv)
bounds = [r for r in bounds if r[k] != 0] # @line L7
if k == n - 1:
body = [{"exec": sorted(lab)}] # @line L8
else:
inner = [(clean(prow + rows), plab) for prow, plab in polys if plab <= lab]
body = codegen(inner, k + 1, prune(ctx + rows, nv), n, nv) # @line L9
parts.append({"k": k, "guards": guards, "bounds": bounds, "body": body}) # @line L10
if order is None and len(parts) > 1:
return [{"k": k, "union": parts}] # @line L4
return parts
# ------------------------------------------------------------- execution
def _rest(r, k, vals):
return sum(r[v] * vals[v] for v in range(len(vals)) if v != k and r[v]) + r[-1]
def _range(node, vals):
"""The range of x_k in a loop node, or None if a guard fails."""
k = node["k"]
if any(_rest(g, k, vals) < 0 for g in node["guards"]):
return None
lo, hi = None, None
for r in node["bounds"]:
a, rest = r[k], _rest(r, k, vals)
if a > 0:
b = -(rest // a) # ceil(-rest / a)
lo = b if lo is None else max(lo, b)
else:
b = rest // (-a) # floor(rest / -a)
hi = b if hi is None else min(hi, b)
if lo is None or hi is None:
raise ValueError("unbounded loop")
return lo, hi
def execute(ast, scop, env, visit):
"""Run the loop nest: visit(s, point) for each statement instance, where
point is the vector of all scanning dimensions."""
vals = [0] * scop.n + [env[p] for p in scop.params]
def run(nodes):
for node in nodes:
if "exec" in node:
for s in node["exec"]:
visit(s, tuple(vals[:scop.n]))
continue
k = node["k"]
if "union" in node:
ranges = [_range(p, vals) for p in node["union"]]
live = [(p, r) for p, r in zip(node["union"], ranges) if r]
if not live:
continue
for x in range(min(r[0] for _, r in live), max(r[1] for _, r in live) + 1):
vals[k] = x
for p, r in live:
if r[0] <= x <= r[1]:
run(p["body"])
vals[k] = x
continue
r = _range(node, vals)
if r is None:
continue
for x in range(r[0], r[1] + 1):
vals[k] = x
run(node["body"])
vals[k] = x
vals[k] = 0
run(ast)
def instance_of(scop, s, point):
"""The iteration vector of statement s at a scanning point."""
return point[scop.m:scop.m + len(scop.stmts[s]["iters"])]
# ------------------------------------------------------------- printing
def _expr(coefs, names):
terms = []
for v, c in zip(names, coefs[:-1]):
if c:
terms.append((c, v))
out = ""
for c, v in terms:
t = v if abs(c) == 1 else f"{abs(c)}*{v}"
out += (" - " if c < 0 else " + ") + t if out else ("-" if c < 0 else "") + t
if coefs[-1] or not out:
c = coefs[-1]
out += f" {'-' if c < 0 else '+'} {abs(c)}" if out else str(c)
return out
def _bound(r, k, names):
a = r[k]
rest = [x for x in r]
rest[k] = 0
if a > 0:
e = _expr([-x for x in rest], names)
return e if a == 1 else f"ceil(({e}) / {a})"
e = _expr(rest, names)
return e if a == -1 else f"floor(({e}) / {-a})"
def show(ast, scop, depth=0):
"""The loop nest as text."""
names, pad, lines = scop.names, " " * depth, []
for node in ast:
if "exec" in node:
for s in node["exec"]:
S = scop.stmts[s]
args = ", ".join(scop.dims[scop.m + j] for j in range(len(S["iters"])))
lines.append(f"{pad}{S['name']}({args})")
continue
if "union" in node:
k = node["k"]
lines.append(f"{pad}for {names[k]} in the union of:")
for p in node["union"]:
lines += show([p], scop, depth + 1)
continue
k, inner = node["k"], depth
if node["guards"]:
conds = " and ".join(f"{_expr(g, names)} >= 0" for g in node["guards"])
lines.append(f"{pad}if {conds}:")
inner += 1
lo = [_bound(r, k, names) for r in node["bounds"] if r[k] > 0]
hi = [_bound(r, k, names) for r in node["bounds"] if r[k] < 0]
ipad = " " * inner
if len(lo) == 1 and lo == hi:
lines.append(f"{ipad}{names[k]} = {lo[0]}")
inner -= 1
else:
lo_s = lo[0] if len(lo) == 1 else f"max({', '.join(lo)})"
hi_s = hi[0] if len(hi) == 1 else f"min({', '.join(hi)})"
lines.append(f"{ipad}for {names[k]} = {lo_s} to {hi_s}:")
lines += show(node["body"], scop, inner + 1)
return lines
# ------------------------------------------------------------- examples
def triangle(schedule="ij"):
"""for i = 0 to N: for j = 0 to i: S(i, j), scanned in (i, j) or (j, i)."""
sched = [{"i": 1}, {"j": 1}] if schedule == "ij" else [{"j": 1}, {"i": 1}]
S = {"name": "S", "iters": ["i", "j"],
"domain": [{"i": 1}, {"N": 1, "i": -1}, {"j": 1}, {"i": 1, "j": -1}],
"schedule": sched}
return Scop(["N"], [{"N": 1}], [S])
def two_ranges():
"""S1 on 0 <= i <= N and S2 on 2 <= i <= N + 2, fused: (i, 0) and (i, 1)."""
S1 = {"name": "S1", "iters": ["i"], "domain": [{"i": 1}, {"N": 1, "i": -1}],
"schedule": [{"i": 1}, {}]}
S2 = {"name": "S2", "iters": ["i"], "domain": [{"i": 1, "": -2}, {"N": 1, "i": -1, "": 2}],
"schedule": [{"i": 1}, {"": 1}]}
return Scop(["N"], [{"N": 1}], [S1, S2])
def skewed_stencil():
"""for t = 0 to N: for i = 1 to N: S(t, i), with the schedule (t, t + i)."""
S = {"name": "S", "iters": ["t", "i"],
"domain": [{"t": 1}, {"N": 1, "t": -1}, {"i": 1, "": -1}, {"N": 1, "i": -1}],
"schedule": [{"t": 1}, {"t": 1, "i": 1}]}
return Scop(["N"], [{"N": 1}], [S])
if __name__ == "__main__":
for title, scop in [("triangle, (i, j)", triangle("ij")), ("triangle, (j, i)", triangle("ji")),
("two ranges, fused", two_ranges()), ("skewed stencil", skewed_stencil())]:
print(f"-- {title}")
print("\n".join(show(scan(scop), scop)))
test_polyhedral_scanning.py 243 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/polyhedral-scanning/. The authors are listed in prov/19214B.jsonl.
"""Tests: for small parameter values, the generated loops must visit every
integer point of every statement domain exactly once, in lexicographic order
of (schedule, iteration vector, statement). Running the statements in that
order on small arrays must give the same memory as the original program
whenever a brute-force check finds the schedule legal."""
import random
import unittest
from polyhedral_scanning import (
Scop, clean, eliminate, execute, feasible, implied, instance_of, scan, separate,
show, skewed_stencil, triangle, two_ranges,
)
def value(aff, env):
return sum(c * (env[v] if v else 1) for v, c in aff.items())
def brute(scop, env, box):
"""All (point, s) with the iteration vector in the box and the domain."""
out = []
for s, S in enumerate(scop.stmts):
d = len(S["iters"])
def rec(prefix):
if len(prefix) == d:
e = dict(env)
e.update(zip(S["iters"], prefix))
if all(value(c, e) >= 0 for c in S["domain"]):
sched = [value(th, e) for th in S["schedule"]]
sched += [0] * (scop.m - len(sched))
out.append((tuple(sched) + tuple(prefix) + (0,) * (scop.d - d), s))
return
for x in range(-box, box + 1):
rec(prefix + [x])
rec([])
return sorted(out)
def scanned(scop, ast, env):
seen = []
execute(ast, scop, env, lambda s, p: seen.append((p, s)))
return seen
def check_scan(test, scop, ns):
ast = scan(scop)
for n in ns:
env = {"N": n}
got, want = scanned(scop, ast, env), brute(scop, env, 2 * n + 4)
# equal to the sorted list of all points: each point once, in order
test.assertEqual(got, want, f"N={n}\n" + "\n".join(show(ast, scop)))
return ast
class Pieces(unittest.TestCase):
def test_simplex_tests(self):
# x >= 0, y >= 0, x + y <= 2 in two variables
rows = [[1, 0, 0], [0, 1, 0], [-1, -1, 2]]
self.assertTrue(feasible(rows, 2))
self.assertFalse(feasible(rows + [[1, 1, -3]], 2))
self.assertTrue(implied(rows, [-1, 0, 2], 2))
self.assertFalse(implied(rows, [-1, 0, 1], 2))
def test_fourier_motzkin(self):
# 0 <= j <= i <= N gives 0 <= i <= N after eliminating j
rows = [[0, 1, 0, 0], [1, -1, 0, 0], [-1, 0, 1, 0]]
self.assertEqual(sorted(eliminate(rows, 1)), sorted([[1, 0, 0, 0], [-1, 0, 1, 0]]))
# i = 2 j with 0 <= i <= 3: the shadow is the rational one, odd i included
rows = [[-1, 2, 0], [1, -2, 0], [1, 0, 0], [-1, 0, 3]]
self.assertEqual(sorted(eliminate(rows, 1)), sorted([[1, 0, 0], [-1, 0, 3]]))
# 2 i + 1 >= 0 has the same integer points as i >= 0
self.assertEqual(clean([[2, 1]]), [[1, 0]])
def test_separation_is_disjoint_and_covers(self):
# [0, 5] and [3, 8] on one line
a, b = [[1, 0], [-1, 5]], [[1, -3], [-1, 8]]
pieces = separate([(a, frozenset("a")), (b, frozenset("b"))], 1)
for x in range(-2, 11):
hit = [lab for rows, lab in pieces if all(r[0] * x + r[1] >= 0 for r in rows)]
want = frozenset(c for c, (lo, hi) in [("a", (0, 5)), ("b", (3, 8))] if lo <= x <= hi)
self.assertEqual(hit, [want] if want else [], x)
class Examples(unittest.TestCase):
def test_triangle(self):
check_scan(self, triangle("ij"), range(0, 5))
ast = check_scan(self, triangle("ji"), range(0, 5))
self.assertEqual(show(ast, triangle("ji"))[:2], ["for t1 = 0 to N:", " for t2 = t1 to N:"])
def test_two_ranges_split_in_three_loops(self):
scop = two_ranges()
ast = check_scan(self, scop, range(0, 6))
self.assertEqual(len(ast), 3)
self.assertEqual(show(ast, scop)[0], "for t1 = 0 to min(N, 1):")
def test_skewed_stencil(self):
check_scan(self, skewed_stencil(), range(0, 5))
def test_guarded_union_fallback(self):
# force the path used when the pieces cannot be sorted
import polyhedral_scanning as ps
saved = ps.sort_pieces
ps.sort_pieces = lambda pieces, k, nv: None
try:
ast = check_scan(self, two_ranges(), range(0, 6))
self.assertIn("union", ast[0])
check_scan(self, random_scop(random.Random(7), False), range(0, 4))
finally:
ps.sort_pieces = saved
def test_stride(self):
# the schedule 2 i leaves holes: odd t1 values have no point
S = {"name": "S", "iters": ["i"], "domain": [{"i": 1}, {"N": 1, "i": -1}],
"schedule": [{"i": 2}]}
check_scan(self, Scop(["N"], [{"N": 1}], [S]), range(0, 5))
# ------------------------------------------------------- random programs
DOMS_J = [({"j": 1}, {"N": 1, "j": -1}), ({"j": 1}, {"i": 1, "j": -1}),
({"j": 1, "i": -1}, {"N": 1, "j": -1})]
DOMS_I = [({"i": 1}, {"N": 1, "i": -1}), ({"i": 1, "": -1}, {"N": 1, "i": -1, "": 1}),
({"i": 1, "": -2}, {"N": 1, "i": -1})]
LINEAR = [[{"i": 1}, {"j": 1}], [{"j": 1}, {"i": 1}], [{"i": 1}, {"i": 1, "j": 1}],
[{"i": 1, "j": 1}, {"i": 1}], [{"i": 1, "j": 1}, {"j": 1}]]
def random_scop(rng, original):
"""One or two outer loops with up to three statements of depth 1 or 2.
Each statement has its original schedule vector (b0, i, b1, j, b2) and,
unless `original`, a random schedule of the same shape. The fields
'write', 'reads' and 'omega' are used by the tests only."""
stmts, k = [], 0
for b0 in range(rng.randint(1, 2)):
lo_i, hi_i = rng.choice(DOMS_I)
for b1 in range(rng.randint(1, 2)):
if k == 3:
break
if rng.random() < 0.5:
iters, dom = ["i"], [lo_i, hi_i]
omega = [{"": b0}, {"i": 1}, {"": b1}, {}, {}]
lin = [{"i": rng.choice([1, 1, 2])}, {}]
else:
iters, dom = ["i", "j"], [lo_i, hi_i] + list(rng.choice(DOMS_J))
omega = [{"": b0}, {"i": 1}, {"": b1}, {"j": 1}, {}]
lin = rng.choice(LINEAR)
sched = omega if original else [{"": b0}, lin[0], {"": b1}, lin[1], {}]
def sub():
d = {"i": rng.choice([0, 1, 1, -1])}
if "j" in iters:
d["j"] = rng.choice([0, 1, -1])
return d, rng.choice([-1, 0, 0, 1])
reads = [(rng.choice("AB"), sub()) for _ in range(rng.randint(1, 2))]
stmts.append({"name": f"S{k}", "iters": iters, "domain": dom, "schedule": sched,
"omega": omega, "write": (rng.choice("AB"), sub()), "reads": reads})
k += 1
return Scop(["N"], [{"N": 1}], stmts)
def cell(acc, env):
arr, (d, c) = acc
return arr, value(d, env) + c
def instances(scop, env, box):
"""(omega vector, s, iteration vector) of every instance."""
out = []
for point, s in brute(scop, env, box):
S = scop.stmts[s]
it = instance_of(scop, s, point)
e = dict(env)
e.update(zip(S["iters"], it))
out.append((tuple(value(o, e) for o in S["omega"]), s, it))
return sorted(out)
def run(scop, env, order):
mem = {}
for s, it in order:
S = scop.stmts[s]
e = dict(env)
e.update(zip(S["iters"], it))
args = [mem.get(cell(r, e), 1) for r in S["reads"]]
mem[cell(S["write"], e)] = (sum(args) * 31 + 7 * s + 1) % 1000003
return mem
def legal(scop, env, inst, pos):
"""Every pair of instances that touch one cell, with a write, keeps its
order. pos maps (s, it) to the place in the new order."""
touched = {}
for _, s, it in inst:
S = scop.stmts[s]
e = dict(env)
e.update(zip(S["iters"], it))
touched[(s, it)] = ({cell(S["write"], e)}, {cell(r, e) for r in S["reads"]})
for x in range(len(inst)):
a = inst[x][1:]
wa, ra = touched[a]
for y in range(x + 1, len(inst)):
b = inst[y][1:]
wb, rb = touched[b]
if (wa & (wb | rb) or ra & wb) and pos[b] < pos[a]:
return False
return True
class RandomPrograms(unittest.TestCase):
def test_original_schedule_gives_original_order(self):
rng = random.Random(2000)
for _ in range(12):
scop = random_scop(rng, True)
ast = check_scan(self, scop, range(0, 4))
for n in range(0, 4):
env = {"N": n}
order = [(s, instance_of(scop, s, p)) for p, s in scanned(scop, ast, env)]
self.assertEqual(order, [(s, it) for _, s, it in instances(scop, env, 2 * n + 4)])
def test_random_schedules(self):
rng = random.Random(1991)
runs = 0
for _ in range(16):
scop = random_scop(rng, False)
ast = check_scan(self, scop, range(0, 4))
for n in range(0, 4):
env = {"N": n}
inst = instances(scop, env, 2 * n + 4)
order = [(s, instance_of(scop, s, p)) for p, s in scanned(scop, ast, env)]
pos = {x: t for t, x in enumerate(order)}
if legal(scop, env, inst, pos):
want = run(scop, env, [(s, it) for _, s, it in inst])
self.assertEqual(run(scop, env, order), want)
runs += 1
self.assertGreater(runs, 20)
if __name__ == "__main__":
unittest.main()
History
Ancourt and Irigoin (1991) gave a general method to scan one polyhedron with DO loops, using Fourier-Motzkin elimination for the bounds. Quilleré, Rajopadhye and Wilde (2000) gave the recursive separation algorithm, which produces code with no redundant tests inside loops. Bastoul (2004) extended it to general schedules and made it practical in CLooG, used by many polyhedral tools, including Pluto. Grosser, Verdoolaege and Cohen (2015) described the AST generator of isl, which handles the same problem with more options for code size.
References
- Corinne Ancourt and François Irigoin, Scanning polyhedra with DO loops, PPoPP 1991, 39-50, loop bounds for one polyhedron by Fourier-Motzkin elimination, as maxima and minima of rounded affine expressions
- Fabien Quilleré, Sanjay Rajopadhye and Doran Wilde, Generation of efficient nested loops from polyhedra, International Journal of Parallel Programming 28(5), 2000, 469-498, the recursive algorithm for a union of polyhedra, with projection, separation into disjoint pieces and sorting at each level
- Cédric Bastoul, Code generation in the polyhedral model is easier than you think, PACT 2004, 7-16, scanning with scattering functions (schedules), the CLooG tool, and the control of code size by limiting separation
- Tobias Grosser, Sven Verdoolaege and Albert Cohen, Polyhedral AST generation is more than scanning polyhedra, ACM TOPLAS 37(4), 2015, the AST generator of isl, with options for separation, unrolling and isolation of full tiles
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 19214B Edit this page History Report an error Markdown