Algorithm Search⌘K

Algorithmadvanced

Feautrier scheduling algorithm

Also called Feautrier's multidimensional scheduling.

Finds affine schedules with the affine form of Farkas' lemma and linear programming, satisfying as many dependences as possible per dimension.

Time
O(e L) worst
Space
O(M) extra
Where
L = the cost of one linear program solve; M = the size of the largest linear program; e = the number of dependence edges (pairs of accesses times depths)
Properties
deterministiciterative

Feautrier's algorithm computes a multidimensional affine schedule for a static control program. It is one solution of the affine scheduling problem. It builds the schedule one dimension at a time. For each dimension it solves a linear program that keeps every remaining dependence in order (weak satisfaction) and puts as many of them as possible strictly in order (strong satisfaction). The affine form of Farkas' lemma makes "in order on the whole dependence polyhedron" a finite set of linear constraints. The edges that are strongly satisfied leave, and the next dimension handles the rest. Paul Feautrier published the method in 1992. It always terminates, so every static control program gets a legal schedule, even when no one-dimensional schedule exists.

In plain words

A loop program has many runs of each statement, and some runs must wait for others. We want a timetable given by simple formulas, one formula per statement, that keeps every needed order. Sometimes one formula cannot do it. The algorithm then builds the time as a list of numbers. For the first number it looks for a formula that never puts a run before a run it needs, and that puts as many needed pairs as possible strictly in order. Those pairs are now done. The pairs that the first number leaves tied are handled by the second number, and so on. Each step is one optimization problem with straight-line constraints, which a standard solver handles exactly. Every step finishes at least one pair, so the list ends. Runs with the same list of numbers can run at the same moment.

The problem

Input. A static control program with integer parameters NN in a context KK. Statement SS has depth dSd_S and an iteration domain DSD_S, a polyhedron that is bounded for each NN. The loop counters are nonnegative on DSD_S, which a shift of each loop gives. A set EE of dependence edges e:S→Te : S \to T, each with a dependence polyhedron 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 and its implementation use memory-based dependences (flow, anti and output), one polyhedron per pair of accesses and per depth ll. At depth ll, sk=tks_k = t_k for k<lk < l and tl≥sl+1t_l \ge s_l + 1. At the "same iteration" depth, the two instances share all their common loops and SS comes first in the text.

Output. For each statement SS, a list ΘS=(θS1,…,θSm)\Theta_S = (\theta^1_S, \dots, \theta^m_S) of affine forms in s⃗\vec{s} and NN such that ΘS(s⃗)<lexΘT(t⃗)\Theta_S(\vec{s}) <_{\mathrm{lex}} \Theta_T(\vec{t}) for every edge ee and every (s⃗,t⃗)∈Pe(\vec{s}, \vec{t}) \in P_e. The instances run in the lexicographic order of their time vectors, and instances with equal vectors may run in parallel.

Weak and strong. One dimension θ\theta weakly satisfies ee if θT(t⃗)−θS(s⃗)≥0\theta_T(\vec{t}) - \theta_S(\vec{s}) \ge 0 on PeP_e, and strongly satisfies it if θT(t⃗)−θS(s⃗)≥1\theta_T(\vec{t}) - \theta_S(\vec{s}) \ge 1 on PeP_e. A list of dimensions is legal for ee when some dimension strongly satisfies ee and all earlier dimensions weakly satisfy it.

The algorithm

Each dimension is the solution of a linear program whose unknowns are the coefficients of θS\theta_S for every statement, one variable εe∈[0,1]\varepsilon_e \in [0, 1] per remaining edge, and the Farkas multipliers. The condition "θT(t⃗)−θS(s⃗)≥εe\theta_T(\vec{t}) - \theta_S(\vec{s}) \ge \varepsilon_e on PeP_e" becomes, by the affine Farkas lemma,

θT(t⃗)−θS(s⃗)−εe≡λe,0+∑iλe,i ce,i(s⃗,t⃗,N),λe≥0,\theta_T(\vec{t}) - \theta_S(\vec{s}) - \varepsilon_e \equiv \lambda_{e,0} + \sum_i \lambda_{e,i}\, c_{e,i}(\vec{s}, \vec{t}, N), \qquad \lambda_e \ge 0,

where ce,i≥0c_{e,i} \ge 0 are the constraints of PeP_e. The identity holds for all values of s⃗\vec{s}, t⃗\vec{t} and NN, so it means one linear equation per variable and one for the constant. The same lemma gives Feautrier's condition θS≥0\theta_S \ge 0 on DSD_S.

  1. FEAUTRIER-SCHEDULE(program)
  2. 1E <- the dependence polyhedra P_e of the program, one per pair of accesses and depth
  3. 2while E is not empty do
  4. 3E' <- the edges still in E; theta_S has free coefficients, with theta_S >= 0 on D_S for each S
  5. 4for each e: S -> T in E' add 0 <= eps_e <= 1 and, by Farkas, theta_T(t) - theta_S(s) >= eps_e on P_e
  6. 5solve the linear program: maximize the sum of the eps_e; G <- { e : eps_e = 1 }
  7. 6solve it again with eps_e = 1 on G and eps_e = 0 elsewhere, minimizing the sum of |coefficients|
  8. 7scale theta to integer coefficients and append theta_S to Theta_S for every S
  9. 8E <- E minus G
  10. 9go to the next dimension
  11. 10return Theta

