Algorithmcore
Allen-Kennedy vectorization algorithm
Also called Allen-Kennedy codegen.
Distributes a loop nest by the strongly connected components of its dependence graph, level by level, and turns each statement that is on no cycle into a vector statement.
- Time
- O(n (r + e)) worst
- Space
- O(r + e) extra
- Where
- e = the number of edges of the dependence graph; n = the depth of the loop nest; r = the number of statements
- Model
- Word RAM
- Properties
- deterministicrecursive
- Evidence
- Proof sketchCode in 1 languages
The Allen-Kennedy algorithm, called codegen by its authors, turns a loop nest into vector statements and sequential loops. At level it builds the dependence graph of the statements with the dependences that are carried at level or deeper or are loop independent, splits it into strongly connected components, and emits the components in topological order. A component with a cycle keeps a sequential loop at level and is handled again at level . A statement that is on no cycle becomes a vector statement over all its loops from level inward. Allen and Kennedy built it for the PFC translator from Fortran to vector Fortran at Rice University, and published it in 1987.
In plain words
A compiler wants to turn a loop into array operations, such as "add these two whole arrays", that a vector machine runs fast. A statement can become an array operation only if no iteration of it needs a result of another iteration of the same loop. The algorithm draws an arrow between two statements when one must run before the other. Statements that wait for each other in a circle must stay in an ordinary loop, because the order of their iterations matters. Every other statement can run as one array operation, at the right place in the order of the arrows. Inside each circle, the algorithm looks one loop deeper, where some arrows disappear, and tries again.
The problem
Input. A loop nest that forms one chain of loops: loop 1 holds loop 2, which holds loop 3, up to depth . Statement is inside the loops 1 to . The statements and their text order are given. The dependence graph has an edge labelled with level for each dependence from an instance of to an instance of that is carried at level , and with level for a loop-independent one.
Output. An equivalent program built only from the original loops (run sequentially) and vector statements. A vector statement over the loops to runs, for fixed outer indices , all instances of at once: it reads all its operands, then it writes all its results, as an array assignment in Fortran 90 does. It is legal only if no dependence joins two of its instances.
The dependence graph comes from dependence testing. The algorithm uses only the level of each edge, not its distance.
The algorithm
CODEGEN(R, k) ▷ R: a set of statements; k: the current loop level- 1
E <- the edges of D between statements of R with level >= k - 2
pi_1, ..., pi_m <- the strongly connected components of (R, E), in topological order - 3
for c <- 1 to m do - 4
if pi_c has two or more statements, or a statement with an edge to itself in E then - 5
emit "for i_k = L_k to U_k:" ▷ a sequential loop - 6
CODEGEN(pi_c, k + 1) - 7
else - 8
S <- the only statement of pi_c - 9
emit S as a vector statement over the loops k to d_S ▷ a scalar statement if d_S = k - 1
The call CODEGEN(all statements, 1) produces the program. Line L1 drops the dependences carried at levels to , because the enclosing sequential loops already keep them, and keeps the loop-independent ones (level ) at every level. Line L2 uses Tarjan's algorithm and a topological sort of the component graph; ties go to the text order. A component with a cycle needs the loop at level to stay sequential, since some of its dependences go from one iteration of that loop to a later one in both directions around the cycle. At level the edges carried at level are gone, so the cycle may break.
Example
This is a small copy of the example in Allen and Kennedy's book, with all loops from 1 to 4 and :
for i = 1 to 4:
S1: X[i] = Y[i] + 10
for j = 1 to 4:
S2: B[j] = A[j][N]
for k = 1 to 4:
S3: A[j+1][k] = B[j] + C[j][k]
S4: Y[i+j] = A[j+1][N]
The dependence graph has these edges, found by checking all pairs of instances (LI means loop independent, level 4):
| edge | levels | reason |
|---|---|---|
| S2 to S2 | 1 | output on , written in every |
| S2 to S3 | 1, LI | flow on |
| S3 to S2 | 1, 2 | flow on , read as at or at a later |
| S3 to S3 | 1 | output on , written in every |
| S3 to S4 | 1, LI | flow on |
| S4 to S3 | 1 | anti on |
| S4 to S4 | 1 | output on |
| S4 to S1 | 1 | flow on |
Level 1. All edges count. The components are , with the cycle , and . The edge puts the big component first. So the loop stays sequential around the first one, and S1 becomes a vector statement over after it.
Level 2, inside the loop. The edges of level 2 or more among S2, S3, S4 are (LI), (level 2) and (LI). The components are , with a cycle, and then . So the loop stays sequential around S2 and S3, and S4 becomes a vector statement over .
Level 3, inside the loop. Only (LI) is left. There is no cycle. S2 has depth 2, so it is a scalar statement, and S3 becomes a vector statement over .
for i = 1 to 4:
for j = 1 to 4:
S2: B[j] = A[j][2]
S3: A[j+1][1:4] = B[j] + C[j][1:4]
S4: Y[i+1:i+4] = A[2:5][2]
S1: X[1:4] = Y[1:4] + 10
S1 moved to the end, after all of the loop. This is legal, because no dependence goes from S1 to the other statements, and it is needed, because S1 reads values of that S4 writes in earlier iterations.
Correctness
The full proof is in proofs/correctness.md. It has three parts.
Every dependence is kept. Take a dependence from to with level . Follow the recursion to the deepest call CODEGEN that has both and in . If , this call sits inside the sequential loop at level , which runs iteration before . If , the edge is in line L1. The two statements cannot be in one component, since that component would be cyclic and line L6 would make a deeper call with both. So the topological order emits all of the component of before all of that of , for the same outer indices. An acyclic component is one statement with no edge to itself of level or more, so no dependence joins two instances of one vector statement, and the read-then-write semantics is exact.
Each statement is vectorized at the first level where it is on no cycle. Let be the graph of the edges with level or more. These graphs shrink as grows. The region that contains at level is the component of in , and it contains the component of in . So becomes a vector statement at the smallest for which is on no cycle of .
No program of the same kind does better. Suppose some program built from the original loops, loop distribution, statement order and vector statements runs as a vector statement over the loops to , and is on a cycle of . All the statements of the cycle are pieces in one sequence for each fixed , and the order of the pieces is the same for all outer indices. Every edge of the cycle has its source and sink in the same outer iteration, so it forces its source piece to be no later than its sink piece, and strictly earlier when one of them is the piece of . Around the cycle this gives the piece of before itself, which is impossible. Darte and Vivien proved more in 1997: with dependence levels as the only information, no transformation at all finds more parallel loops.
Proof: Allen-Kennedy codegen keeps every dependence and vectorizes each statement as early as possiblefull
We use the notation of the page. The loops form one chain of depth , so for each the statements of depth or more are one contiguous run of the text, inside loop . Statement is inside the loops to . An instance is with . A dependence pair goes from an instance that runs first in the sequential program to an instance . Its level is the first common loop where and differ, and then . If they agree on all common loops, the level is (loop independent). For , the graph has the statements as nodes and an edge when some pair from to has level or more.
A generated program is a tree. A loop node at level runs its children in order for each value of , in increasing order. A vector node runs, for the current values of , all instances of with those outer indices as one step: it reads all its operands, then writes all its results. Each statement is in exactly one vector node, and the loops above it run all values of , so each instance runs in exactly one step.
By the reordering theorem on the legality page, the generated program computes the same memory as the original one if two conditions hold: every dependence pair runs in order (the step of the source strictly before the step of the sink), and no dependence pair has both instances in one step. The second condition makes the read-then-write rule of a step exact: no instance of the step reads or overwrites a cell that another instance of the same step writes.
Lemma 1 (backward edges and cycles). (a) A loop-independent pair goes from a statement to a statement strictly later in the text. (b) Every statement on a cycle of , with , has depth at least . (c) has no cycle.
Proof. (a) If the instances agree on all common loops, the sequential program runs them in text order, and two different instances of one statement cannot agree on all its loops. (c) follows from (a), because the text positions only grow along a path of . For (b), an edge of that does not go strictly forward in the text comes, by (a), from a pair of level with , so both of its statements share loop and have depth at least . Take a cycle of . Let be its statement that comes first in the text, and the one that comes last. The edge of the cycle into and the edge out of do not go strictly forward, so and have depth at least . All statements of the cycle lie between and in the text, and the statements of depth or more are contiguous, so all of them have depth at least .
Lemma 2 (regions). For , the region of a call CODEGEN is a strongly connected component of restricted to the region of the parent call, with a cycle, and all its statements have depth at least . The call runs inside sequential loop nodes at the levels to .
Proof. Line L6 makes the call at level for a component of the edges of level or more that has two statements or a self edge, so it has a cycle. Lemma 1(b) gives the depths. Line L5 emits the loop node at level around the call, and by induction the parent call is inside the loops at levels to .
Theorem 1 (every dependence is kept). For every dependence pair from to , with level , the step of comes strictly before the step of , and the two instances are not in one step.
Proof. The root call has both and in its region. Let CODEGEN be the deepest call whose region contains both. There are two cases.
Case A: . By Lemma 2, the call runs inside a sequential loop node at level , and both steps are below it. The instances agree on , so they are in the same run of that loop node, and , so the step of runs in an earlier iteration of it. The pair is in order, and not in one step.
Case B: . Then is an edge in the set of line L1. If and were in the same component, that component would have a cycle (two statements, or the self edge when ), and line L6 would call CODEGEN at level on a region that holds both, against the choice of . So they are in different components, and the edge goes from the component of to that of . Line L2 puts the component of first. The instances agree on , so they are in the same run of the code of this call, in which all the code of the component of runs before all the code of the component of . The pair is in order, and not in one step.
Theorem 2 (the vector level). Statement becomes a vector node where is the least integer such that is on no cycle of . Also .
Proof. The graphs shrink as grows: . By Lemma 1(b), is on no cycle of when , and by Lemma 1(c) when . So the least is at most .
Let be the set of statements that are on a common cycle with in , together with ; this is the strongly connected component of in . We show by induction on : if the call at level whose region contains exists, its region contains , and the component of that its line L2 finds is exactly . For the region is all statements and is all edges of . For the step, the call at level exists only if line L4 found cyclic, and its region is . A cycle of through is a cycle of , so , and line L1 at level keeps every edge of inside . So the component of there is .
Line L4 at level finds the component of cyclic exactly when is on a cycle of . So the calls go down while is on a cycle, and becomes a vector node at the first level where it is not.
Theorem 3 (maximality in the distribution model). Take any program built from the original loops, in their original nesting and direction, by loop distribution and by reordering the pieces at each level, in which each statement is in one vector node that replaces its loops to . If the program keeps every dependence pair in order and has no pair inside one step, then for each statement, where is the level of Theorem 2.
Proof. Assume that the program runs as with . Then is on a cycle of , which we take simple. If , a pair of instances of has level or more, so it shares and lies in one step, which is not allowed. So , and appears only at the two ends of the cycle.
By Lemma 1(b), every statement of the cycle has depth at least , so it is inside the loops to of the original program. In the new program these loops were distributed, and the pieces were ordered. At the level of the vector node , inside the loops to that hold it, consider the sequence of pieces that holds . Each statement of the cycle with the same as either runs in a piece of this sequence or runs entirely before or after the whole sequence; we give it the position or in those two cases and the index of its piece otherwise. The order of the pieces does not depend on . Write for the position of statement .
Each edge comes from a pair of level or more, so its two instances share . The program keeps the pair in order, so , because a later position runs later for the same outer indices. When one of and is , the inequality is strict: the piece of is the single step , and the other statement is not , so it is in another piece or outside the sequence. Around the cycle this gives , which is impossible.
Theorem 3 is limited to programs of this kind. Darte and Vivien (1997) proved a stronger result: if the only information about the dependences is their level, no transformation finds more parallel loops than Allen and Kennedy's algorithm.
Termination and cost. Each call at level calls itself only at level , and by Lemma 1(c) no call at level is made, so the depth of the recursion is at most . The regions of the calls at one level are disjoint. If each call passes the edges inside each child region down to that child, the work at one level is for line L1, Tarjan's algorithm and the topological sort. The total is time.
Complexity
Each call runs Tarjan's algorithm and a topological sort on the edges inside its region, in time. The regions of the calls at one level are disjoint, so one level costs in total, and there are at most levels. The worst case is time and extra space for the graph, the component lists and the recursion. In a real compiler the dependence tests that build the graph cost far more than codegen. The implementation on this page builds the graph by brute force over all pairs of instances on small loop bounds, which is quadratic in the number of instances and is only for testing.
Properties
- Distribution only. The algorithm never interchanges loops and never changes the order of iterations of a loop it keeps. It only distributes loops and reorders statements.
- Level information only. It uses the level of each edge and nothing else. The direction vectors and distances are not needed.
- Sequential loops are kept whole. A loop that stays sequential at level is a plain loop. Its inner part may still have vector statements and DOALL loops.
- Parallel loops as well as vectors. The same recursion, with "run as a parallel loop" instead of "emit as a vector statement", finds DOALL loops; that is the version that Darte and Vivien study.
Variants and improvements
- Breaking cycles first. Scalar expansion, renaming, node splitting and loop skewing remove some dependences or change their level before codegen runs. Allen and Kennedy describe them in the chapter on fine-grained parallelism of their book.
- Loop interchange. In a cyclic component, a loop that carries no dependence of the component can move inward, so that the vector statement runs along it; see loop interchange.
- Self anti-dependences. A statement such as
A[i] = A[i+1] + 1has a self edge that is an anti-dependence. The read-then-write semantics of a vector statement keeps it, so a compiler can ignore such edges in line L4. The plain algorithm does not. - Fixed-length vectors. A machine with vectors of elements runs a vector statement in strips of ; see strip mining and vectorization.
- Richer dependence information. With distance vectors or dependence polyhedra, more parallelism is possible, for example by skewing; the hyperplane method and Feautrier's scheduling use it.
When to use it
Use it in a vectorizing or parallelizing compiler for loop nests whose dependences are known only up to their level, or whose distances are not uniform. It is simple, fast and optimal for that information. For innermost-loop SIMD code on modern processors it is the core of loop vectorization, together with strip mining and alignment. For short straight-line code, SLP vectorization packs statements of one block instead.
Pitfalls
- Text order instead of topological order. With
S1: C[i] = A[i-1]andS2: A[i] = B[i], the only edge goes from S2 to S1, carried at level 1. The vector statements must run S2 first. Emitting them in text order reads before it is written. - Dropping loop-independent edges at deep levels. Line L1 must keep the edges of level at every level. Without them, two statements of one iteration can come out in the wrong order.
- Edges of level exactly . Line L1 takes level or more, not only level . Edges carried deeper still order the statements.
- Missing self edges. A single statement with a carried edge to itself, such as
A[i+1] = A[i] + 1, is a cycle. Treating every one-statement component as acyclic gives a wrong vector statement. - Element-by-element semantics. The proof uses the rule that a vector statement reads all operands before it writes. That holds for the statements that the algorithm emits, but not for a hand-written loop that a reader takes for a vector statement.
- A scalar on every iteration. A scalar temporary written in each iteration makes a cycle at every level. Expand it into an array first.
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/allen-kennedy-algorithm/. The authors are listed in prov/WZS56G.jsonl.
"""Allen-Kennedy vector code generation (codegen) on a chain of loops.
A program is one chain of loops: loop 1 holds loop 2, which holds loop 3,
and so on up to depth n. Loop l runs its index from bounds[l-1][0] to
bounds[l-1][1], both included. The statements are listed in text order.
Statement S sits at depth d (it is inside loops 1 to d) and has the form
W[f(i)] = c0 + c1 * R1[g1(i)] + ... + e . i (mod MOD)
where every subscript is affine in the d indices of S. The statements with
a depth of l + 1 or more must be contiguous in the text for every l, so that
the loops form one chain.
The dependence graph has an edge (S, T, level) for each pair of instances
S(i) before T(j) that touch the same cell, at least one of them a write.
The level is the first loop where i and j differ, or LI = n + 1 for a
loop-independent dependence. codegen(R, k) follows the page: it takes the
strongly connected components of the edges of level k or more inside R, in
topological order; a cyclic component becomes a sequential loop at level k
with a recursive call at level k + 1, and an acyclic one (a single
statement) becomes a vector statement over the loops k to depth(S).
"""
from itertools import product
MOD = (1 << 61) - 1
class Stmt:
"""A statement W[f(i)] = c0 + sum(c_r * R_r[g_r(i)]) + e . i."""
def __init__(self, name, depth, write, reads, coefs, const=1, idx_coefs=None):
self.name = name
self.depth = depth
self.write = write # (array, [(coeffs, const), ...])
self.reads = reads # list of (array, [(coeffs, const), ...])
self.coefs = coefs # one integer per read
self.const = const
self.idx_coefs = idx_coefs or [0] * depth
def cell(self, acc, it):
arr, subs = acc
return (arr,) + tuple(sum(a * x for a, x in zip(co, it)) + c for co, c in subs)
def value(self, mem, it, init):
v = self.const + sum(e * x for e, x in zip(self.idx_coefs, it))
for co, acc in zip(self.coefs, self.reads):
v += co * read(mem, self.cell(acc, it), init)
return v % MOD
class Program:
def __init__(self, bounds, stmts):
self.bounds = bounds # list of (lo, hi) per loop level
self.stmts = stmts
self.n = len(bounds)
check_chain(self)
def check_chain(prog):
"""The statements of depth > l form one contiguous run, for each l."""
for l in range(prog.n):
pos = [p for p, s in enumerate(prog.stmts) if s.depth > l]
if pos and pos[-1] - pos[0] + 1 != len(pos):
raise ValueError("the loops do not form one chain")
def read(mem, cell, init):
if cell not in mem:
mem[cell] = init(cell)
return mem[cell]
def instances(prog):
"""All statement instances (s, it) in the order of the sequential program."""
out = []
def body(level, prefix, ids):
p = 0
while p < len(ids):
s = ids[p]
if prog.stmts[s].depth == level:
out.append((s, prefix))
p += 1
else:
q = p
while q < len(ids) and prog.stmts[ids[q]].depth > level:
q += 1
lo, hi = prog.bounds[level]
for v in range(lo, hi + 1):
body(level + 1, prefix + (v,), ids[p:q])
p = q
body(0, (), list(range(len(prog.stmts))))
return out
def accesses(prog, inst):
s, it = inst
st = prog.stmts[s]
for acc in st.reads:
yield st.cell(acc, it), False
yield st.cell(st.write, it), True
def dependence_pairs(prog):
"""Brute force: every dependent pair of instances (src, snk), src first."""
seq = instances(prog)
by_cell = {}
for pos, inst in enumerate(seq):
for cell, w in accesses(prog, inst):
by_cell.setdefault(cell, []).append((pos, inst, w))
pairs = set()
for lst in by_cell.values():
for a in range(len(lst)):
for b in range(a + 1, len(lst)):
pa, ia, wa = lst[a]
pb, ib, wb = lst[b]
if (wa or wb) and pa != pb:
pairs.add((ia, ib) if pa < pb else (ib, ia))
return pairs
def level_of(prog, src, snk):
"""First loop level where the common indices differ, or n + 1 (loop independent)."""
(s, i), (t, j) = src, snk
c = min(prog.stmts[s].depth, prog.stmts[t].depth)
for l in range(c):
if i[l] != j[l]:
return l + 1
return prog.n + 1
def dependence_graph(prog, pairs=None):
"""Edges (s, t, level) of the statement-level dependence graph."""
if pairs is None:
pairs = dependence_pairs(prog)
return {(a[0], b[0], level_of(prog, a, b)) for a, b in pairs}
def tarjan_scc(nodes, succ):
"""Strongly connected components (Tarjan); returns a list of lists."""
index, low, on, stack, comps = {}, {}, set(), [], []
counter = [0]
def visit(v):
index[v] = low[v] = counter[0]
counter[0] += 1
stack.append(v)
on.add(v)
for w in succ.get(v, ()):
if w not in index:
visit(w)
low[v] = min(low[v], low[w])
elif w in on:
low[v] = min(low[v], index[w])
if low[v] == index[v]:
comp = []
while True:
w = stack.pop()
on.discard(w)
comp.append(w)
if w == v:
break
comps.append(sorted(comp))
for v in nodes:
if v not in index:
visit(v)
return comps
def topo_components(nodes, edges):
"""SCCs in a topological order of the condensation, ties by text order."""
succ = {}
for a, b in edges:
succ.setdefault(a, []).append(b)
comps = tarjan_scc(sorted(nodes), succ)
where = {v: c for c, comp in enumerate(comps) for v in comp}
indeg = [0] * len(comps)
out = [set() for _ in comps]
for a, b in edges:
ca, cb = where[a], where[b]
if ca != cb and cb not in out[ca]:
out[ca].add(cb)
indeg[cb] += 1
ready = sorted((comps[c][0], c) for c in range(len(comps)) if indeg[c] == 0)
order = []
while ready:
_, c = ready.pop(0)
order.append(comps[c])
for d in out[c]:
indeg[d] -= 1
if indeg[d] == 0:
ready.append((comps[d][0], d))
ready.sort()
return order
def codegen(prog, graph, region=None, k=1):
"""Allen-Kennedy codegen(R, k). Returns a list of nodes:
("loop", k, children) is a sequential loop at level k, and
("vec", s, k) runs statement s as a vector statement over loops k to depth(s)."""
if region is None:
region = list(range(len(prog.stmts)))
rs = set(region)
edges = [(a, b) for a, b, lev in graph if a in rs and b in rs and lev >= k] # @line L1
comps = topo_components(region, edges) # @line L2
code = []
for comp in comps: # @line L3
if len(comp) > 1 or (comp[0], comp[0]) in edges: # @line L4
assert all(prog.stmts[s].depth >= k for s in comp)
inner = codegen(prog, graph, comp, k + 1) # @line L6
code.append(("loop", k, inner)) # @line L5
else: # @line L7
s = comp[0] # @line L8
code.append(("vec", s, k)) # @line L9
return code
def vector_levels(code, out=None):
"""For each statement, the level k at which it is vectorized."""
if out is None:
out = {}
for node in code:
if node[0] == "loop":
vector_levels(node[2], out)
else:
out[node[1]] = node[2]
return out
def run_sequential(prog, init):
mem = {}
for s, it in instances(prog):
st = prog.stmts[s]
v = st.value(mem, it, init)
mem[st.cell(st.write, it)] = v
return mem
def run_code(prog, code, init, steps=None):
"""Run generated code. A vector statement reads all its operands, then
writes all its results. If steps is a dict, it records for each instance
the number of the step (vector statement execution) that ran it."""
mem = {}
counter = [0]
def run(nodes, prefix):
for node in nodes:
if node[0] == "loop":
lo, hi = prog.bounds[node[1] - 1]
for v in range(lo, hi + 1):
run(node[2], prefix + (v,))
else:
s, k = node[1], node[2]
st = prog.stmts[s]
ranges = [range(lo, hi + 1) for lo, hi in prog.bounds[k - 1:st.depth]]
its = [prefix[:k - 1] + rest for rest in product(*ranges)]
vals = [st.value(mem, it, init) for it in its]
for it, v in zip(its, vals):
mem[st.cell(st.write, it)] = v
if steps is not None:
for it in its:
steps[(s, it)] = counter[0]
counter[0] += 1
run(code, ())
return mem
NAMES = "ijklmn"
def show_sub(co, c, vec_from):
terms = []
for l, a in enumerate(co):
if a:
v = NAMES[l]
terms.append((v if a == 1 else "-" + v if a == -1 else f"{a}*{v}"))
s = "+".join(terms).replace("+-", "-")
if c or not s:
s = (s + ("+" if c > 0 and s else "") + str(c)) if s else str(c)
return s
def show(prog, code, indent=0):
"""Print generated code; a vector statement lists its vector indices."""
lines = []
pad = " " * indent
for node in code:
if node[0] == "loop":
l = node[1]
lo, hi = prog.bounds[l - 1]
lines.append(f"{pad}for {NAMES[l - 1]} = {lo} to {hi}:")
lines.extend(show(prog, node[2], indent + 1))
else:
s, k = node[1], node[2]
st = prog.stmts[s]
def acc(a):
arr, subs = a
return arr + "".join("[" + show_sub(co, c, k) + "]" for co, c in subs)
parts = [acc(r) for r in st.reads] + ([str(st.const)] if st.const else [])
rhs = " + ".join(parts) or "0"
vec = ",".join(NAMES[l] for l in range(k - 1, st.depth))
head = f"vector ({vec}): " if vec else ""
lines.append(f"{pad}{head}{st.name}: {acc(st.write)} = {rhs}")
return lines
def sub(coeffs, const):
return (tuple(coeffs), const)
def book_example(N=2, size=4):
"""The imperfect nest of the page (a small copy of Allen and Kennedy's example):
for i: S1: X[i] = Y[i] + 10
for j: S2: B[j] = A[j][N]
for k: S3: A[j+1][k] = B[j] + C[j][k]
S4: Y[i+j] = A[j+1][N]
"""
b = [(1, size)] * 3
s1 = Stmt("S1", 1, ("X", [sub([1], 0)]), [("Y", [sub([1], 0)])], [1], 10)
s2 = Stmt("S2", 2, ("B", [sub([0, 1], 0)]), [("A", [sub([0, 1], 0), sub([0, 0], N)])], [1], 0)
s3 = Stmt("S3", 3, ("A", [sub([0, 1, 0], 1), sub([0, 0, 1], 0)]),
[("B", [sub([0, 1, 0], 0)]), ("C", [sub([0, 1, 0], 0), sub([0, 0, 1], 0)])], [1, 1], 0)
s4 = Stmt("S4", 2, ("Y", [sub([1, 1], 0)]), [("A", [sub([0, 1], 1), sub([0, 0], N)])], [1], 0)
return Program(b, [s1, s2, s3, s4])
if __name__ == "__main__":
prog = book_example()
g = dependence_graph(prog)
for e in sorted(g):
print(prog.stmts[e[0]].name, "->", prog.stmts[e[1]].name, "level", e[2])
print("\n".join(show(prog, codegen(prog, g))))
test_allen_kennedy_algorithm.py 208 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/allen-kennedy-algorithm/. The authors are listed in prov/WZS56G.jsonl.
import random
from allen_kennedy_algorithm import (
MOD,
Program,
Stmt,
book_example,
codegen,
dependence_graph,
dependence_pairs,
run_code,
run_sequential,
show,
vector_levels,
)
def init_value(cell):
v = 7
for x in cell:
v = (v * 1000003 + (ord(x) if isinstance(x, str) else x + 50)) % MOD
return v
def random_program(rng):
n = rng.randint(1, 3)
bounds = [(rng.randint(0, 1), rng.randint(2, 3)) for _ in range(n)]
while True:
r = rng.randint(1, 4)
depths = [rng.randint(1, n) for _ in range(r)]
ok = True
for l in range(n):
pos = [p for p, d in enumerate(depths) if d > l]
if pos and pos[-1] - pos[0] + 1 != len(pos):
ok = False
if ok:
break
arrays = {"A": rng.randint(1, 2), "B": rng.randint(1, 2), "C": 1}
def access(d):
arr = rng.choice("ABC")
subs = []
for _ in range(arrays[arr]):
co = [0] * d
if rng.random() < 0.85:
co[rng.randrange(d)] = rng.choice([1, 1, 1, -1, 2])
subs.append((tuple(co), rng.randint(-1, 1)))
return (arr, subs)
stmts = []
for s, d in enumerate(depths):
reads = [access(d) for _ in range(rng.randint(0, 2))]
coefs = [rng.randrange(1, MOD) for _ in reads]
idx = [rng.randrange(MOD) for _ in range(d)]
stmts.append(Stmt(f"S{s + 1}", d, access(d), reads, coefs, rng.randrange(MOD), idx))
return Program(bounds, stmts)
def on_cycle(graph, s, m):
"""Brute force: is s reachable from itself through edges of level >= m?"""
succ = {}
for a, b, lev in graph:
if lev >= m:
succ.setdefault(a, set()).add(b)
seen, todo = set(), list(succ.get(s, ()))
while todo:
v = todo.pop()
if v == s:
return True
if v not in seen:
seen.add(v)
todo.extend(succ.get(v, ()))
return False
def ordered_partitions(items):
if not items:
yield []
return
first, rest = items[0], items[1:]
for part in ordered_partitions(rest):
for i in range(len(part)):
yield part[:i] + [[first] + part[i]] + part[i + 1:]
for i in range(len(part) + 1):
yield part[:i] + [[first]] + part[i:]
def all_codes(prog, region, k):
"""Every code of the model: loop distribution and statement order at each
level, each piece a sequential loop at level k or a one-statement vector."""
out = []
for part in ordered_partitions(region):
choices = []
for block in part:
opts = []
if len(block) == 1:
opts.append(("vec", block[0], k))
if all(prog.stmts[s].depth >= k for s in block):
for inner in all_codes(prog, sorted(block), k + 1):
opts.append(("loop", k, inner))
choices.append(opts)
combos = [[]]
for opts in choices:
combos = [c + [o] for c in combos for o in opts]
out.extend(combos)
return out
def keeps_all(prog, code, pairs):
steps = {}
run_code(prog, code, init_value, steps)
return all(steps[a] < steps[b] for a, b in pairs)
def test_book_example():
prog = book_example()
code = codegen(prog, dependence_graph(prog))
assert show(prog, code) == [
"for i = 1 to 4:",
" for j = 1 to 4:",
" S2: B[j] = A[j][2]",
" vector (k): S3: A[j+1][k] = B[j] + C[j][k]",
" vector (j): S4: Y[i+j] = A[j+1][2]",
"vector (i): S1: X[i] = Y[i] + 10",
]
assert run_code(prog, code, init_value) == run_sequential(prog, init_value)
def test_simple_cases():
s = lambda co, c: (tuple(co), c)
# A[i+1] = A[i] + B[i]: a flow cycle at level 1, so a sequential loop.
rec = Program([(1, 5)], [Stmt("S1", 1, ("A", [s([1], 1)]), [("A", [s([1], 0)]), ("B", [s([1], 0)])], [1, 1], 0)])
assert codegen(rec, dependence_graph(rec)) == [("loop", 1, [("vec", 0, 2)])]
# S1: A[i] = B[i]; S2: C[i] = A[i-1]: no cycle, both vector, S1 first.
two = Program([(1, 5)], [
Stmt("S1", 1, ("A", [s([1], 0)]), [("B", [s([1], 0)])], [1], 0),
Stmt("S2", 1, ("C", [s([1], 0)]), [("A", [s([1], -1)])], [1], 0)])
assert codegen(two, dependence_graph(two)) == [("vec", 0, 1), ("vec", 1, 1)]
# Backward carried dependence: S1 reads A[i+1], S2 writes A[i]. The
# vector code must put S1 first; its read of A[i+1] precedes S2's write.
back = Program([(1, 5)], [
Stmt("S1", 1, ("B", [s([1], 0)]), [("A", [s([1], 1)])], [1], 0),
Stmt("S2", 1, ("A", [s([1], 0)]), [("C", [s([1], 0)])], [1], 0)])
code = codegen(back, dependence_graph(back))
assert code == [("vec", 0, 1), ("vec", 1, 1)]
assert run_code(back, code, init_value) == run_sequential(back, init_value)
# S1: C[i] = A[i-1]; S2: A[i] = B[i]. The only edge goes from S2 to S1
# (carried flow), so the topological order puts S2 first. Text order
# would read A before it is written.
rev = Program([(1, 5)], [
Stmt("S1", 1, ("C", [s([1], 0)]), [("A", [s([1], -1)])], [1], 0),
Stmt("S2", 1, ("A", [s([1], 0)]), [("B", [s([1], 0)])], [1], 0)])
code = codegen(rev, dependence_graph(rev))
assert code == [("vec", 1, 1), ("vec", 0, 1)]
assert run_code(rev, code, init_value) == run_sequential(rev, init_value)
wrong = [("vec", 0, 1), ("vec", 1, 1)]
assert run_code(rev, wrong, init_value) != run_sequential(rev, init_value)
def test_random_programs_keep_every_dependence():
rng = random.Random(1987)
for _ in range(300):
prog = random_program(rng)
pairs = dependence_pairs(prog)
graph = dependence_graph(prog, pairs)
code = codegen(prog, graph)
steps = {}
mem = run_code(prog, code, init_value, steps)
for a, b in pairs:
assert steps[a] < steps[b], (a, b)
assert mem == run_sequential(prog, init_value)
def test_vector_level_is_first_acyclic_level():
rng = random.Random(9)
for _ in range(300):
prog = random_program(rng)
graph = dependence_graph(prog)
lv = vector_levels(codegen(prog, graph))
for s, st in enumerate(prog.stmts):
m = 1
while m <= prog.n and on_cycle(graph, s, m):
m += 1
assert lv[s] == m
assert m <= st.depth + 1
def test_maximal_among_all_distributions():
rng = random.Random(2001)
tried = 0
while tried < 60:
prog = random_program(rng)
if len(prog.stmts) > 3 or prog.n > 2:
continue
tried += 1
pairs = dependence_pairs(prog)
best = vector_levels(codegen(prog, dependence_graph(prog, pairs)))
found_legal = False
for code in all_codes(prog, list(range(len(prog.stmts))), 1):
if keeps_all(prog, code, pairs):
found_legal = True
lv = vector_levels(code)
for s in lv:
assert lv[s] >= best[s]
assert found_legal
History
Randy Allen and Ken Kennedy developed the algorithm for PFC, the Parallel Fortran Converter, at Rice University, and published it in the ACM Transactions on Programming Languages and Systems in 1987. The ideas of dependence graphs and their strongly connected components came from the work of Kuck and his group at Illinois on the Parafrase system. Allen and Kennedy's 2001 book gives the algorithm under the name codegen, with the example above. In 1997 Darte and Vivien proved that it finds the most parallel loops possible when the only information is the level of each dependence.
References
- Randy Allen and Ken Kennedy, Automatic translation of FORTRAN programs to vector form, ACM Transactions on Programming Languages and Systems 9(4), 1987, 491-542, the vector code generation procedure (codegen on the strongly connected components of the dependence graph, level by level) and the PFC translator
- Randy Allen and Ken Kennedy, Optimizing Compilers for Modern Architectures, a Dependence-Based Approach, Morgan Kaufmann, 2002 (copyright 2001), Chapter 2 (the section on parallelization and vectorization, with the advanced vectorization algorithm codegen and its worked example) and Chapter 5 (transformations that break dependence cycles before vectorization)
- Alain Darte and Frédéric Vivien, On the optimality of Allen and Kennedy's algorithm for parallelism extraction in nested loops, Parallel Algorithms and Applications 12(1-3), 1997, 83-112, the main theorem (with dependence levels as the only information, no algorithm finds more parallel loops than Allen and Kennedy's)
- Michael Wolfe, High Performance Compilers for Parallel Computing, Addison-Wesley, 1996, the chapter on vector code generation (loop distribution by strongly connected components and vector statements)
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 WZS56G Edit this page History Report an error Markdown