Algorithm Search⌘K

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

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 ϕS\phi_S 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 u⋅N+wu \cdot N + w 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 NN in a context KK. Statement SS has depth dSd_S and a domain DSD_S, a polyhedron that is bounded for each NN. A set EE of dependence edges e:S→Te : S \to T with polyhedra PeP_e of pairs (s⃗,t⃗)(\vec{s}, \vec{t}) such that T(t⃗)T(\vec{t}) must run after S(s⃗)S(\vec{s}). 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 ΦS=(ϕS1,…,ϕSm)\Phi_S = (\phi^1_S, \dots, \phi^m_S) such that ΦS(s⃗)<lexΦT(t⃗)\Phi_S(\vec{s}) <_{\mathrm{lex}} \Phi_T(\vec{t}) on every PeP_e, grouped into bands of consecutive hyperplanes. Inside a band, every hyperplane has ϕT(t⃗)−ϕS(s⃗)≥0\phi_T(\vec{t}) - \phi_S(\vec{s}) \ge 0 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 dSd_S linearly independent hyperplanes, so the transformation is one-to-one on its domain.

Hyperplanes. A hyperplane is ϕS(i⃗)=cS⋅i⃗+cS,0\phi_S(\vec{i}) = c_S \cdot \vec{i} + c_{S,0} with integer cS≥0c_S \ge 0 and cS,0≥0c_{S,0} \ge 0. For an edge ee, the distance along ϕ\phi is δe(s⃗,t⃗)=ϕT(t⃗)−ϕS(s⃗)\delta_e(\vec{s}, \vec{t}) = \phi_T(\vec{t}) - \phi_S(\vec{s}).

The algorithm

For each hyperplane, Pluto solves one integer linear program. Its unknowns are the coefficients cSc_S, cS,0c_{S,0} of every statement, the bound u≥0u \ge 0 (one entry per parameter) and w≥0w \ge 0, and the Farkas multipliers. For every remaining edge it asks

δe(s⃗,t⃗)≥0andu⋅N+w−δe(s⃗,t⃗)≥0on Pe.\delta_e(\vec{s}, \vec{t}) \ge 0 \quad\text{and}\quad u \cdot N + w - \delta_e(\vec{s}, \vec{t}) \ge 0 \qquad \text{on } P_e.

Each of the two conditions is "an affine form in s⃗\vec{s}, t⃗\vec{t}, NN is nonnegative on PeP_e". By the affine Farkas lemma it holds exactly when the form equals λ0+∑iλice,i\lambda_0 + \sum_i \lambda_i c_{e,i} with λ≥0\lambda \ge 0, where the ce,i≥0c_{e,i} \ge 0 are the constraints of PeP_e. Matching the coefficients gives linear equations in all the unknowns.

Two more constraints stop the solver from returning zero or repeating a hyperplane. Let HSH_S be the matrix of the hyperplanes already found for SS, and HS⊥=I−HST(HSHST)−1HSH_S^\perp = I - H_S^T (H_S H_S^T)^{-1} H_S, the projection onto its orthogonal complement. For each statement that is not yet full rank, Pluto asks h⋅cS≥0h \cdot c_S \ge 0 for every row hh of HS⊥H_S^\perp and ∑hh⋅cS≥1\sum_h h \cdot c_S \ge 1. With no hyperplane found yet, this is ∑jcS,j≥1\sum_j c_{S,j} \ge 1.

  1. PLUTO(program)
  2. 1E <- the dependence polyhedra of the program; H_S <- empty for each S; the current band is empty
  3. 2while E is not empty or some H_S has rank less than d_S do
  4. 3if 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
  5. 4if a solution exists then append phi to the band and to H_S for each S that is not full; continue
  6. 5if the band is not empty then close it: E <- E minus the edges that some hyperplane of the band strongly satisfies; continue
  7. 6if 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
  8. 7else 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
  9. 8else append, for each S that is not full, a unit vector independent of H_S
  10. 9close the last band
  11. 10return the dimensions and the bands