Why εe\varepsilon_e is 0 or 1. Line L5 never returns a fraction. Take a feasible solution in which the smallest positive εe\varepsilon_e is μ<1\mu < 1. Divide every θS\theta_S by μ\mu. Every difference grows by the factor 1/μ1/\mu, so each edge with εe>0\varepsilon_e > 0 now has a difference of at least 1 on PeP_e, and the others still have at least 0. The sum of the εe\varepsilon_e grows. So at an optimum every εe\varepsilon_e is 0 or 1, and the optimum is the largest number of remaining edges that one affine dimension can strongly satisfy while it weakly satisfies all the others.

Line L6. The optimum of L5 is not unique, and the vertex that the simplex method finds can have large coefficients. Line L6 keeps the same set GG and picks small coefficients, with a small weight on the constant terms. This is a choice of this implementation. Feautrier solves each dimension with parametric integer programming and takes a lexicographic minimum, which gives integer coefficients and, in Part I, puts a bound on the latency first. Any solution with the same GG is a correct dimension.

Line L7. The linear program works over the rationals. Multiplying all θS\theta_S of one dimension by the least common multiple DD of the denominators keeps every difference at least 0, and the strong ones at least D≥1D \ge 1.

Example

Running sum. For for i = 0 to N: for j = 0 to N: S: s = s + A[i][j], every instance reads and writes s. There are two edges: e1e_1 at depth 1 (t1≥s1+1t_1 \ge s_1 + 1, with s2s_2 and t2t_2 free in [0,N][0, N]) and e2e_2 at depth 2 (s1=t1s_1 = t_1, t2≥s2+1t_2 \ge s_2 + 1). The affine scheduling problem page shows that no single affine form strongly satisfies both.

  • In the first round, θ=ai+bj+cN+c0\theta = a i + b j + c N + c_0 must weakly satisfy e1e_1. On e1e_1 the difference a(t1−s1)+b(t2−s2)a(t_1 - s_1) + b(t_2 - s_2) takes the value a−bNa - bN when t2−s2=−Nt_2 - s_2 = -N, and for NN large this forces b=0b = 0. Then θ=i\theta = i strongly satisfies e1e_1 and gives difference 0 on e2e_2. The best sum is 1, and G={e1}G = \{e_1\}.
  • In the second round only e2e_2 is left, and θ=j\theta = j strongly satisfies it.

The schedule is ΘS(i,j)=(i,j)\Theta_S(i, j) = (i, j), the original sequential order. This is correct: each instance needs the one before it, so there is no parallelism to find.

Lower triangular matrix-vector product.

for i = 0 to N - 1:
S1:   y[i] = 0
      for j = 0 to i:
S2:       y[i] = y[i] + L[i][j] * x[j]

