Algorithmresearch
Pluto algorithm
Also called Bondhugula tiling hyperplanes.
Finds affine transformations that allow tiling and parallelism by minimizing a bound on dependence distances with integer linear programming.
- Time
- O((s d + e) I) worst
- Space
- O(e d) extra
- Where
- I = the cost of one integer linear program solve (exponential in the worst case); d = the depth of the deepest loop nest; e = the number of dependence edges; s = the number of statements
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
The Pluto algorithm finds an affine transformation of a loop program whose outer loops can be tiled and run in parallel. Uday Bondhugula and his coauthors published it in 2008. It builds the new loops one hyperplane at a time. Each hyperplane is an affine form per statement that must keep every remaining dependence nonnegative, so that a band of such hyperplanes can be tiled. Among the legal hyperplanes it picks one that minimizes a bound on the dependence distances along it, by integer linear programming. A small distance means little communication between tiles that run in parallel, or short reuse distances for tiles that run in sequence. The constraints on whole dependence polyhedra become linear with the affine form of Farkas' lemma, as in Feautrier's scheduling. Pluto is the base of the source-to-source compiler of the same name and of many later polyhedral optimizers.
In plain words
A program has loops, and some runs of its statements depend on others. We want to cut the work into blocks, like tiles on a floor, that fit in the cache, and run some blocks at the same time. Cutting is safe when, along each new loop direction, every needed value comes from the same block or from a block that is already done. Pluto looks for such directions one at a time. Among the safe ones, it prefers the direction in which a value travels the shortest way, because short trips mean less data moves between blocks. Each choice is a small integer optimization problem. When no new safe direction exists, Pluto splits the statements into groups that can run one after the other, and starts again.
The problem
Input. A static control program with integer parameters in a context . Statement has depth and a domain , a polyhedron that is bounded for each . A set of dependence edges with polyhedra of pairs such that must run after . This page uses memory-based dependences (flow, anti and output), one polyhedron per pair of accesses and per depth, as in the affine scheduling problem.
Output. For each statement, a list of affine forms such that on every , grouped into bands of consecutive hyperplanes. Inside a band, every hyperplane has on every dependence that the earlier dimensions do not already order. Such a band is fully permutable, and it can be tiled. Each statement gets linearly independent hyperplanes, so the transformation is one-to-one on its domain.
Hyperplanes. A hyperplane is with integer and . For an edge , the distance along is .
The algorithm
For each hyperplane, Pluto solves one integer linear program. Its unknowns are the coefficients , of every statement, the bound (one entry per parameter) and , and the Farkas multipliers. For every remaining edge it asks
Each of the two conditions is "an affine form in , , is nonnegative on ". By the affine Farkas lemma it holds exactly when the form equals with , where the are the constraints of . Matching the coefficients gives linear equations in all the unknowns.
Two more constraints stop the solver from returning zero or repeating a hyperplane. Let be the matrix of the hyperplanes already found for , and , the projection onto its orthogonal complement. For each statement that is not yet full rank, Pluto asks for every row of and . With no hyperplane found yet, this is .
PLUTO(program)- 1
E <- the dependence polyhedra of the program; H_S <- empty for each S; the current band is empty - 2
while E is not empty or some H_S has rank less than d_S do - 3
if some H_S is not full: phi, u, w <- the integer lexmin of (u, w, sum of c, sum of c0) with, for e in E, 0 <= delta_e <= u.N + w on P_e (Farkas), and the independence rows - 4
if a solution exists then append phi to the band and to H_S for each S that is not full; continue - 5
if the band is not empty then close it: E <- E minus the edges that some hyperplane of the band strongly satisfies; continue - 6
if E has edges between different strongly connected components then append a scalar dimension with the topological index of the component of S, and remove those edges - 7
else if E is not empty then append place p of the original schedule, p the least place that orders an edge of E, and remove the edges it strongly satisfies - 8
else append, for each S that is not full, a unit vector independent of H_S - 9
close the last band - 10
return the dimensions and the bands
The objective. The lexicographic minimum puts first. When , every distance along the hyperplane is a constant at most . When also , no dependence crosses the hyperplane at all, and the loop is parallel with no communication. The sums of the coefficients come next, to keep the loops simple. The implementation bounds every coefficient by 4, by 4 and by 30, as Pluto bounds its coefficients. Since all unknowns are then bounded integers, it turns the lexicographic order into one weighted sum, with a last small term that breaks ties toward the original loop order. It finds the integer optimum by branch and bound over an exact simplex method. Pluto itself solves the same problem with parametric integer programming.
Satisfied edges. An edge is strongly satisfied by if on . The coefficients are integers, so is an integer at integer points, and a positive rational minimum of over is enough. Edges leave only when a band closes (line L5), not after each hyperplane. So every hyperplane of a band has on all edges that were in when the band began, which is what tiling needs.
When the solver fails. If no hyperplane exists, Pluto closes the band. If that removes no edge, it cuts the dependence graph between its strongly connected components and orders them by a scalar dimension (line L6), which is a loop distribution. Line L7 is a safety net of this implementation for a single component: it reuses one component of the original loop order, which weakly satisfies all remaining edges and strongly satisfies at least one, by the argument on the Feautrier scheduling page. Line L8 completes the rank once no edge is left, which is always legal.
Example
Gauss-Seidel in one dimension. The loop for t = 0 to N: for i = 1 to N-1: A[i] = (A[i-1] + A[i] + A[i+1]) / 3 has dependences in the directions , , and in .
- First hyperplane. is illegal, because the direction gives . is legal. With memory-based dependences, the write of
A[i]at time conflicts with the accesses at every later time, so reaches , and the solver returns with , . - Second hyperplane. It must be independent of , so , and forces . The cheapest choice is , with , .
The band is a time skewing of the loop. Both hyperplanes keep all dependences nonnegative, so the band can be tiled with rectangular tiles in the skewed space. This is the classic result for stencils, also reached by hand with loop skewing. With exact dataflow dependences, only nearby time steps are linked, and the distances become constants.
Two-dimensional stencil. For A[i][j] = A[i-1][j] + A[i][j-1], the hyperplanes are and with and . The original loops are already a tilable band.
Fusion with a shift.
for i = 1 to N: S1: B[i] = A[i]
for i = 1 to N: S2: C[i] = B[i-1] + B[i+1]
A fused loop with is illegal, because reads B[i+1], which writes later. Pluto returns and , a fusion with a shift, with and . The edge is not strongly satisfied, because reads B[i] in the same new iteration as writes it. A scalar dimension (0 for , 1 for ) puts first inside the fused loop. The result is and , one loop in which B[i] is used right after it is written.
Matrix multiplication. For C[i][j] = 0 followed by a loop with C[i][j] += A[i][k] * B[k][j], the first two hyperplanes are and for both statements, with : both loops are parallel. The third is for the update and 0 for the initialization, and a scalar dimension puts the initialization first. The three hyperplanes form one band, so all three loops can be tiled.
Correctness
The full proof is in the proof page. It shows four facts.
- Legality. Every dimension appended weakly satisfies every edge that is in at that time, and an edge leaves only when some appended dimension strongly satisfies it. At the end is empty, so for every pair in every the first nonzero entry of is positive.
- Tiling. Inside a band, every hyperplane has on every edge that is in when the band starts, and a pair that no earlier dimension orders belongs to such an edge. So adding the tile coordinates of a band in front of it keeps every dependence in order, for any tile size .
- The cost bound. For each hyperplane found by the integer program and each edge in at that time, on all of , for every in the context.
- Termination. Each solver success raises the rank of every statement that is not full, each band closes once, and lines L6 and L7 each remove at least one edge.
Proof: The Pluto algorithm terminates and returns a legal transformation whose bands can be tiled, with the stated bound on dependence distancesfull
Setting. We use the notation of the page. The program is a static control program with integer parameters in the context . Statement has depth and a domain . Each edge of the input set has a polyhedron , given by affine constraints that include the domains and the context. As on the Feautrier scheduling page, the edges are the memory-based dependences split by depth, and each edge has a position in the original schedule vector : for an edge of depth , and for a "same iteration" edge with common loops. For a dimension (an affine form per statement) and an edge , write . The dimension weakly satisfies if on the integer points of , and strongly satisfies it if there.
Claim. The loop stops. Let be the list of dimensions it returns, and let the bands be its lists of hyperplanes.
- Legality. For every , every and every integer pair , .
- One to one. For each , the linear parts of the hyperplanes of contain linearly independent rows, so is one to one on .
- Tiling. For any integer tile size , the vector obtained by inserting for in a band in front of the hyperplanes of , for every band with two or more hyperplanes, still satisfies claim 1.
- The cost bound. If was found at line L3 with bound , then on for every edge that was in at that time. Every pair of an edge in on which the dimensions before the band of are equal belongs to such an edge.
Step 1: the linear constraints are sound
Lemma 1 (affine Farkas lemma). Let be a nonempty polyhedron, with affine . An affine form is nonnegative on all of if and only if for some .
This is Corollary 7.1h of Schrijver's book.
Line L3 writes and in the form of Lemma 1, with new multipliers for each edge and each of the two forms, and matches the coefficients of , , and the constant. These equations are linear in the unknowns. For the correctness claims we need only the "if" part of Lemma 1, which holds for every , empty or not: each term is nonnegative on . So any solution of line L3 has
The "only if" part says that line L3 misses no legal hyperplane within the coefficient bounds; this matters for the quality of the result, not for its correctness.
Lemma 2. The test of strong satisfaction is sound: if the rational minimum of over exists and is positive, then on the integer points of .
Proof. Every dimension that the algorithm builds has integer coefficients: the integer program asks for integers, the scalar dimension uses component indices, and lines L7 and L8 use components of and unit vectors. So at an integer point, with integer , is an integer. It is at least , so it is at least 1.
Step 2: every dimension weakly satisfies the current edges
Lemma 3. Each dimension appended while the current set is weakly satisfies every edge of . The dimension of line L6 strongly satisfies each edge that line L6 removes, and the dimension of line L7 strongly satisfies at least one edge of .
Proof. Line L3. This is (1).
Line L6. Let be the index of the strongly connected component of , in the graph whose arcs are the edges of , with the components in topological order. For an arc , either both lie in one component, and , or the component of comes before that of , and . The second case is exactly the set of edges that line L6 removes.
Line L7. Let and let be component of (0 if is shorter). For each edge , , so place lies in the common prefix of the two vectors, where both have the same kind of entry. By Lemma 4 of the Feautrier scheduling proof, the places before are equal on and place grows by at least 1. So on if , and if , which holds for at least one edge. The rational minimum of over is then at least 1, so the test of line L7 removes that edge.
Line L8. It runs only when is empty, and the claim is empty.
Lemma 4. An edge leaves only at lines L5, L6 and L7, and only when some dimension appended while it was in strongly satisfies it.
Proof. Line L5 removes an edge when some hyperplane of the band being closed passes the test of Lemma 2. Those hyperplanes were appended after the band began, and edges leave only at lines L5, L6 and L7, none of which runs while a band is open (line L5 closes it, and lines L6 and L7 run only when the band is empty). So the edge was in when each of them was appended. For lines L6 and L7, use Lemma 3.
Step 3: termination and rank
Let , the total rank of the hyperplane rows recorded for the statements.
Lemma 5. Each success of line L3 raises the rank of every statement that is not full. Each run of line L8 does the same.
Proof. Let be a statement with , and the linear part of the new . If is empty, the constraint gives . Otherwise each row of (or a positive multiple of it) is orthogonal to every row of , because . The constraints for every row and force for some row . If were a combination of the rows of , every would be 0. So is independent of . Line L8 appends a unit vector for the first counter with . Such an exists, because the unit vectors span the whole space and does not.
Termination. Every round of the loop does one of the following.
- A success of line L3 or a run of line L8. It raises , which is at most . A run of line L8 happens only when some statement is not full, because the loop runs with empty only in that case.
- A run of line L5. It empties the band, which only a success or a run of line L8 fills. So there are at most such rounds.
- A run of line L6 or L7. It removes at least one edge (Lemma 3), and no edge is ever added. So there are at most such rounds.
So the loop stops after at most rounds. It stops only when is empty and every has rank , which with Lemma 5 gives claim 2: the rows of are the linear parts of hyperplanes of , and a map whose linear part has rank is one to one on .
Step 4: legality
Take and an integer pair . At the end is empty, so left at some round. Let be the index of the last dimension appended up to the end of that round, and by Lemma 4 let be the index of a dimension appended while was in that strongly satisfies it. By Lemma 3, every dimension with weakly satisfies , so for , and . The first nonzero entry of is at some place at most , and it is positive. This is claim 1.
Step 5: the bands can be tiled
Lemma 6. The hyperplanes of a band have consecutive indices. Let be a band, and let and be such that at this pair for every before the first index of . Then was in during the whole band, and on for every .
Proof. While a band is open, only lines L3 and L8 append dimensions, and both append them to the band. Line L8 runs only when the band is empty, and then is empty. So a band is a run of consecutive dimensions. If had left before the band began, by Lemma 4 some dimension before the band would strongly satisfy it, and its would be at least 1 at the pair, not 0. Edges leave only when the band closes, so is in while each hyperplane of is appended. If began at line L8, then was empty and this cannot happen, so consists of hyperplanes from line L3, and (1) gives the inequality.
Proof of claim 3. Fix and an integer pair in , and let be the first place where is nonzero. By claim 1, . The tiled vector keeps all entries of in the same order and adds tile entries in front of the bands of two or more hyperplanes. The tile entry of a dimension has difference 0, because takes the same value at the two points. If is not in a band with tile entries, the first nonzero entry of the difference of the tiled vectors is the entry of , which is positive. Otherwise let be the band of . Every before has , so by Lemma 6, for every . The floor function is nondecreasing, so every tile entry of has a difference . If one of them is positive, the first nonzero entry is a positive tile entry. If all are 0, the entries that follow are those of from the start of on, and the first nonzero one is . In both cases .
Step 6: the cost bound and what it measures
The first part of claim 4 is (1). For the second part, take a pair of an edge on which the dimensions before the band of are equal. By Lemma 6, was in when was appended, so (1) applies to .
The two readings of the bound in the paper of Bondhugula and others (CC 2008) follow from it. Let and cut the space along into slabs of width , , for an integer .
- Communication. Suppose is a parallel dimension, so that the slabs run on different processors. A value moves between processors along a dependence pair only if . Let be the slab of the source. Then , and . So every source that sends a value out of its slab lies in the last layers of the slab. The number of values that a slab sends along is at most the number of points of in those layers. When this does not grow with along , and when no value moves.
- Reuse. Suppose is a sequential dimension. The target runs at most values of after the source , so bounds the reuse distance of the dependence, counted in hyperplanes .
The integer program minimizes first in lexicographic order, so among the legal, independent hyperplanes within the coefficient bounds it picks one with the smallest such bound. This is a statement about the bound only. The number of points in a layer, the tile shape and the machine are not in the objective, so the minimum bound is a locality heuristic and not a proof of the fastest code.
Complexity
The integer program succeeds at most times, because each success raises the rank of some statement. Each failure is followed by a band closing, a cut or a fallback, and there are at most closings and at most cuts and fallbacks. So there are integer programs, plus one linear program per edge and hyperplane for the strong satisfaction tests. The integer programs are NP-hard in general, so is exponential in the worst case. In practice they have tens to hundreds of bounded unknowns, and they stay small for typical kernels. The Farkas multipliers make the programs grow linearly with the number of constraints of the dependence polyhedra.
Properties
- Tilable bands. Every band of two or more hyperplanes can be tiled with rectangular tiles in the new coordinates, and its tiles can run as a pipelined wavefront even when no hyperplane in it is parallel.
- Fusion and distribution together. The constant terms let statements of different loops share a hyperplane with a shift, and the cuts between strongly connected components distribute them when that fails.
- Integer coefficients. The coefficients are integers by construction, so no scaling is needed.
- Nonnegative coefficients. Restricting keeps the integer programs small, at the cost of missing transformations such as loop reversal.
Variants and improvements
- Negative coefficients. Pluto+ (Bondhugula, Acharya and Cohen, 2016) allows negative coefficients, which brings in loop reversal and more skewings, and makes the linear independence constraints complete.
- Fusion policies. The Pluto tool has several policies that decide where to cut the dependence graph, from maximal fusion to no fusion, rather than only at the points where the solver fails.
- Other polyhedral schedulers. The isl scheduler, used in LLVM's Polly and in PPCG, combines Pluto's proximity cost with Feautrier's greedy fallback when no tilable band exists.
- Concurrent start. For stencils, diamond tiling (Bandishti, Pananilath and Bondhugula 2012) adds a constraint so that tiles can start in parallel along a face.
When to use it
Use Pluto-style scheduling to tile and parallelize dense loop nests with affine accesses, such as stencils, linear algebra kernels and image filters, for cache locality and coarse-grained parallelism on multicores. When the goal is the maximum degree of fine-grained parallelism, Feautrier's algorithm is the reference. For one perfect nest with uniform dependences, unimodular transformations or the hyperplane method are simpler.
Pitfalls
- Affine programs only. The dependence polyhedra and the Farkas linearization need affine loop bounds and affine subscripts. Index arrays and data-dependent conditions take the program out of the model.
- A heuristic, not an optimum. The integer program minimizes a bound on dependence distances. That bound is a proxy for communication volume and reuse distance, not a model of the machine. The lexicographic minimum is optimal for this objective only, and it does not prove that the code runs fastest. Tile sizes, vectorization, prefetching and the cost of the generated loop bounds are all outside the model.
- A legal schedule can be slow. A transformation that tiles well can still give loops with complex bounds, many empty tiles or poor vectorization. Measure the result.
- Memory-based dependences. Anti and output dependences link far-apart time steps, as in the Gauss-Seidel example where . Exact dataflow dependences, or array expansion, give smaller bounds.
- The independence trick can fail. The constraint asks for a positive component in a fixed direction. When the rows of cancel, for example after a first hyperplane in two dimensions, no new hyperplane passes, even though one exists. The algorithm then falls back to a cut, and the band ends early.
- Bounded coefficients. The bounds on the coefficients make the integer programs finite, but a legal hyperplane with larger coefficients is then missed.
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/pluto-algorithm/. The authors are listed in prov/8AZ5A6.jsonl.
"""The Pluto algorithm (Bondhugula, Hartono, Ramanujam and Sadayappan, 2008).
Pluto looks for tiling hyperplanes: one affine form phi_S(i) = c_S . i + c_S0
per statement, with c >= 0, such that every dependence e : S -> T that is not
yet satisfied has
phi_T(t) - phi_S(s) >= 0 on P_e (legal for tiling)
u . N + w - (phi_T(t) - phi_S(s)) >= 0 on P_e (the cost bound)
Both are made linear by the affine form of Farkas' lemma. Among the integer
solutions it takes the lexicographic minimum of (u, w, sum of c, sum of
constants), by branch and bound over an exact simplex method. Hyperplanes
found one after the other form a band. A new hyperplane must be linearly
independent of the earlier ones of each statement; Pluto asks for a
nonnegative component in the orthogonal complement. When no hyperplane is
found, the band closes and the dependences it satisfies leave. If none leave,
the statements are split by the strongly connected components of the
dependence graph.
Affine forms are dicts from names to Fractions; the key "" is the constant.
A constraint e means e >= 0.
"""
from fractions import Fraction
from itertools import product
from math import floor, gcd, lcm
COEF_MAX = 4 # bounds on the integer unknowns keep branch and bound finite
U_MAX = 4
W_MAX = 30
# ---------------------------------------------------------------- affine forms
def form(d=None, const=0):
out = {k: Fraction(v) for k, v in (d or {}).items() if v}
if const:
out[""] = Fraction(const)
return out
def F(**kw):
c = kw.pop("c", 0)
return form(kw, c)
def add(a, b, k=1):
out = dict(a)
for v, c in b.items():
out[v] = out.get(v, Fraction(0)) + k * c
if out[v] == 0:
del out[v]
return out
def evaluate(a, env):
return sum((c * (env[v] if v else 1) for v, c in a.items()), Fraction(0))
def rename(a, names):
return {names.get(v, v): c for v, c in a.items()}
# ------------------------------------------------------- exact simplex method
def _reduce(row):
g = gcd(*row)
return [x // g for x in row] if g > 1 else row
def _ints(xs):
xs = [Fraction(x) for x in xs]
d = lcm(*[x.denominator for x in xs if x])
return [int(x * d) if x else 0 for x in xs]
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, in exact arithmetic.
Returns the optimal values, None if infeasible; raises ValueError if the
problem is unbounded."""
m, n = len(A), len(c)
rows, basis = [], []
for i in range(m):
row = _ints(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)
cz = _ints(list(c))
obj = cz[:n] + [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
class LP:
"""Named variables (free or >= 0), linear equalities and inequalities,
and an objective to maximize."""
def __init__(self):
self.cols, self.eqs, self.ncol = {}, [], 0
def copy(self):
other = LP()
other.cols, other.eqs, other.ncol = dict(self.cols), list(self.eqs), self.ncol
return other
def var(self, name, free=False):
if name not in self.cols:
cs = [(self.ncol, 1)]
self.ncol += 1
if free:
cs.append((self.ncol, -1))
self.ncol += 1
self.cols[name] = cs
return name
def eq(self, coefs, rhs):
self.eqs.append((dict(coefs), Fraction(rhs)))
def ge(self, coefs, rhs):
s = self.var(f"_slack{len(self.eqs)}")
coefs = dict(coefs)
coefs[s] = Fraction(-1)
self.eq(coefs, rhs)
def maximize(self, objective):
A, b = [], []
for coefs, rhs in self.eqs:
row = [Fraction(0)] * self.ncol
for v, a in coefs.items():
for j, sg in self.cols[v]:
row[j] += sg * a
A.append(row)
b.append(rhs)
c = [Fraction(0)] * self.ncol
for v, a in objective.items():
for j, sg in self.cols[v]:
c[j] += sg * a
x = lp_max(c, A, b)
if x is None:
return None
return {v: sum((sg * x[j] for j, sg in cs), Fraction(0)) for v, cs in self.cols.items()}
def ilp_min(lp, obj, ints):
"""Minimize obj (integer coefficients on integer variables) with the
variables `ints` integer, by depth-first branch and bound. The integer
variables must be bounded. Returns (value, solution) or (None, None)."""
best, best_sol = None, None
stack = [[]]
while stack:
extra = stack.pop()
cur = lp.copy()
for v, lo, val in extra:
if lo:
cur.ge({v: 1}, val)
else:
cur.ge({v: -1}, -val)
sol = cur.maximize({k: -c for k, c in obj.items()})
if sol is None:
continue
val = sum(c * sol[k] for k, c in obj.items())
if best is not None and -floor(-val) >= best:
continue
x = next((v for v in ints if sol[v].denominator != 1), None)
if x is None:
best, best_sol = val, sol
continue
f = floor(sol[x])
stack.append(extra + [(x, True, f + 1)])
stack.append(extra + [(x, False, f)])
return best, best_sol
def ilp_lexmin(lp, objectives, ints):
"""Lexicographic minimum: minimize each objective in turn and fix it."""
lp, sol = lp.copy(), None
for obj in objectives:
best, sol = ilp_min(lp, obj, ints)
if best is None:
return None
lp.eq(obj, best)
return sol
def min_over(f, cons):
"""The rational minimum of the affine form f on {x : c(x) >= 0}, or None
if it is unbounded below."""
lp = LP()
for v in sorted({v for e in cons + [f] for v in e if v}):
lp.var(v, free=True)
for e in cons:
lp.ge({v: c for v, c in e.items() if v}, -e.get("", 0))
try:
sol = lp.maximize({v: -c for v, c in f.items() if v})
except ValueError:
return None
return evaluate(f, {v: sol.get(v, 0) for v in f if v})
# ------------------------------------------------------------ static programs
class Stmt:
def __init__(self, name, iters, betas, domain, write, reads):
self.name, self.iters, self.betas = name, iters, betas
self.domain = domain # forms >= 0 over iters and params
self.write = write # (array, [forms])
self.reads = reads # list of (array, [forms])
def theta(self, point):
"""The original schedule vector (beta_0, i_1, beta_1, ...)."""
out = [self.betas[0]]
for x, b in zip(point, self.betas[1:]):
out += [x, b]
return out
class Program:
def __init__(self, params, context, stmts):
self.params, self.context, self.stmts = params, context, stmts
self.by_name = {s.name: s for s in stmts}
def common_loops(S, T):
c = 0
while c < min(len(S.iters), len(T.iters)) and S.betas[c] == T.betas[c]:
c += 1
return c
def feasible(cons):
lp = LP()
for v in sorted({v for e in cons for v in e if v}):
lp.var(v, free=True)
for e in cons:
lp.ge({v: c for v, c in e.items() if v}, -e.get("", 0))
return lp.maximize({}) is not None
def dependences(prog):
"""Dependence polyhedra by depth: a list of (S, T, constraints, p) in the
variables s0.., t0.. and the parameters, where p is the place of the
original schedule vector that orders the pair (counted from 1)."""
edges, seen = [], set()
for S, T in product(prog.stmts, repeat=2):
sn = {v: f"s{k}" for k, v in enumerate(S.iters)}
tn = {v: f"t{k}" for k, v in enumerate(T.iters)}
accs = []
for (arr, sub) in [S.write] + S.reads:
for (arr2, sub2) in [T.write] + T.reads:
if arr == arr2 and ((arr, sub) == S.write or (arr2, sub2) == T.write):
accs.append((sub, sub2))
base = [rename(e, sn) for e in S.domain] + [rename(e, tn) for e in T.domain] + list(prog.context)
c = common_loops(S, T)
levels = list(range(1, c + 1)) + ([None] if S.betas[c] < T.betas[c] else [])
for sub, sub2 in accs:
acc = []
for a, b in zip(sub, sub2):
e = add(rename(a, sn), rename(b, tn), -1)
acc += [e, add({}, e, -1)]
for l in levels:
cons = base + acc
for k in range(c if l is None else l - 1):
e = F(**{f"s{k}": 1, f"t{k}": -1})
cons += [e, add({}, e, -1)]
if l is not None:
cons.append(F(**{f"t{l - 1}": 1, f"s{l - 1}": -1, "c": -1}))
key = (S.name, T.name, frozenset(tuple(sorted(e.items())) for e in cons))
if key not in seen and feasible(cons):
seen.add(key)
edges.append((S, T, cons, 2 * c + 1 if l is None else 2 * l))
return edges
# ------------------------------------------------------------ Farkas and ILP
def farkas(lp, terms, cons, tag):
"""Add psi >= 0 on {c >= 0 for c in cons}, where psi = sum of
sign * column * variable over `terms`, as the identity
psi = lambda_0 + sum lambda_i c_i with lambda >= 0 (affine Farkas
lemma). A pair c, -c gets one free multiplier."""
keys = [tuple(sorted(c.items())) for c in cons]
neg = {tuple(sorted((v, -a) for v, a in c.items())) for c in cons}
kept, free, seen = [], [], set()
for c, key in zip(cons, keys):
if key in seen:
continue
seen.add(key)
if key in neg:
seen.add(tuple(sorted((v, -a) for v, a in c.items())))
kept.append(c)
free.append(key in neg)
lams = [lp.var(f"lam.{tag}.{i}", free=f) for i, f in enumerate(free)]
lam0 = lp.var(f"lam.{tag}.const")
eq = {}
for v, col, sg in terms:
eq.setdefault(v, {})
eq[v][col] = eq[v].get(col, 0) + sg
for v in set(eq) | {v for c in kept for v in c}:
row = dict(eq.get(v, {}))
for lam, c in zip(lams, kept):
if c.get(v):
row[lam] = row.get(lam, 0) - c[v]
if v == "":
row[lam0] = row.get(lam0, 0) - 1
lp.eq(row, 0)
def coef(S, j):
return f"{S.name}.c{j}"
def const(S):
return f"{S.name}.c0"
def phi_terms(S, prefix, sign):
out = [(f"{prefix}{j}", coef(S, j + 1), sign) for j in range(len(S.iters))]
out.append(("", const(S), sign))
return out
def orthogonal_rows(H, d):
"""Integer rows spanning the orthogonal complement of the rows of H in
Q^d: the nonzero rows of I - H^T (H H^T)^{-1} H, scaled to integers."""
r = len(H)
M = [[sum(Fraction(H[a][k]) * H[b][k] for k in range(d)) for b in range(r)] for a in range(r)]
inv = [[Fraction(int(a == b)) for b in range(r)] for a in range(r)]
for col in range(r): # Gauss-Jordan on M
piv = next(i for i in range(col, r) if M[i][col] != 0)
M[col], M[piv], inv[col], inv[piv] = M[piv], M[col], inv[piv], inv[col]
p = M[col][col]
M[col] = [x / p for x in M[col]]
inv[col] = [x / p for x in inv[col]]
for i in range(r):
if i != col and M[i][col] != 0:
k = M[i][col]
M[i] = [x - k * y for x, y in zip(M[i], M[col])]
inv[i] = [x - k * y for x, y in zip(inv[i], inv[col])]
out = []
for a in range(d):
row = []
for b in range(d):
s = sum(H[x][a] * inv[x][y] * H[y][b] for x in range(r) for y in range(r))
row.append(Fraction(int(a == b)) - s)
if any(row):
ints = _reduce(_ints(row))
if ints not in out:
out.append(ints)
return out
def find_hyperplane(prog, edges, H):
"""One ILP: the lexmin of (u, w, sum c, sum c0) over legal, bounded,
independent hyperplanes. Returns ({S: form}, u, w) or None."""
lp = LP()
ints = ["u", "w"]
lp.var("u")
lp.var("w")
lp.ge({"u": -1}, -U_MAX)
lp.ge({"w": -1}, -W_MAX)
loop_sum, const_sum = {}, {}
for S in prog.stmts:
cs = [coef(S, j + 1) for j in range(len(S.iters))] + [const(S)]
for v in cs:
lp.var(v)
lp.ge({v: -1}, -COEF_MAX)
ints.append(v)
for v in cs[:-1]:
loop_sum[v] = 1
const_sum[const(S)] = 1
d = len(S.iters)
if len(H[S.name]) < d:
rows = orthogonal_rows(H[S.name], d) if H[S.name] else [[1] * d]
for h in rows:
lp.ge({coef(S, j + 1): h[j] for j in range(d) if h[j]}, 0)
total = {}
for h in rows:
for j in range(d):
total[coef(S, j + 1)] = total.get(coef(S, j + 1), 0) + h[j]
lp.ge({v: a for v, a in total.items() if a}, 1)
for idx, (S, T, cons, _) in enumerate(edges):
delta = phi_terms(T, "t", 1) + phi_terms(S, "s", -1)
farkas(lp, delta, cons, f"leg{idx}")
bound = [("N", "u", 1), ("", "w", 1)] + [(v, c, -sg) for v, c, sg in delta]
farkas(lp, bound, cons, f"cost{idx}")
# The unknowns are bounded integers, so the lexicographic minimum of
# (u, w, sum c, sum c0, tie) is the minimum of one weighted sum: each
# weight is larger than the largest value of everything after it. The
# last term, sum of (depth - 1) * c, breaks ties toward the original
# loop order.
tie = {coef(S, j + 1): j for S in prog.stmts for j in range(1, len(S.iters))}
w4 = COEF_MAX * sum(tie.values()) + 1
w3 = w4 * (COEF_MAX * len(const_sum) + 1)
w2 = w3 * (COEF_MAX * len(loop_sum) + 1)
w1 = w2 * (W_MAX + 1)
obj = {"u": w1, "w": w2}
obj.update({v: w3 + tie.get(v, 0) for v in loop_sum})
obj.update({v: w4 for v in const_sum})
sol = ilp_lexmin(lp, [obj], ints)
if sol is None:
return None
phi = {}
for S in prog.stmts:
f = {S.iters[j]: sol[coef(S, j + 1)] for j in range(len(S.iters))}
f[""] = sol[const(S)]
phi[S.name] = {v: c for v, c in f.items() if c}
return phi, int(sol["u"]), int(sol["w"])
def delta_form(phi, e):
S, T, _, _ = e
sn = {v: f"s{k}" for k, v in enumerate(S.iters)}
tn = {v: f"t{k}" for k, v in enumerate(T.iters)}
return add(rename(phi[T.name], tn), rename(phi[S.name], sn), -1)
def strongly(phi, e):
"""phi_T - phi_S >= 1 on the integer points of P_e. The difference is an
integer there, so a positive rational minimum is enough."""
m = min_over(delta_form(phi, e), e[2])
return m is not None and m > 0
def scc_order(names, edges):
"""Tarjan's algorithm on the statement graph; returns a map from a name
to the index of its component in topological order."""
succ = {n: [] for n in names}
for S, T, _, _ in edges:
succ[S.name].append(T.name)
index, low, stack, on, comps = {}, {}, [], set(), []
def visit(v):
index[v] = low[v] = len(index)
stack.append(v)
on.add(v)
for w in succ[v]:
if w not in index:
visit(w)
low[v] = min(low[v], low[w])
elif w in on:
low[v] = min(low[v], index[w])
if low[v] == index[v]:
comp = set()
while True:
w = stack.pop()
on.discard(w)
comp.add(w)
if w == v:
break
comps.append(comp)
for v in names:
if v not in index:
visit(v)
comps.reverse() # Tarjan finds sinks first
return {v: k for k, comp in enumerate(comps) for v in comp}
def original_component(prog, p):
"""Place p (from 1) of the original schedule vector, as an affine form
per statement; 0 for statements whose vector is shorter."""
out = {}
for S in prog.stmts:
if p <= 2 * len(S.iters) + 1:
out[S.name] = F(**{S.iters[p // 2 - 1]: 1}) if p % 2 == 0 else form({}, S.betas[(p - 1) // 2])
else:
out[S.name] = {}
return out
def pluto(prog):
"""Returns (dims, bands, edges). dims is a list of dicts with keys
'phi' ({S: form}), 'kind' ('hyperplane', 'scalar', 'original' or
'complete'), and 'u', 'w' for hyperplanes. bands lists the index lists
of the bands of hyperplanes."""
all_edges = dependences(prog)
E = list(all_edges) # @line L1
H = {S.name: [] for S in prog.stmts}
dims, bands, band = [], [], []
def close():
nonlocal E, band
if band:
bands.append(band)
E = [e for e in E if not any(strongly(dims[k]["phi"], e) for k in band)]
band = []
while E or any(len(H[S.name]) < len(S.iters) for S in prog.stmts): # @line L2
found = None
if any(len(H[S.name]) < len(S.iters) for S in prog.stmts):
found = find_hyperplane(prog, E, H) # @line L3
if found:
phi, u, w = found
for S in prog.stmts: # @line L4
if len(H[S.name]) < len(S.iters):
H[S.name].append([phi[S.name].get(x, 0) for x in S.iters])
band.append(len(dims))
dims.append({"phi": phi, "kind": "hyperplane", "u": u, "w": w})
continue
if band:
close() # @line L5
continue
order = scc_order([S.name for S in prog.stmts], E)
cross = [e for e in E if order[e[0].name] != order[e[1].name]]
if cross: # @line L6
dims.append({"phi": {S.name: form({}, order[S.name]) for S in prog.stmts}, "kind": "scalar"})
E = [e for e in E if e not in cross]
elif E: # @line L7
phi = original_component(prog, min(e[3] for e in E))
dims.append({"phi": phi, "kind": "original"})
E = [e for e in E if not strongly(phi, e)]
else: # @line L8
phi = {}
for S in prog.stmts:
phi[S.name] = {}
for x in S.iters:
rows = H[S.name] + [[int(y == x) for y in S.iters]]
if len(H[S.name]) < len(S.iters) and rank(rows) == len(rows):
H[S.name].append(rows[-1])
phi[S.name] = F(**{x: 1})
break
band.append(len(dims))
dims.append({"phi": phi, "kind": "complete", "u": 0, "w": 0})
close() # @line L9
return dims, bands, all_edges # @line L10
def rank(rows):
m = [[Fraction(x) for x in r] for r in rows]
rk = 0
for col in range(len(m[0]) if m else 0):
piv = next((i for i in range(rk, len(m)) if m[i][col] != 0), None)
if piv is None:
continue
m[rk], m[piv] = m[piv], m[rk]
for i in range(len(m)):
if i != rk and m[i][col] != 0:
k = m[i][col] / m[rk][col]
m[i] = [x - k * y for x, y in zip(m[i], m[rk])]
rk += 1
return rk
# ------------------------------------------------------------ brute force
def instances(prog, env, box):
out = []
for S in prog.stmts:
for p in product(range(-box, box + 1), repeat=len(S.iters)):
e = dict(env)
e.update(zip(S.iters, p))
if all(evaluate(c, e) >= 0 for c in S.domain):
out.append((S.theta(p), S, p))
out.sort(key=lambda x: x[0])
return out
def cells(S, p, env):
e = dict(env)
e.update(zip(S.iters, p))
w = (S.write[0],) + tuple(int(evaluate(x, e)) for x in S.write[1])
rs = [(a,) + tuple(int(evaluate(x, e)) for x in sub) for a, sub in S.reads]
return w, rs
def brute_dependences(prog, env, box):
"""All pairs of instances (a, b), a before b, that touch one cell with
at least one write."""
inst = instances(prog, env, box)
acc = [cells(S, p, env) for _, S, p in inst]
out = []
for x in range(len(inst)):
wx, rx = acc[x]
for y in range(x + 1, len(inst)):
wy, ry = acc[y]
if wx == wy or wx in ry or wy in rx:
out.append(((inst[x][1].name, inst[x][2]), (inst[y][1].name, inst[y][2])))
return out
def time_vector(prog, dims, name, point, env, bands=(), tile=None):
"""The new time of an instance. With a tile size, each band of two or
more hyperplanes gets tile coordinates floor(phi / tile) in front."""
S = prog.by_name[name]
e = dict(env)
e.update(zip(S.iters, point))
vals = [evaluate(d["phi"][name], e) for d in dims]
if tile is None:
return tuple(vals)
starts = {b[0]: b for b in bands if len(b) >= 2}
out = []
for k, v in enumerate(vals):
if k in starts:
out += [floor(vals[j] / tile) for j in starts[k]]
out.append(v)
return tuple(out)
def run(prog, env, box, order_key=None, rng=None):
"""Run the instances in the original order, or sorted by order_key with
ties in a random order."""
inst = instances(prog, env, box)
if order_key is not None:
if rng is not None:
rng.shuffle(inst)
inst.sort(key=lambda x: order_key(x[1].name, x[2]))
mem = {}
for _, S, p in inst:
w, rs = cells(S, p, env)
val = 7 * prog.stmts.index(S) + sum(p) + 1
for r in rs:
val = (3 * val + mem.get(r, hash(r) % 97)) % 1000003
mem[w] = val
return mem
def show(dims):
def fmt(f):
terms = [(f"{c}*{v}" if c != 1 else v) if v else str(c)
for v, c in sorted(f.items(), key=lambda t: (t[0] == "", t[0]))]
return " + ".join(terms).replace("+ -", "- ") or "0"
names = list(dims[0]["phi"]) if dims else []
return {n: "(" + ", ".join(fmt(d["phi"][n]) for d in dims) + ")" for n in names}
# ------------------------------------------------------------------ examples
def seidel():
"""for t = 0 to N: for i = 1 to N - 1: A[i] = (A[i-1] + A[i] + A[i+1]) / 3"""
s = Stmt("S", ["t", "i"], [0, 0, 0], [F(t=1), F(N=1, t=-1), F(i=1, c=-1), F(N=1, i=-1, c=-1)],
("A", [F(i=1)]), [("A", [F(i=1, c=-1)]), ("A", [F(i=1)]), ("A", [F(i=1, c=1)])])
return Program(["N"], [F(N=1, c=-2)], [s])
def stencil():
"""for i = 1 to N: for j = 1 to N: A[i][j] = A[i-1][j] + A[i][j-1]"""
s = Stmt("S", ["i", "j"], [0, 0, 0], [F(i=1, c=-1), F(N=1, i=-1), F(j=1, c=-1), F(N=1, j=-1)],
("A", [F(i=1), F(j=1)]), [("A", [F(i=1, c=-1), F(j=1)]), ("A", [F(i=1), F(j=1, c=-1)])])
return Program(["N"], [F(N=1, c=-1)], [s])
def producer_consumer():
"""for i = 1 to N: S1: B[i] = A[i]; for i = 1 to N: S2: C[i] = B[i-1] + B[i+1]"""
s1 = Stmt("S1", ["i"], [0, 0], [F(i=1, c=-1), F(N=1, i=-1)], ("B", [F(i=1)]), [("A", [F(i=1)])])
s2 = Stmt("S2", ["i"], [1, 0], [F(i=1, c=-1), F(N=1, i=-1)], ("C", [F(i=1)]),
[("B", [F(i=1, c=-1)]), ("B", [F(i=1, c=1)])])
return Program(["N"], [F(N=1, c=-1)], [s1, s2])
def matmul():
"""for i, j: S1: C[i][j] = 0; for k: S2: C[i][j] = C[i][j] + A[i][k] * B[k][j]"""
dom = [F(i=1), F(N=1, i=-1), F(j=1), F(N=1, j=-1)]
s1 = Stmt("S1", ["i", "j"], [0, 0, 0], dom, ("C", [F(i=1), F(j=1)]), [])
s2 = Stmt("S2", ["i", "j", "k"], [0, 0, 1, 0], dom + [F(k=1), F(N=1, k=-1)],
("C", [F(i=1), F(j=1)]), [("C", [F(i=1), F(j=1)]), ("A", [F(i=1), F(k=1)]), ("B", [F(k=1), F(j=1)])])
return Program(["N"], [F(N=1)], [s1, s2])
if __name__ == "__main__":
for name, prog in [("seidel", seidel()), ("stencil", stencil()),
("producer-consumer", producer_consumer()), ("matmul", matmul())]:
dims, bands, edges = pluto(prog)
info = [(d["kind"], d.get("u"), d.get("w")) for d in dims]
print(name, len(edges), "edges", show(dims), "bands", bands, info)
test_pluto_algorithm.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pluto-algorithm/. The authors are listed in prov/8AZ5A6.jsonl.
"""Tests: the transformation must order every dependence that a brute-force
search finds; inside each band every hyperplane must keep the dependences
that reach the band nonnegative and within the bound u N + w; and running
the instances in the new order, untiled or tiled, with ties in a random
order, must give the same memory as the original program."""
import random
import unittest
from pluto_algorithm import (
F, LP, Program, Stmt, brute_dependences, dependences, form, ilp_lexmin, matmul,
orthogonal_rows, pluto, producer_consumer, run, seidel, show, stencil, time_vector,
)
def check_all(test, prog, ns, seed=0):
dims, bands, edges = pluto(prog)
pairs = 0
rng = random.Random(seed)
for n in ns:
env = {"N": n}
box = 2 * n + 2
for (a, p), (b, q) in brute_dependences(prog, env, box):
va = time_vector(prog, dims, a, p, env)
vb = time_vector(prog, dims, b, q, env)
test.assertLess(va, vb, f"{a}{p} -> {b}{q} at N={n}")
pairs += 1
diff = [y - x for x, y in zip(va, vb)]
for band in bands:
if any(diff[:band[0]]):
continue # satisfied before the band
for k in band:
test.assertGreaterEqual(diff[k], 0, "band not permutable")
test.assertLessEqual(diff[k], dims[k]["u"] * n + dims[k]["w"], "cost bound")
want = run(prog, env, box)
for tile in (None, 2, 3):
got = run(prog, env, box,
lambda name, pt: time_vector(prog, dims, name, pt, env, bands, tile), rng)
test.assertEqual(got, want, f"N={n} tile={tile}")
return dims, bands, pairs
class Pieces(unittest.TestCase):
def test_orthogonal_rows(self):
self.assertEqual(orthogonal_rows([[1, 0]], 2), [[0, 1]])
self.assertEqual(orthogonal_rows([[1, 1]], 2), [[1, -1], [-1, 1]])
self.assertEqual(orthogonal_rows([[1, 0, 0], [0, 1, 0]], 3), [[0, 0, 1]])
def test_ilp_lexmin(self):
# minimize x, then y, over 2x + 2y >= 3, 0 <= x, y <= 5, integers:
# the rational optimum has x = 0, y = 3/2; the integer one y = 2
lp = LP()
for v in "xy":
lp.var(v)
lp.ge({v: -1}, -5)
lp.ge({"x": 2, "y": 2}, 3)
sol = ilp_lexmin(lp, [{"x": 1}, {"y": 1}], ["x", "y"])
self.assertEqual((sol["x"], sol["y"]), (0, 2))
class Examples(unittest.TestCase):
def test_seidel_skews_time(self):
dims, bands, _ = check_all(self, seidel(), range(2, 5))
self.assertEqual(show(dims), {"S": "(t, i + t)"})
self.assertEqual(bands, [[0, 1]])
self.assertEqual([(d["u"], d["w"]) for d in dims], [(1, 0), (1, 1)])
def test_stencil_tiles_directly(self):
dims, bands, _ = check_all(self, stencil(), range(1, 5))
self.assertEqual(show(dims), {"S": "(i, j)"})
self.assertEqual([(d["u"], d["w"]) for d in dims], [(0, 1), (0, 1)])
def test_producer_consumer_fuses_with_a_shift(self):
dims, bands, _ = check_all(self, producer_consumer(), range(1, 6))
self.assertEqual(show(dims), {"S1": "(i, 0)", "S2": "(i + 1, 1)"})
self.assertEqual((dims[0]["u"], dims[0]["w"]), (0, 2))
self.assertEqual(dims[1]["kind"], "scalar")
def test_matmul_band_of_three(self):
dims, bands, _ = check_all(self, matmul(), range(0, 3))
self.assertEqual(bands, [[0, 1, 2]])
self.assertEqual([(d["u"], d["w"]) for d in dims[:2]], [(0, 0), (0, 0)])
def random_program(rng):
"""At most three statements at depth 1 or 2 in one or two outer loops,
on one-dimensional arrays A and B with affine subscripts."""
stmts, k = [], 0
for b0 in range(rng.randint(1, 2)):
for b1 in range(rng.randint(1, 2)):
if k == 3:
break
dom_i = [F(i=1), F(N=1, i=-1)]
if rng.random() < 0.5:
iters, betas, dom = ["i"], [b0, b1], dom_i
else:
lo, hi = rng.choice([(F(j=1), F(N=1, j=-1)), (F(j=1), F(i=1, j=-1)),
(F(j=1, i=-1), F(N=1, j=-1))])
iters, betas, dom = ["i", "j"], [b0, b1, 0], dom_i + [lo, hi]
def sub():
d = {"i": rng.choice([0, 1, 1, 2, -1])}
if "j" in iters:
d["j"] = rng.choice([0, 1, 1, -1])
if rng.random() < 0.2:
d["N"] = 1
return form(d, rng.choice([-1, 0, 0, 1]))
reads = [(rng.choice("AB"), [sub()]) for _ in range(rng.randint(1, 2))]
stmts.append(Stmt(f"S{k}", iters, betas, dom, (rng.choice("AB"), [sub()]), reads))
k += 1
return Program(["N"], [F(N=1)], stmts)
class RandomPrograms(unittest.TestCase):
def test_random(self):
# programs with many edges make large integer programs; they are
# skipped to keep the test fast
rng = random.Random(2008)
total, kinds, t = 0, set(), 0
while t < 16:
prog = random_program(rng)
if len(dependences(prog)) > 10:
continue
t += 1
dims, bands, pairs = check_all(self, prog, range(0, 4), seed=t)
total += pairs
kinds |= {d["kind"] for d in dims}
self.assertGreater(total, 500)
self.assertIn("hyperplane", kinds)
if __name__ == "__main__":
unittest.main()
History
Feautrier's 1992 papers set up the affine form of Farkas' lemma for schedules. From 1997, Lim and Lam used affine partitioning with the same tool to find communication-free and pipelined parallelism. In 2008, Bondhugula, Hartono, Ramanujam and Sadayappan (PLDI) and Bondhugula, Baskaran, Krishnamoorthy, Ramanujam, Rountev and Sadayappan (CC) combined these ideas into one practical algorithm. It finds tiling hyperplanes one at a time with a cost function that bounds dependence distances, and handles fusion and distribution in the same framework. The tool Pluto became a reference for polyhedral optimization, and its cost function is the "proximity" objective of the isl scheduler.
References
- Uday Bondhugula, Albert Hartono, J. Ramanujam and P. Sadayappan, A practical automatic polyhedral parallelizer and locality optimizer, PLDI 2008, 101-113, the tiling legality constraint, the cost function as a bound u.n + w on the dependence distances, its linearization with Farkas' lemma, the lexicographic minimum, the linear independence constraints, and the iterative algorithm with cuts between strongly connected components
- Uday Bondhugula, Muthu Baskaran, Sriram Krishnamoorthy, J. Ramanujam, Atanas Rountev and P. Sadayappan, Automatic transformations for communication-minimized parallelization and locality optimization in the polyhedral model, Compiler Construction (CC) 2008, LNCS, 132-146, the reading of the dependence distance along a tiling hyperplane as communication volume for parallel hyperplanes and as reuse distance for sequential ones, and the bounding function
- Alexander Schrijver, Theory of Linear and Integer Programming, Wiley, 1986, Corollary 7.1h (the affine form of Farkas' lemma)
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 8AZ5A6 Edit this page History Report an error Markdown