The objective. The lexicographic minimum puts uu first. When u=0u = 0, every distance along the hyperplane is a constant at most ww. When also w=0w = 0, 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, uu by 4 and ww 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 ϕ\phi if δe≥1\delta_e \ge 1 on PeP_e. The coefficients are integers, so δe\delta_e is an integer at integer points, and a positive rational minimum of δe\delta_e over PeP_e is enough. Edges leave EE only when a band closes (line L5), not after each hyperplane. So every hyperplane of a band has δe≥0\delta_e \ge 0 on all edges that were in EE 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 (0,1)(0, 1), (1,0)(1, 0), (1,1)(1, 1) and (1,−1)(1, -1) in (t,i)(t, i).

  • First hyperplane. ϕ=i\phi = i is illegal, because the direction (1,−1)(1, -1) gives δ=−1\delta = -1. ϕ=t\phi = t is legal. With memory-based dependences, the write of A[i] at time tt conflicts with the accesses at every later time, so δ\delta reaches NN, and the solver returns ϕ=t\phi = t with u=1u = 1, w=0w = 0.
  • Second hyperplane. It must be independent of (1,0)(1, 0), so ci≥1c_i \ge 1, and (1,−1)(1, -1) forces ct≥cic_t \ge c_i. The cheapest choice is ϕ=t+i\phi = t + i, with u=1u = 1, w=1w = 1.

The band (t,t+i)(t, t + i) 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 ii and jj with u=0u = 0 and w=1w = 1. 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 ϕS1=ϕS2=i\phi_{S1} = \phi_{S2} = i is illegal, because S2(i)S2(i) reads B[i+1], which S1(i+1)S1(i+1) writes later. Pluto returns ϕS1=i\phi_{S1} = i and ϕS2=i+1\phi_{S2} = i + 1, a fusion with a shift, with u=0u = 0 and w=2w = 2. The edge is not strongly satisfied, because S2(i−1)S2(i-1) reads B[i] in the same new iteration ii as S1(i)S1(i) writes it. A scalar dimension (0 for S1S1, 1 for S2S2) puts S1S1 first inside the fused loop. The result is ΦS1=(i,0)\Phi_{S1} = (i, 0) and ΦS2=(i+1,1)\Phi_{S2} = (i + 1, 1), one loop in which B[i] is used right after it is written.

Matrix multiplication. For C[i][j] = 0 followed by a kk loop with C[i][j] += A[i][k] * B[k][j], the first two hyperplanes are ii and jj for both statements, with u=w=0u = w = 0: both loops are parallel. The third is kk 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 EE at that time, and an edge leaves EE only when some appended dimension strongly satisfies it. At the end EE is empty, so for every pair in every PeP_e the first nonzero entry of ΦT(t⃗)−ΦS(s⃗)\Phi_T(\vec{t}) - \Phi_S(\vec{s}) is positive.
  • Tiling. Inside a band, every hyperplane has δe≥0\delta_e \ge 0 on every edge that is in EE when the band starts, and a pair that no earlier dimension orders belongs to such an edge. So adding the tile coordinates ⌊ϕ/τ⌋\lfloor \phi / \tau \rfloor of a band in front of it keeps every dependence in order, for any tile size τ≥1\tau \ge 1.
  • The cost bound. For each hyperplane found by the integer program and each edge in EE at that time, 0≤δe≤u⋅N+w0 \le \delta_e \le u \cdot N + w on all of PeP_e, for every NN 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 NN in the context KK. Statement SS has depth dSd_S and a domain DSD_S. Each edge e:S→Te : S \to T of the input set E0E_0 has a polyhedron PeP_e, given by affine constraints ce,i(s⃗,t⃗,N)≥0c_{e,i}(\vec{s}, \vec{t}, N) \ge 0 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 π(e)\pi(e) in the original schedule vector ΩS(s⃗)=(β0S,s1,β1S,…,sdS,βdSS)\Omega_S(\vec{s}) = (\beta^S_0, s_1, \beta^S_1, \dots, s_{d_S}, \beta^S_{d_S}): π(e)=2l\pi(e) = 2l for an edge of depth ll, and π(e)=2c+1\pi(e) = 2c + 1 for a "same iteration" edge with cc common loops. For a dimension ϕ\phi (an affine form per statement) and an edge ee, write δeϕ(s⃗,t⃗)=ϕT(t⃗)−ϕS(s⃗)\delta_e\phi(\vec{s}, \vec{t}) = \phi_T(\vec{t}) - \phi_S(\vec{s}). The dimension ϕ\phi weakly satisfies ee if δeϕ≥0\delta_e\phi \ge 0 on the integer points of PeP_e, and strongly satisfies it if δeϕ≥1\delta_e\phi \ge 1 there.