The edges go from S1(i)S1(i) to S2(i,j)S2(i, j) and from S2(i,j)S2(i, j) to S2(i,j′)S2(i, j') with j′>jj' > j. One round strongly satisfies all of them with θS1(i)=0\theta_{S1}(i) = 0 and θS2(i,j)=j+1\theta_{S2}(i, j) = j + 1. At time 0 all the S1S1 instances run in parallel. At time j+1j + 1, every row i≥ji \ge j adds its jj-th term in parallel. The last instance runs at time NN, so there are N+1N + 1 time steps, against N+N(N+1)/2N + N(N+1)/2 instances that the sequential program runs one after the other.

Two-dimensional stencil. For A[i][j] = A[i-1][j] + A[i][j-1] over 1≤i,j≤N1 \le i, j \le N, one round gives θ(i,j)=i+j\theta(i, j) = i + j, the wavefront schedule of Lamport's hyperplane method.

Reverse copy. For x[i] = f(i) over 0≤i≤N0 \le i \le N followed by y[j] = x[N - j] over 0≤j≤N0 \le j \le N, the schedule is θS1=0\theta_{S1} = 0 and θS2=1\theta_{S2} = 1. Each loop becomes fully parallel, and the two loops stay in sequence.

Correctness

The full proof is in the proof page. Here is the outline.

  • Each dimension is valid. By the affine Farkas lemma, the linear constraints of line L4 hold exactly when θT−θS≥εe\theta_T - \theta_S \ge \varepsilon_e on the whole polyhedron PeP_e, for nonempty PeP_e. By the scaling argument above, the edges with εe=1\varepsilon_e = 1 are strongly satisfied, and all other remaining edges are weakly satisfied.
  • Each round makes progress. If EE is not empty, some affine dimension strongly satisfies at least one edge of EE and weakly satisfies the others. Take the original schedule vector (β0,s1,β1,… )(\beta_0, s_1, \beta_1, \dots), where βk\beta_k is a text position, and the first position pp at which some edge of EE is strongly satisfied. All edges of EE have equal components before pp, so the component at pp weakly satisfies all of them. It is also nonnegative when the loop counters are. So GG is never empty.
  • Termination. Each round removes at least one edge, so there are at most ∣E∣|E| rounds.
  • Legality. An edge removed in round rr is weakly satisfied by rounds 11 to r−1r - 1, because it was still in EE, and strongly satisfied by round rr. So for each pair in PeP_e, the first nonzero component of the difference of the time vectors is positive.
  • One dimension when possible. If a nonnegative one-dimensional schedule exists, it strongly satisfies every edge, so the first round has G=EG = E and the algorithm returns one dimension.
Proof: Feautrier's greedy algorithm terminates and returns a legal multidimensional schedulefull

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, a polyhedron that is bounded for each NN, on which every loop counter is nonnegative. Each edge e:S→Te : S \to T of the input set E0E_0 has a nonempty 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. The edges are the memory-based dependences of the program, split by depth, as on the page: at depth ll the constraints contain sk=tks_k = t_k for k<lk < l and tl−sl−1≥0t_l - s_l - 1 \ge 0; at the "same iteration" depth they contain sk=tks_k = t_k for all common loops, and SS comes before TT in the text of the innermost common loop. For an affine form θ\theta per statement and an edge ee, write Δeθ(s⃗,t⃗)=θT(t⃗)−θS(s⃗)\Delta_e\theta(\vec{s}, \vec{t}) = \theta_T(\vec{t}) - \theta_S(\vec{s}).

Claim. The algorithm stops after at most ∣E0∣|E_0| rounds. The list Θ\Theta it returns satisfies ΘS(s⃗)<lexΘT(t⃗)\Theta_S(\vec{s}) <_{\mathrm{lex}} \Theta_T(\vec{t}) 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. If some affine θ\theta with θS≥0\theta_S \ge 0 on every DSD_S strongly satisfies every edge of E0E_0, the list has one dimension.

Step 1: the linear constraints say what they should

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. The "if" part is direct: each term is nonnegative on PP. □\square

The variables of PeP_e are s⃗\vec{s}, t⃗\vec{t} and NN. The identity in Lemma 1 holds for all values of these variables, so it is equivalent to the equality of the coefficients of each variable and of the constants. The coefficients of Δeθ−εe\Delta_e\theta - \varepsilon_e are linear in the unknown coefficients of θ\theta and in εe\varepsilon_e, so line L4 adds linear equations in the unknowns θ\theta, ε\varepsilon and λ\lambda, with λ≥0\lambda \ge 0. By Lemma 1, a vector of unknowns satisfies them if and only if Δeθ≥εe\Delta_e\theta \ge \varepsilon_e on PeP_e. In the same way, the constraints of line L3 hold if and only if θS≥0\theta_S \ge 0 on the polyhedron of DSD_S and KK for each SS. When both cc and −c-c are constraints, the implementation uses one free multiplier for the pair; this is the same as the difference of two nonnegative ones.

Step 2: the first linear program returns 0 or 1

Let EE be the current set of edges and let FF be the set of feasible points of line L4: affine θ\theta with θS≥0\theta_S \ge 0 on each DSD_S, and 0≤εe≤10 \le \varepsilon_e \le 1 with Δeθ≥εe\Delta_e\theta \ge \varepsilon_e on PeP_e for e∈Ee \in E.

Lemma 2. At every optimal point of line L5, every εe\varepsilon_e is 0 or 1.

Proof. Let (θ,ε)(\theta, \varepsilon) be optimal and suppose some εe\varepsilon_e lies strictly between 0 and 1. Let μ\mu be the least positive εe\varepsilon_e; then 0<μ<10 < \mu < 1. Set θ′=θ/μ\theta' = \theta / \mu and εe′=1\varepsilon'_e = 1 if εe>0\varepsilon_e > 0 and εe′=0\varepsilon'_e = 0 otherwise. Then θS′≥0\theta'_S \ge 0 on DSD_S. For an edge with εe>0\varepsilon_e > 0, Δeθ′=Δeθ/μ≥εe/μ≥1\Delta_e\theta' = \Delta_e\theta / \mu \ge \varepsilon_e / \mu \ge 1 on PeP_e. For an edge with εe=0\varepsilon_e = 0, Δeθ′≥0\Delta_e\theta' \ge 0. So (θ′,ε′)∈F(\theta', \varepsilon') \in F. Its objective is the number of positive εe\varepsilon_e, which is larger than ∑eεe\sum_e \varepsilon_e, because one term is less than 1. This contradicts optimality. □\square

So the set G={e:εe=1}G = \{e : \varepsilon_e = 1\} of line L5 is a set of edges that one feasible θ\theta strongly satisfies, while it weakly satisfies all of EE. By Lemma 2, the optimal value is the largest size of such a set.

Step 3: the chosen dimension is correct

Lemma 3. The dimension appended at line L7 weakly satisfies every edge of EE, strongly satisfies every edge of GG, and is nonnegative on every domain.

Proof. Line L6 solves the constraints of Step 1 with εe\varepsilon_e fixed to 1 on GG and to 0 on E∖GE \setminus G. This system is feasible, because the optimum of line L5 satisfies it. Its objective is a weighted sum of absolute values, bounded below by 0, so an optimum exists. By Step 1, its θ\theta has Δeθ≥1\Delta_e\theta \ge 1 on PeP_e for e∈Ge \in G, Δeθ≥0\Delta_e\theta \ge 0 for e∈Ee \in E, and θS≥0\theta_S \ge 0 on DSD_S. Line L7 multiplies every θS\theta_S by the same integer D≥1D \ge 1. This multiplies each Δeθ\Delta_e\theta by DD, so the three properties stay true, and the coefficients become integers. □\square

Step 4: every round removes an edge

Let Ω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}) be the original schedule vector of SS, where βkS≥0\beta^S_k \ge 0 is the text position at depth kk. Its components are affine in s⃗\vec{s} and nonnegative on DSD_S, because the counters are nonnegative. For an edge ee with cc common loops, define its position π(e)\pi(e): if ee has depth ll, then π(e)=2l\pi(e) = 2l, the place of the counter sls_l; if ee is a "same iteration" edge, then π(e)=2c+1\pi(e) = 2c + 1, the place of βc\beta_c. Number the components from 1.

