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)
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
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 in a context . Statement has depth and an iteration domain , a polyhedron that is bounded for each . The loop counters are nonnegative on , which a shift of each loop gives. A set of dependence edges , each with a dependence polyhedron of pairs such that must run after . This page and its implementation use memory-based dependences (flow, anti and output), one polyhedron per pair of accesses and per depth . At depth , for and . At the "same iteration" depth, the two instances share all their common loops and comes first in the text.
Output. For each statement , a list of affine forms in and such that for every edge and every . 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 weakly satisfies if on , and strongly satisfies it if on . A list of dimensions is legal for when some dimension strongly satisfies and all earlier dimensions weakly satisfy it.
The algorithm
Each dimension is the solution of a linear program whose unknowns are the coefficients of for every statement, one variable per remaining edge, and the Farkas multipliers. The condition " on " becomes, by the affine Farkas lemma,
where are the constraints of . The identity holds for all values of , and , so it means one linear equation per variable and one for the constant. The same lemma gives Feautrier's condition on .
FEAUTRIER-SCHEDULE(program)- 1
E <- the dependence polyhedra P_e of the program, one per pair of accesses and depth - 2
while E is not empty do - 3
E' <- the edges still in E; theta_S has free coefficients, with theta_S >= 0 on D_S for each S - 4
for 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 - 5
solve the linear program: maximize the sum of the eps_e; G <- { e : eps_e = 1 } - 6
solve it again with eps_e = 1 on G and eps_e = 0 elsewhere, minimizing the sum of |coefficients| - 7
scale theta to integer coefficients and append theta_S to Theta_S for every S - 8
E <- E minus G - 9
go to the next dimension - 10
return Theta
Why is 0 or 1. Line L5 never returns a fraction. Take a feasible solution in which the smallest positive is . Divide every by . Every difference grows by the factor , so each edge with now has a difference of at least 1 on , and the others still have at least 0. The sum of the grows. So at an optimum every 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 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 is a correct dimension.
Line L7. The linear program works over the rationals. Multiplying all of one dimension by the least common multiple of the denominators keeps every difference at least 0, and the strong ones at least .
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: at depth 1 (, with and free in ) and at depth 2 (, ). The affine scheduling problem page shows that no single affine form strongly satisfies both.
- In the first round, must weakly satisfy . On the difference takes the value when , and for large this forces . Then strongly satisfies and gives difference 0 on . The best sum is 1, and .
- In the second round only is left, and strongly satisfies it.
The schedule is , 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 to and from to with . One round strongly satisfies all of them with and . At time 0 all the instances run in parallel. At time , every row adds its -th term in parallel. The last instance runs at time , so there are time steps, against 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 , one round gives , the wavefront schedule of Lamport's hyperplane method.
Reverse copy. For x[i] = f(i) over followed by y[j] = x[N - j] over , the schedule is and . 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 on the whole polyhedron , for nonempty . By the scaling argument above, the edges with are strongly satisfied, and all other remaining edges are weakly satisfied.
- Each round makes progress. If is not empty, some affine dimension strongly satisfies at least one edge of and weakly satisfies the others. Take the original schedule vector , where is a text position, and the first position at which some edge of is strongly satisfied. All edges of have equal components before , so the component at weakly satisfies all of them. It is also nonnegative when the loop counters are. So is never empty.
- Termination. Each round removes at least one edge, so there are at most rounds.
- Legality. An edge removed in round is weakly satisfied by rounds to , because it was still in , and strongly satisfied by round . So for each pair in , 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 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 in the context . Statement has depth and a domain , a polyhedron that is bounded for each , on which every loop counter is nonnegative. Each edge of the input set has a nonempty polyhedron , given by affine constraints 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 the constraints contain for and ; at the "same iteration" depth they contain for all common loops, and comes before in the text of the innermost common loop. For an affine form per statement and an edge , write .
Claim. The algorithm stops after at most rounds. The list it returns satisfies for every , every and every integer pair . If some affine with on every strongly satisfies every edge of , the list has one dimension.
Step 1: the linear constraints say what they should
Lemma 1 (affine Farkas lemma). Let be a nonempty polyhedron, with affine . An affine form is nonnegative on all of if and only if for some .
This is Corollary 7.1h of Schrijver's book. The "if" part is direct: each term is nonnegative on .
The variables of are , and . 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 are linear in the unknown coefficients of and in , so line L4 adds linear equations in the unknowns , and , with . By Lemma 1, a vector of unknowns satisfies them if and only if on . In the same way, the constraints of line L3 hold if and only if on the polyhedron of and for each . When both and 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 be the current set of edges and let be the set of feasible points of line L4: affine with on each , and with on for .
Lemma 2. At every optimal point of line L5, every is 0 or 1.
Proof. Let be optimal and suppose some lies strictly between 0 and 1. Let be the least positive ; then . Set and if and otherwise. Then on . For an edge with , on . For an edge with , . So . Its objective is the number of positive , which is larger than , because one term is less than 1. This contradicts optimality.
So the set of line L5 is a set of edges that one feasible strongly satisfies, while it weakly satisfies all of . 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 , strongly satisfies every edge of , and is nonnegative on every domain.
Proof. Line L6 solves the constraints of Step 1 with fixed to 1 on and to 0 on . 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 has on for , for , and on . Line L7 multiplies every by the same integer . This multiplies each by , so the three properties stay true, and the coefficients become integers.
Step 4: every round removes an edge
Let be the original schedule vector of , where is the text position at depth . Its components are affine in and nonnegative on , because the counters are nonnegative. For an edge with common loops, define its position : if has depth , then , the place of the counter ; if is a "same iteration" edge, then , the place of . Number the components from 1.
Lemma 4. For an edge and every , the components of and are equal, and component of exceeds that of by at least 1.
Proof. The components before are (or up to ). The text positions for are equal, because the two statements share these loops. The counters before depth are equal by the constraints of . At position , by the constraints. At position , , because these are different integers and comes first.
Lemma 5. If is not empty, the set of line L5 is not empty.
Proof. Let , and let reach the minimum. Every edge has , and , so component belongs to the common prefix of the two statements of , where both vectors have the same kind of entry. Define as component of for every statement that has one, and as for the others. Then on . By Lemma 4, on if , and on if . So , with and the other , 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 , so .
Step 5: conclusion
Termination. By Lemma 5, line L8 removes at least one edge in each round, so the loop runs at most times.
Legality. Take and let be the round that removes it. For each round , was in , so by Lemma 3 the dimension weakly satisfies : on . The dimension strongly satisfies it: . So for every , the vector has nonnegative entries up to place and a positive entry at place . Its first nonzero entry is at some place and is positive, so .
One dimension. If an affine with on each strongly satisfies every edge of , then with every is feasible in the first round, and its objective is the largest possible. So , 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 before 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 . So it lies in some , and the schedule keeps its order. Instances with equal time vectors are therefore independent, and they may run in any order or in parallel.
Complexity
Building the edges takes one rational feasibility test per pair of accesses and depth, at most tests. There are at most rounds, each with two linear programs, so the total is linear program solves, . The linear programs have one unknown per schedule coefficient, per edge and per constraint of each , and one equation per variable of each . So is linear in the size of the dependence polyhedra. With the simplex method, 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 .
- 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 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 . 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 . 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.
# 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
- 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
- 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
- Alexander Schrijver, Theory of Linear and Integer Programming, Wiley, 1986, Corollary 7.1h (the affine form of Farkas' lemma)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7EMC3G Edit this page History Report an error Markdown