Claim. The loop stops. Let Φ=(ϕ1,…,ϕm)\Phi = (\phi^1, \dots, \phi^m) be the list of dimensions it returns, and let the bands be its lists of hyperplanes.

  1. Legality. For every e∈E0e \in E_0, every N∈KN \in K and every integer pair (s⃗,t⃗)∈Pe(\vec{s}, \vec{t}) \in P_e, ΦS(s⃗)<lexΦT(t⃗)\Phi_S(\vec{s}) <_{\mathrm{lex}} \Phi_T(\vec{t}).
  2. One to one. For each SS, the linear parts of the hyperplanes of SS contain dSd_S linearly independent rows, so ΦS\Phi_S is one to one on DSD_S.
  3. Tiling. For any integer tile size τ≥1\tau \ge 1, the vector Φτ\Phi^\tau obtained by inserting ⌊ϕk/τ⌋\lfloor \phi^k / \tau \rfloor for kk in a band BB in front of the hyperplanes of BB, for every band with two or more hyperplanes, still satisfies claim 1.
  4. The cost bound. If ϕk\phi^k was found at line L3 with bound (u,w)(u, w), then 0≤δeϕk≤u⋅N+w0 \le \delta_e\phi^k \le u \cdot N + w on PeP_e for every edge ee that was in EE at that time. Every pair (s⃗,t⃗)(\vec{s}, \vec{t}) of an edge in E0E_0 on which the dimensions before the band of ϕk\phi^k are equal belongs to such an edge.

Step 1: the linear constraints are sound

Lemma 1 (affine Farkas lemma). Let P={x:ci(x)≥0, i=1,…,m}P = \{x : c_i(x) \ge 0,\ i = 1, \dots, m\} be a nonempty polyhedron, with affine cic_i. An affine form ψ\psi is nonnegative on all of PP if and only if ψ≡λ0+∑iλici\psi \equiv \lambda_0 + \sum_i \lambda_i c_i for some λ0,…,λm≥0\lambda_0, \dots, \lambda_m \ge 0.

This is Corollary 7.1h of Schrijver's book. □\square

Line L3 writes δeϕ\delta_e\phi and u⋅N+w−δeϕu \cdot N + w - \delta_e\phi in the form of Lemma 1, with new multipliers λ≥0\lambda \ge 0 for each edge and each of the two forms, and matches the coefficients of s⃗\vec{s}, t⃗\vec{t}, NN 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 PP, empty or not: each term λici\lambda_i c_i is nonnegative on PP. So any solution of line L3 has

0≤δeϕ≤u⋅N+won Pe, for every e in the current E.(1)0 \le \delta_e\phi \le u \cdot N + w \quad \text{on } P_e, \text{ for every } e \text{ in the current } E. \tag{1}

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 μ\mu of δeϕ\delta_e\phi over PeP_e exists and is positive, then δeϕ≥1\delta_e\phi \ge 1 on the integer points of PeP_e.

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 Ω\Omega and unit vectors. So at an integer point, with integer NN, δeϕ\delta_e\phi is an integer. It is at least μ>0\mu > 0, so it is at least 1. □\square

Step 2: every dimension weakly satisfies the current edges

Lemma 3. Each dimension appended while the current set is EE weakly satisfies every edge of EE. 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 EE.

Proof. Line L3. This is (1).

Line L6. Let ord(S)\mathrm{ord}(S) be the index of the strongly connected component of SS, in the graph whose arcs are the edges of EE, with the components in topological order. For an arc S→TS \to T, either both lie in one component, and δe=0\delta_e = 0, or the component of SS comes before that of TT, and δe=ord(T)−ord(S)≥1\delta_e = \mathrm{ord}(T) - \mathrm{ord}(S) \ge 1. The second case is exactly the set of edges that line L6 removes.

Line L7. Let p=min⁡e∈Eπ(e)p = \min_{e \in E} \pi(e) and let ϕS\phi_S be component pp of ΩS\Omega_S (0 if ΩS\Omega_S is shorter). For each edge e∈Ee \in E, p≤π(e)≤2ce+1p \le \pi(e) \le 2c_e + 1, so place pp 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 π(e)\pi(e) are equal on PeP_e and place π(e)\pi(e) grows by at least 1. So δeϕ=0\delta_e\phi = 0 on PeP_e if π(e)>p\pi(e) > p, and δeϕ≥1\delta_e\phi \ge 1 if π(e)=p\pi(e) = p, which holds for at least one edge. The rational minimum of δeϕ\delta_e\phi over PeP_e is then at least 1, so the test of line L7 removes that edge.