Lemma 4. For an edge ee and every (s⃗,t⃗)∈Pe(\vec{s}, \vec{t}) \in P_e, the components q<π(e)q < \pi(e) of ΩS(s⃗)\Omega_S(\vec{s}) and ΩT(t⃗)\Omega_T(\vec{t}) are equal, and component π(e)\pi(e) of ΩT(t⃗)\Omega_T(\vec{t}) exceeds that of ΩS(s⃗)\Omega_S(\vec{s}) by at least 1.

Proof. The components before π(e)\pi(e) are β0,s1,…,βl−1\beta_0, s_1, \dots, \beta_{l-1} (or up to scs_c). The text positions βk\beta_k for k<ck < c are equal, because the two statements share these loops. The counters before depth ll are equal by the constraints of PeP_e. At position 2l2l, tl−sl≥1t_l - s_l \ge 1 by the constraints. At position 2c+12c + 1, βcT−βcS≥1\beta^T_c - \beta^S_c \ge 1, because these are different integers and SS comes first. □\square

Lemma 5. If EE is not empty, the set GG of line L5 is not empty.

Proof. Let p=min⁡e∈Eπ(e)p = \min_{e \in E} \pi(e), and let e∗e^\ast reach the minimum. Every edge e∈Ee \in E has π(e)≥p\pi(e) \ge p, and p≤π(e)≤2ce+1p \le \pi(e) \le 2c_e + 1, so component pp belongs to the common prefix of the two statements of ee, where both vectors have the same kind of entry. Define θS\theta_S as component pp of ΩS\Omega_S for every statement that has one, and as 00 for the others. Then θS≥0\theta_S \ge 0 on DSD_S. By Lemma 4, Δeθ=0\Delta_e\theta = 0 on PeP_e if π(e)>p\pi(e) > p, and Δeθ≥1\Delta_e\theta \ge 1 on PeP_e if π(e)=p\pi(e) = p. So θ\theta, with εe∗=1\varepsilon_{e^\ast} = 1 and the other εe=0\varepsilon_e = 0, is feasible with objective at least 1. The optimum of line L5 is then at least 1, and by Lemma 2 it is a whole number of edges with εe=1\varepsilon_e = 1, so G≠∅G \ne \emptyset. □\square

Step 5: conclusion

Termination. By Lemma 5, line L8 removes at least one edge in each round, so the loop runs at most ∣E0∣|E_0| times.

Legality. Take e∈E0e \in E_0 and let rr be the round that removes it. For each round q<rq < r, ee was in EE, so by Lemma 3 the dimension θq\theta^q weakly satisfies ee: Δeθq≥0\Delta_e\theta^q \ge 0 on PeP_e. The dimension θr\theta^r strongly satisfies it: Δeθr≥1\Delta_e\theta^r \ge 1. So for every (s⃗,t⃗)∈Pe(\vec{s}, \vec{t}) \in P_e, the vector ΘT(t⃗)−ΘS(s⃗)\Theta_T(\vec{t}) - \Theta_S(\vec{s}) has nonnegative entries up to place rr and a positive entry at place rr. Its first nonzero entry is at some place q≤rq \le r and is positive, so ΘS(s⃗)<lexΘT(t⃗)\Theta_S(\vec{s}) <_{\mathrm{lex}} \Theta_T(\vec{t}).

One dimension. If an affine θ\theta with θS≥0\theta_S \ge 0 on each DSD_S strongly satisfies every edge of E0E_0, then θ\theta with every εe=1\varepsilon_e = 1 is feasible in the first round, and its objective ∣E0∣|E_0| is the largest possible. So G=E0G = E_0, and the loop stops after one round.

Completeness of the edges. Every pair of instances that touch the same element, with at least one write, and with S(s⃗)S(\vec{s}) before T(t⃗)T(\vec{t}) in the original order, satisfies the constraints of exactly one depth for the pair of accesses involved, by the definition of the lexicographic order of Ω\Omega. So it lies in some PeP_e, and the schedule keeps its order. Instances with equal time vectors are therefore independent, and they may run in any order or in parallel. ■\blacksquare

Complexity

Building the edges takes one rational feasibility test per pair of accesses and depth, at most ee tests. There are at most ee rounds, each with two linear programs, so the total is O(e)O(e) linear program solves, O(eL)O(e L). The linear programs have one unknown per schedule coefficient, per edge and per constraint of each PeP_e, and one equation per variable of each PeP_e. So MM is linear in the size of the dependence polyhedra. With the simplex method, LL is exponential in the worst case and small in practice. With a polynomial algorithm for linear programming, the whole method runs in polynomial time. This is one reason Feautrier's method is practical, unlike exact searches for the schedule with the lowest latency.

The implementation on this page uses an exact simplex method over integer rows with Dantzig's rule and a lexicographic ratio test, which does not cycle.

Properties

  • Always succeeds. Every static control program gets a legal schedule. The number of dimensions is at most the number of edges.
  • Greedy. Each dimension maximizes the number of strongly satisfied edges among the remaining ones. Edges that the outer dimensions satisfy leave the outer loops free of their constraints, which tends to make inner dimensions parallel.
  • Parallelism, not locality. The objective counts satisfied edges. It does not look at reuse or at the size of the dependence distances.
  • Exact arithmetic. Legality on the whole parametric polyhedron is exact. No point is sampled and nothing is rounded.

Variants and improvements

  • One-dimensional schedules. Feautrier's Part I asks for one affine form that strongly satisfies every edge, with a bound on the latency as the objective. When it exists, the latency is affine in NN.
  • Integer solutions by PIP. Feautrier solves each linear program with parametric integer programming, as in array dataflow analysis. The lexicographic minimum gives integer coefficients directly.
  • Dataflow input. With the exact source functions of array dataflow analysis as edges, after array expansion, only the true flow of values constrains the schedule, and more parallelism appears.
  • Pluto. The Pluto algorithm keeps the Farkas linearization and the per-dimension structure, but asks for hyperplanes that weakly satisfy a whole band of edges, so that the band can be tiled, and minimizes a bound on the dependence distances.
  • Uniform programs. For uniform dependences, linear schedules go back to Karp, Miller and Winograd, and Lamport's hyperplane method is the one-dimensional case.

When to use it

Use it to find the parallelism of a static control program automatically: the result says which loops are parallel and which must stay sequential, and it works for imperfect nests with many statements. When locality and tiling matter more than the degree of parallelism, the Pluto algorithm is the usual choice. For a single perfect loop nest with uniform dependences, a unimodular transformation or the hyperplane method is simpler.

Pitfalls

  • Affine programs only. The dependence polyhedra and the Farkas linearization need affine loop bounds and affine subscripts. Index arrays, non-affine subscripts and data-dependent conditions take the program out of the model.
  • A legal schedule can be slow. The matrix-vector schedule θS2=j+1\theta_{S2} = j + 1 runs the rows in parallel and walks down the columns of L, which has poor locality for a row-major array. It also needs one barrier per time step. The algorithm counts satisfied edges and knows nothing about caches, vector units or synchronization costs.
  • Large coefficients. A vertex of the first linear program can have large coefficients, and scaling to integers can make them larger. Loops generated from such a schedule have large strides and many empty iterations. A second objective, as in line L6, or a lexicographic minimum, keeps them small.
  • Keep εe≤1\varepsilon_e \le 1. Without the bound, the linear program is unbounded, because the schedule can be scaled up without limit.
  • Empty polyhedra. The affine Farkas lemma needs a nonempty PeP_e. An empty dependence polyhedron must be dropped before the schedule is built. Otherwise its Farkas equations can have no solution, or they restrict the schedule for no reason.
  • Memory-based edges limit parallelism. Anti and output dependences force orders that array expansion could remove. Feeding the algorithm the exact dataflow edges gives more freedom, but then the generated code must expand the arrays.

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.