Line L8. It runs only when EE is empty, and the claim is empty. □\square

Lemma 4. An edge leaves EE only at lines L5, L6 and L7, and only when some dimension appended while it was in EE 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 EE 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 EE when each of them was appended. For lines L6 and L7, use Lemma 3. □\square

Step 3: termination and rank

Let r=∑Srank⁡HSr = \sum_S \operatorname{rank} H_S, 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 SS be a statement with rank⁡HS<dS\operatorname{rank} H_S < d_S, and cSc_S the linear part of the new ϕS\phi_S. If HSH_S is empty, the constraint ∑jcS,j≥1\sum_j c_{S,j} \ge 1 gives cS≠0c_S \ne 0. Otherwise each row hh of HS⊥=I−HST(HSHST)−1HSH_S^\perp = I - H_S^T (H_S H_S^T)^{-1} H_S (or a positive multiple of it) is orthogonal to every row of HSH_S, because HSHS⊥=0H_S H_S^\perp = 0. The constraints h⋅cS≥0h \cdot c_S \ge 0 for every row and ∑hh⋅cS≥1\sum_h h \cdot c_S \ge 1 force h⋅cS>0h \cdot c_S > 0 for some row hh. If cSc_S were a combination of the rows of HSH_S, every h⋅cSh \cdot c_S would be 0. So cSc_S is independent of HSH_S. Line L8 appends a unit vector exe_x for the first counter xx with rank⁡(HS,ex)=rank⁡HS+1\operatorname{rank}(H_S, e_x) = \operatorname{rank} H_S + 1. Such an xx exists, because the unit vectors span the whole space and HSH_S does not. □\square

Termination. Every round of the loop does one of the following.

  • A success of line L3 or a run of line L8. It raises rr, which is at most ∑SdS≤sd\sum_S d_S \le s d. A run of line L8 happens only when some statement is not full, because the loop runs with EE 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 sds d 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 ∣E0∣|E_0| such rounds.

So the loop stops after at most 2sd+∣E0∣2 s d + |E_0| rounds. It stops only when EE is empty and every HSH_S has rank dSd_S, which with Lemma 5 gives claim 2: the rows of HSH_S are the linear parts of hyperplanes of SS, and a map whose linear part has rank dSd_S is one to one on ZdS\mathbb{Z}^{d_S}.

Step 4: legality

Take e∈E0e \in E_0 and an integer pair (s⃗,t⃗)∈Pe(\vec{s}, \vec{t}) \in P_e. At the end EE is empty, so ee left EE at some round. Let rr be the index of the last dimension appended up to the end of that round, and by Lemma 4 let q≤rq \le r be the index of a dimension appended while ee was in EE that strongly satisfies it. By Lemma 3, every dimension ϕk\phi^k with k≤rk \le r weakly satisfies ee, so δeϕk≥0\delta_e\phi^k \ge 0 for k≤rk \le r, and δeϕq≥1\delta_e\phi^q \ge 1. The first nonzero entry of ΦT(t⃗)−ΦS(s⃗)\Phi_T(\vec{t}) - \Phi_S(\vec{s}) is at some place at most qq, 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 BB be a band, and let e∈E0e \in E_0 and (s⃗,t⃗)∈Pe(\vec{s}, \vec{t}) \in P_e be such that δeϕk=0\delta_e\phi^k = 0 at this pair for every kk before the first index of BB. Then ee was in EE during the whole band, and δeϕk≥0\delta_e\phi^k \ge 0 on PeP_e for every k∈Bk \in B.

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 EE is empty. So a band is a run of consecutive dimensions. If ee had left EE before the band began, by Lemma 4 some dimension before the band would strongly satisfy it, and its δe\delta_e would be at least 1 at the pair, not 0. Edges leave EE only when the band closes, so ee is in EE while each hyperplane of BB is appended. If BB began at line L8, then EE was empty and this cannot happen, so BB consists of hyperplanes from line L3, and (1) gives the inequality. □\square