feautrier_scheduling.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/feautrier-scheduling/. The authors are listed in prov/7EMC3G.jsonl.
"""Feautrier's multidimensional affine scheduling (greedy version).

A static control program has statements with polyhedral domains in their
loop counters and the parameters. Each dependence edge e : S -> T is a
polyhedron P_e of pairs (s, t). A schedule gives each statement a list of
affine forms; it is legal when Theta_S(s) <lex Theta_T(t) on every P_e.

One dimension at a time, a linear program finds affine forms theta that
weakly satisfy every remaining edge (theta_T(t) - theta_S(s) >= eps_e with
0 <= eps_e <= 1) and maximizes the sum of the eps_e. Legality on the whole
polyhedron is linear thanks to the affine form of Farkas' lemma. Edges with
eps_e = 1 are strongly satisfied and leave; the rest go to the next
dimension.

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 gcd, lcm


# ---------------------------------------------------------------- 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 holds the reduced costs (up to a positive factor) and
    obj[j] > 0 means column j improves. Dantzig's rule picks the largest
    reduced cost, and ties in the ratio test are broken lexicographically on
    the columns `lexcols` (the start basis), which avoids cycling. After a
    fixed number of pivots the run moves to Bland's rule for good, 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 list of optimal values (Fractions), or 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)
    # phase 1: maximize -sum(art), reduced costs = sum of rows on non-art cols
    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
    # drive artificials out of the basis, drop redundant rows
    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)
    # phase 2
    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:
    """A small modelling layer: named variables (free or >= 0), linear
    equalities and inequalities, and an objective to maximize."""

    def __init__(self):
        self.cols = {}          # name -> list of (column, sign)
        self.eqs = []           # (dict name -> coef, rhs)
        self.ncol = 0

    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):
        """sum coefs >= rhs, with a new slack."""
        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()}


# ------------------------------------------------------------ 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):
        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):
    """Rational feasibility of {x : e(x) >= 0}, with free variables."""
    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 level: a list of (S, T, constraints) in the
    variables s0.., t0.. and the parameters. A pair (S(s), T(t)) is in it when
    both touch one element, one of them writes it, and S(s) runs first."""
    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))
        if not accs:
            continue
        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))
    return edges


# ------------------------------------------------------- Feautrier scheduling

def coef(S, k, x):
    return f"{S.name}.{x}.{k}"


def theta_terms(prog, S, k, sign, prefix):
    """theta_S at dimension k, renamed: {variable: column name}, as pairs
    (variable or "", column, sign)."""
    out = [(f"{prefix}{j}", coef(S, k, f"i{j}"), sign) for j in range(len(S.iters))]
    out += [(p, coef(S, k, p), sign) for p in prog.params]
    out.append(("", coef(S, k, "c"), sign))
    return out


def farkas(lp, terms, cons, tag, eps):
    """Add: psi - eps = lambda_0 + sum lambda_i c_i, identically in all the
    variables, with lambda >= 0 (the affine form of Farkas' lemma). Here psi
    is an affine form whose coefficients are LP columns, given by `terms`,
    and the c_i >= 0 are the constraints `cons`. Then psi >= eps on cons.
    When both c and -c are in cons, one free multiplier serves the pair."""
    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)
    cons = kept
    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
    variables = set(eq) | {v for c in cons for v in c}
    for v in variables:
        row = dict(eq.get(v, {}))
        for lam, c in zip(lams, cons):
            if c.get(v):
                row[lam] = row.get(lam, 0) - c[v]
        if v == "":
            row[lam0] = row.get(lam0, 0) - 1
            if eps is not None:
                row[eps] = row.get(eps, 0) - 1
        lp.eq(row, 0)


def edge_terms(prog, e, k):
    S, T, _ = e
    return theta_terms(prog, T, k, 1, "t") + theta_terms(prog, S, k, -1, "s")


def nonnegative(lp, prog, k):
    """theta_S >= 0 on the domain of S, for every statement (Feautrier's
    convention: time starts at 0)."""
    for S in prog.stmts:
        sn = {v: f"s{j}" for j, v in enumerate(S.iters)}
        cons = [rename(c, sn) for c in S.domain] + list(prog.context)
        farkas(lp, theta_terms(prog, S, k, 1, "s"), cons, f"pos.{S.name}", None)


def new_lp(prog, k):
    lp = LP()
    for S in prog.stmts:
        for x in [f"i{j}" for j in range(len(S.iters))] + prog.params + ["c"]:
            lp.var(coef(S, k, x), free=True)
    nonnegative(lp, prog, k)
    return lp


def one_dimension(prog, edges, k):
    """Return (theta, strong): theta maps a statement name to an affine form
    in its iterators and the parameters; strong is the set of edge indices
    that this dimension satisfies strongly."""
    lp = new_lp(prog, k)
    eps = {}
    for idx, e in enumerate(edges):
        eps[idx] = lp.var(f"eps{k}.{idx}")
        lp.ge({eps[idx]: -1}, -1)                                  # eps <= 1
        farkas(lp, edge_terms(prog, e, k), e[2], f"e{idx}", eps[idx])  # @line L4
    sol = lp.maximize({eps[i]: 1 for i in eps})  # @line L5
    strong = {i for i in eps if sol[eps[i]] == 1}
    assert all(sol[eps[i]] in (0, 1) for i in eps)
    # second LP: the same strong set, with the smallest coefficients
    lp2 = new_lp(prog, k)
    absvars = {}
    for S in prog.stmts:
        for x in [f"i{j}" for j in range(len(S.iters))] + prog.params + ["c"]:
            v = coef(S, k, x)
            a = lp2.var("abs." + v)
            lp2.ge({a: 1, v: -1}, 0)
            lp2.ge({a: 1, v: 1}, 0)
            absvars[a] = 1 if x != "c" else Fraction(1, 1000)
    one = lp2.var("one")
    lp2.eq({one: 1}, 1)
    for idx, e in enumerate(edges):
        farkas(lp2, edge_terms(prog, e, k), e[2], f"e{idx}", one if idx in strong else None)
    sol = lp2.maximize({a: -w for a, w in absvars.items()})  # @line L6
    theta = {}
    for S in prog.stmts:
        f = {}
        for j in range(len(S.iters)):
            f[S.iters[j]] = sol[coef(S, k, f"i{j}")]
        for p in prog.params:
            f[p] = sol[coef(S, k, p)]
        f[""] = sol[coef(S, k, "c")]
        theta[S.name] = {v: c for v, c in f.items() if c}
    return theta, strong


def feautrier_schedule(prog):
    """Multidimensional schedule: a dict from statement names to lists of
    affine forms, and the list of strong sets per dimension."""
    edges = dependences(prog)  # @line L1
    left = list(range(len(edges)))
    sched = {S.name: [] for S in prog.stmts}
    report = []
    k = 0
    while left:  # @line L2
        sub = [edges[i] for i in left]  # @line L3
        theta, strong = one_dimension(prog, sub, k)
        assert strong, "no edge satisfied: impossible for a static control program"
        d = lcm(*[c.denominator for f in theta.values() for c in f.values()] or [1])
        for name in sched:  # @line L7
            sched[name].append({v: c * d for v, c in theta[name].items()})
        report.append({left[i] for i in strong})
        left = [left[i] for i in range(len(left)) if i not in strong]  # @line L8
        k += 1  # @line L9
    return sched, edges, report  # @line L10


# ------------------------------------------------------------ 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 schedule_vector(prog, sched, name, point, env):
    S = prog.by_name[name]
    e = dict(env)
    e.update(zip(S.iters, point))
    return tuple(evaluate(f, e) for f in sched[name])


def run(prog, env, box, order_key=None, rng=None):
    """Run the instances in the original order, or sorted by order_key; ties
    are run in a random order (they are the parallel instances)."""
    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(sched):
    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"
    return {n: "(" + ", ".join(fmt(f) for f in fs) + ")" for n, fs in sched.items()}


# ------------------------------------------------------------------ examples

def running_sum():
    """for i = 0 to N: for j = 0 to N: S: s = s + A[i][j]"""
    s = Stmt("S", ["i", "j"], [0, 0, 0], [F(i=1), F(N=1, i=-1), F(j=1), F(N=1, j=-1)],
             ("s", []), [("s", []), ("A", [F(i=1), F(j=1)])])
    return Program(["N"], [F(N=1)], [s])


def matvec():
    """for i = 0 to N-1: S1: y[i] = 0; for j = 0 to i: S2: y[i] += L[i][j] * x[j]"""
    s1 = Stmt("S1", ["i"], [0, 0], [F(i=1), F(N=1, i=-1, c=-1)], ("y", [F(i=1)]), [])
    s2 = Stmt("S2", ["i", "j"], [0, 1, 0], [F(i=1), F(N=1, i=-1, c=-1), F(j=1), F(i=1, j=-1)],
              ("y", [F(i=1)]), [("y", [F(i=1)]), ("L", [F(i=1), F(j=1)]), ("x", [F(j=1)])])
    return Program(["N"], [F(N=1, c=-1)], [s1, s2])


def reverse_copy():
    """for i = 0 to N: S1: x[i] = f(i);  for j = 0 to N: S2: y[j] = x[N - j]"""
    s1 = Stmt("S1", ["i"], [0, 0], [F(i=1), F(N=1, i=-1)], ("x", [F(i=1)]), [])
    s2 = Stmt("S2", ["j"], [1, 0], [F(j=1), F(N=1, j=-1)], ("y", [F(j=1)]), [("x", [F(N=1, j=-1)])])
    return Program(["N"], [F(N=1)], [s1, s2])