Proof of claim 3. Fix e∈E0e \in E_0 and an integer pair in PeP_e, and let k0k_0 be the first place where Δ=ΦT(t⃗)−ΦS(s⃗)\Delta = \Phi_T(\vec{t}) - \Phi_S(\vec{s}) is nonzero. By claim 1, Δk0>0\Delta_{k_0} > 0. The tiled vector Φτ\Phi^\tau keeps all entries of Φ\Phi in the same order and adds tile entries in front of the bands of two or more hyperplanes. The tile entry of a dimension k<k0k < k_0 has difference 0, because ϕk\phi^k takes the same value at the two points. If k0k_0 is not in a band with tile entries, the first nonzero entry of the difference of the tiled vectors is the entry of ϕk0\phi^{k_0}, which is positive. Otherwise let BB be the band of k0k_0. Every kk before BB has Δk=0\Delta_k = 0, so by Lemma 6, Δk≥0\Delta_k \ge 0 for every k∈Bk \in B. The floor function is nondecreasing, so every tile entry of BB has a difference ⌊ϕTk(t⃗)/τ⌋−⌊ϕSk(s⃗)/τ⌋≥0\lfloor \phi^k_T(\vec{t}) / \tau \rfloor - \lfloor \phi^k_S(\vec{s}) / \tau \rfloor \ge 0. 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 Φ\Phi from the start of BB on, and the first nonzero one is Δk0>0\Delta_{k_0} > 0. In both cases ΦSτ(s⃗)<lexΦTτ(t⃗)\Phi^\tau_S(\vec{s}) <_{\mathrm{lex}} \Phi^\tau_T(\vec{t}). □\square

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 e∈E0e \in E_0 on which the dimensions before the band BB of ϕk\phi^k are equal. By Lemma 6, ee was in EE when ϕk\phi^k was appended, so (1) applies to ee.

The two readings of the bound in the paper of Bondhugula and others (CC 2008) follow from it. Let b=u⋅N+wb = u \cdot N + w and cut the space along ϕ\phi into slabs of width τ\tau, aτ≤ϕ<(a+1)τa\tau \le \phi < (a + 1)\tau, for an integer aa.

  • Communication. Suppose ϕ\phi is a parallel dimension, so that the slabs run on different processors. A value moves between processors along a dependence pair only if ⌊ϕS(s⃗)/τ⌋<⌊ϕT(t⃗)/τ⌋\lfloor \phi_S(\vec{s}) / \tau \rfloor < \lfloor \phi_T(\vec{t}) / \tau \rfloor. Let aa be the slab of the source. Then ϕT(t⃗)≥(a+1)τ\phi_T(\vec{t}) \ge (a + 1)\tau, and ϕS(s⃗)=ϕT(t⃗)−δeϕ≥(a+1)τ−b\phi_S(\vec{s}) = \phi_T(\vec{t}) - \delta_e\phi \ge (a + 1)\tau - b. So every source that sends a value out of its slab lies in the last bb layers ϕ=(a+1)τ−b,…,(a+1)τ−1\phi = (a + 1)\tau - b, \dots, (a + 1)\tau - 1 of the slab. The number of values that a slab sends along ee is at most the number of points of DSD_S in those bb layers. When u=0u = 0 this does not grow with NN along ϕ\phi, and when u=w=0u = w = 0 no value moves.
  • Reuse. Suppose ϕ\phi is a sequential dimension. The target T(t⃗)T(\vec{t}) runs at most bb values of ϕ\phi after the source S(s⃗)S(\vec{s}), so bb bounds the reuse distance of the dependence, counted in hyperplanes ϕ=const\phi = \text{const}.

The integer program minimizes (u,w)(u, w) 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. ■\blacksquare

Complexity

The integer program succeeds at most sds d 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 sds d closings and at most ee cuts and fallbacks. So there are O(sd+e)O(s d + e) integer programs, plus one linear program per edge and hyperplane for the strong satisfaction tests. The integer programs are NP-hard in general, so II 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 cS,0c_{S,0} 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 c≥0c \ge 0 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 u=1u = 1. Exact dataflow dependences, or array expansion, give smaller bounds.
  • The independence trick can fail. The constraint ∑hh⋅cS≥1\sum_h h \cdot c_S \ge 1 asks for a positive component in a fixed direction. When the rows of HS⊥H_S^\perp cancel, for example after a first hyperplane (1,1)(1, 1) 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.

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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example