def stencil():
    """for i = 1 to N: for j = 1 to N: S: 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])


if __name__ == "__main__":
    for name, prog in [("running sum", running_sum()), ("matvec", matvec()),
                       ("reverse copy", reverse_copy()), ("stencil", stencil())]:
        sched, edges, report = feautrier_schedule(prog)
        print(name, len(edges), "edges", show(sched), [sorted(r) for r in report])
test_feautrier_scheduling.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/feautrier-scheduling/. The authors are listed in prov/7EMC3G.jsonl.
"""Tests: every schedule must order every dependence that a brute-force
search finds, and running the instances in schedule order, with ties in a
random order, must give the same memory as the original program."""

import random
import unittest

from feautrier_scheduling import (
    F, LP, Program, Stmt, brute_dependences, dependences, feautrier_schedule, form, instances,
    matvec, reverse_copy, run, running_sum, schedule_vector, show, stencil,
)


def check_legal(test, prog, sched, ns):
    pairs = 0
    for n in ns:
        env = {"N": n}
        for (a, p), (b, q) in brute_dependences(prog, env, 2 * n + 2):
            va = schedule_vector(prog, sched, a, p, env)
            vb = schedule_vector(prog, sched, b, q, env)
            test.assertLess(va, vb, f"{a}{p} -> {b}{q} at N={n}")
            pairs += 1
    return pairs


def check_runs(test, prog, sched, ns, seed):
    rng = random.Random(seed)
    for n in ns:
        env = {"N": n}
        want = run(prog, env, 2 * n + 2)
        for _ in range(3):
            got = run(prog, env, 2 * n + 2,
                      lambda name, p: schedule_vector(prog, sched, name, p, env), rng)
            test.assertEqual(got, want, f"N={n}")


def check_all(test, prog, ns, seed=0):
    sched, edges, report = feautrier_schedule(prog)
    # each dimension strongly satisfies at least one edge, each edge once
    test.assertTrue(all(report))
    seen = sorted(i for r in report for i in r)
    test.assertEqual(seen, list(range(len(edges))))
    pairs = check_legal(test, prog, sched, ns)
    check_runs(test, prog, sched, ns, seed)
    return sched, report, pairs


class Examples(unittest.TestCase):
    def test_lp(self):
        lp = LP()
        lp.var("x")
        lp.var("y")
        lp.ge({"x": -1, "y": -2}, -4)
        lp.ge({"x": -3, "y": -1}, -6)
        sol = lp.maximize({"x": 1, "y": 1})
        self.assertEqual((sol["x"], sol["y"]), (F(c=8)[""] / 5, F(c=6)[""] / 5))

    def test_running_sum_needs_two_dimensions(self):
        sched, report, pairs = check_all(self, running_sum(), range(0, 4))
        self.assertEqual(show(sched), {"S": "(i, j)"})
        self.assertGreater(pairs, 100)

    def test_matvec_is_one_dimensional(self):
        sched, report, _ = check_all(self, matvec(), range(1, 5))
        self.assertEqual(len(report), 1)
        # latency N: the last instance S2(N-1, N-1) runs at time N
        for n in range(1, 5):
            env = {"N": n}
            last = max(schedule_vector(matvec(), sched, S.name, p, env)
                       for _, S, p in instances(matvec(), env, n + 1))
            self.assertEqual(last, (n,))

    def test_reverse_copy_is_fully_parallel(self):
        sched, _, _ = check_all(self, reverse_copy(), range(0, 4))
        self.assertEqual(show(sched), {"S1": "(0)", "S2": "(1)"})

    def test_stencil_wavefront(self):
        sched, report, _ = check_all(self, stencil(), range(1, 5))
        self.assertEqual(show(sched), {"S": "(i + j)"})


def random_program(rng):
    """One or two outer loops with at most three statements at depth 1 or 2
    that write and read 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 linear programs; they are
        # skipped to keep the test fast
        rng = random.Random(1992)
        total, dims, t = 0, set(), 0
        while t < 20:
            prog = random_program(rng)
            if len(dependences(prog)) > 14:
                continue
            t += 1
            sched, report, pairs = check_all(self, prog, range(0, 4), seed=t)
            total += pairs
            dims.add(len(report))
        self.assertGreater(total, 1000)
        self.assertTrue({1, 2} <= dims)


if __name__ == "__main__":
    unittest.main()

History

Paul Feautrier published the two parts of "Some efficient solutions to the affine scheduling problem" in 1992. Part I applies the affine form of Farkas' lemma to dependence polyhedra and finds one-dimensional schedules by linear programming. Part II shows that some programs have no one-dimensional schedule and gives the greedy construction of multidimensional schedules on this page. The work extends the linear schedules of Karp, Miller and Winograd (1967) for uniform recurrences and Lamport's hyperplane method (1974) to programs with affine dependences and many statements. Darte and Vivien later studied how much parallelism such schedules can find. In 2002, Vivien showed that, inside its own framework, the greedy method does not lose parallelism because of the way it is designed. In 2008, Bondhugula and his coauthors used the same linearization in the Pluto algorithm, with a cost function aimed at tiling and locality.

References

  1. Paul Feautrier, Some efficient solutions to the affine scheduling problem, Part I, One-dimensional time, International Journal of Parallel Programming 21(5), 1992, 313-347, the affine form of Farkas' lemma applied to dependence polyhedra, the linear constraints for legal one-dimensional schedules, and the nonnegativity of the schedule on the domains
  2. Paul Feautrier, Some efficient solutions to the affine scheduling problem, Part II, Multidimensional time, International Journal of Parallel Programming 21(6), 1992, 389-420, the greedy construction of a multidimensional schedule, one dimension at a time, that strongly satisfies as many remaining dependences as possible, and the proof that it always terminates for static control programs
  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