Algorithmadvanced
Wolf-Lam locality optimization
Also called data locality optimizing algorithm, reuse analysis.
Models temporal and spatial reuse as vector spaces and picks unimodular transformations and tiling that keep the reuse in the innermost loops.
- Time
- O(4^k k! k D + 2^k k^3 A^2) worst
- Space
- O(k^2 + A) extra
- Where
- A = the number of array accesses; D = the number of distance vectors; k = the depth of the loop nest
- Model
- Word RAM
- Properties
- deterministiciterative
- Evidence
- Proof sketchCode in 1 languages
The Wolf-Lam algorithm chooses a unimodular transformation and a tiling of a perfect loop nest so that data that the nest uses again is still in the cache when it is used again. It describes reuse with vector spaces: for an access , the iterations that touch the same element differ by a vector in the nullspace of . The loops that run inside one tile span the localized space , and reuse along a direction in becomes a cache hit. For each candidate set of loops, the algorithm checks that a legal transformation can put those loops innermost as a fully permutable band, estimates the memory accesses per iteration from the reuse spaces inside , and keeps the cheapest set. Michael Wolf and Monica Lam published it at PLDI in 1991.
In plain words
A program that walks over a big table often reads the same numbers many times. If the second read comes soon after the first, the number is still in the fast cache. If it comes late, the program waits for the slow memory. This algorithm looks at each array read in a loop nest and finds the directions in which the loops come back to the same number, or to a neighbour in the same cache line. Then it tries groups of loops. For each group it asks whether the loops can be legally reordered so that this group runs in small blocks at the inside of the nest. For each group that works, it estimates how many slow memory reads one step costs, and it keeps the cheapest group. Last, it cuts that group into blocks.
The problem
Input. A perfect nest of depth with rectangular bounds. A set of constant dependence distance vectors, each nonzero and lexicographically positive. A list of array accesses , where is an integer matrix with columns and a constant vector; all accesses with the same array and the same form one uniformly generated set. The arrays are in row-major order. Two numbers for the cost model: , the number of elements in a cache line, and , an estimate of the trip count of a loop inside a tile.
Output. A set of loops to localize, and a unimodular matrix that keeps every dependence and makes the loops of the innermost loops, as a fully permutable band. A band is fully permutable when every dependence that the outer loops do not carry has a nonnegative entry at every loop of the band; then every order of the band is legal, and so is tiling it.
Goal. The smallest estimated number of memory accesses per iteration. There are three kinds of reuse. An access has self-temporal reuse when it touches the same element in two iterations, and self-spatial reuse when it touches the same cache line. Two accesses of one uniformly generated set have group reuse when they touch the same data.
The algorithm
WOLF-LAM(accesses A[H i + c], distances D, depth k, line l, trip s)- 1
for each uniformly generated set (A, H) do R_ST <- ker H; R_SS <- ker H_S - 2
best <- none - 3
for each subset I of the loops, smallest first do - 4
T <- signed permutation with I innermost, then skew of I, with I fully permutable - 5
if no such T is legal then continue - 6
L <- span{e_j : j in I} - 7
cost <- sum over the sets of (g_S + (g_T - g_S) / l) / (l^e s^dim(R_ST ∩ L)) - 8
if best = none or cost < best.cost then best <- (I, T, cost) - 9
apply best.T and tile the |I| innermost loops by B when |I| >= 2
Line L1 computes the reuse spaces. holds the directions in which one access touches the same element again. is with its last row set to , so holds the directions in which the access stays in one row of the array, where the elements share cache lines. The spaces depend only on , so one computation serves the whole set.
Lines L3 to L5 test whether the loops of can run innermost. Line L4 tries every order and every sign (loop reversal) of the loops outside , then every order and sign of the loops of , and accepts the first choice that makes every distance lexicographically positive. Then it skews the band, loop by loop, by the smallest factor that makes the band entries of every distance not carried by an outer loop nonnegative. After the skew, the band is fully permutable.
Line L6 is the localized space. The outer loops are a signed copy of the loops outside , so two iterations of one tile differ only on the loops of , whatever the skew is.
Line L7 is the cost model of the paper. is the number of classes of offsets in a set, where and are in one class when for some : the accesses of a class touch the same data within a tile, so the class fetches it once. is the same count for and the offsets with their last entry set to . The classes of fetch a cache line; the extra temporal classes inside them cost each. The term divides by for each localized direction of self-temporal reuse. when is larger than , which means the access also walks along a cache line inside the tile; then the cost divides by . Otherwise . Line L8 keeps the cheapest set, and the smaller one on a tie. Line L9 tiles the band; a band of one loop needs no tile loop.
Example
The successive over-relaxation sweep
for i1 = 1 to t:
for i2 = 1 to n - 2:
for i3 = 1 to n - 2:
A[i2][i3] = (A[i2][i3] + A[i2+1][i3] + A[i2-1][i3] + A[i2][i3+1] + A[i2][i3-1]) / 5
has one uniformly generated set: with the offsets , , , , . Line L1 gives : every sweep reads the same array. gives . The distances are , , , and . The candidates of lines L3 to L8, with and :
| localized loops | , , , | cost | value |
|---|---|---|---|
| none | 5, 3, 0, 0 | 3.25 | |
| 3, 3, 1, 0 | 0.375 | ||
| 3, 1, 0, 0 | 1.25 | ||
| 1, 1, 1, 0 | 0.125 | ||
| 1, 1, 1, 1 | 0.00125 | ||
| , , | not legal |
Every set with inside and some other loop outside fails line L5. The outermost loop is then or . The distances and have opposite signs at , and and have opposite signs at , so with either sign, one distance starts with a negative entry. The set of all three loops is legal only with the skew. Line L4 keeps the order and skews by . The distances become , , , and , all nonnegative, so the three new loops can be tiled.
An LRU simulation shows the effect and the limit of the model. The setup is 8 sweeps over the interior of a array, 8 elements per line, a cache of 32 lines, and the five reads of each iteration:
| order | misses |
|---|---|
| original | 1024 |
| tiles of 8 on only | 1120 |
| skewed, tiles of 4 | 502 |
| skewed, tiles of 8 | 512 |
| skewed, tiles of 16 | 1027 |
The skewed and tiled nest halves the misses. With tiles of 16, the data of one tile does not fit in the cache any more, and the result is worse than the original. The cost model does not see the tile size.
A smaller case: for i: for j: sum += A[j][i] walks down the columns. Here and . Localizing costs and localizing costs , so the algorithm picks and interchanges the loops. For elements, lines of 8 and a 16-line cache, the misses fall from 4096 to 512.
Correctness
The full proof is in proofs/correctness.md. It has three parts.
The reuse spaces are exact. One access touches the same element at and exactly when , and the same row exactly when . Two accesses of one set touch the same element at and exactly when ; with this is an equivalence relation on the offsets, because is a subspace.
The chosen nest keeps every dependence. is a signed permutation followed by a unitriangular skew, so . For each distance, the outer part of is lexicographically positive, or it is and the band part is nonnegative and nonzero; an induction over the band loops shows that the skew factor of line L4 gives this. Then the tile entries cannot decrease along a dependence, and the order of tiles, then points, puts every sink after its source. By Theorem 1 of the legality page, the result equals that of the original nest.
The search finds the cheapest legal set. Line L4 finds a transformation for exactly when some signed permutation with the loops of innermost is legal, since it tries all of them. The empty set is always legal. Line L3 tries every set, so line L8 ends with a set of minimum cost.
Proof: The reuse spaces are exact, the chosen transformation keeps every dependence, and the search finds the cheapest legal set of loopsfull
Setting
The nest has depth and a box of iterations . is a finite set of nonzero distance vectors, each lexicographically positive. Every dependence of the nest goes from an iteration to the iteration with , or stays inside one iteration; the body of one iteration runs as a unit, with its statements in text order. An access touches, at iteration , the element of array with subscripts , where is an integer matrix with columns and is an integer vector. Arrays are stored in row-major order, so the elements whose subscripts differ only in the last place lie next to each other in memory. is with its last row set to .
For a set of loops, line L4 looks for a signed permutation matrix , whose rows are , that lists the loops outside first and the loops of last, and for a lower unitriangular integer matrix of size . It then sets
For we write , with the first entries (the outer part) and the last entries (the band part). Line L9 runs the iterations in the order of the key
compared lexicographically, with the floor entries left out when . This is the order of a nest that runs the outer loops, then the tile loops, then the loops inside one tile.
Part 1: the reuse spaces
Lemma 1 (self-temporal reuse). One access touches the same element at iterations and if and only if .
Proof. if and only if .
Lemma 2 (self-spatial reuse). One access touches the same row of the array, that is, elements whose subscripts agree in all places but the last, at iterations and if and only if .
Proof. The subscripts at and at differ by . They agree in all places but the last exactly when every row of except the last gives on , which is .
Only elements of one row lie next to each other in row-major order, so only they can share a cache line; that is why the spatial space uses . Since , temporal reuse is a special case of spatial reuse.
Lemma 3 (group reuse). Let two accesses have the same array and the same and offsets . Access 1 at iteration and access 2 at iteration touch the same element if and only if . For a subspace , the relation is an equivalence relation on the offsets.
Proof. is the same as . The image is a subspace, so it contains , it is closed under negation, and it is closed under addition: these give reflexivity, symmetry and transitivity.
Because is already transitive, the union of all pairs with , which the implementation forms, gives exactly its classes. The number of classes is ; the same with and the offsets with their last entry set to is .
The test is over the rational numbers. When every row of is a unit vector, that is, every subscript is a loop index plus a constant, and is spanned by unit vectors, a rational solution can be replaced by an integer one: the entries of are entries of , so we can set each needed entry of to the integer entry of . Then the rational classes are the classes of real reuse between integer iterations.
Part 2: the localized space of the transformed nest
Lemma 4. Two iterations with the same outer part differ by a vector of .
Proof. The first rows of are the first rows of , which are for the loops . So lists the entries , . If two iterations have the same , their difference is at every .
So the iterations inside one tile, and for large tiles inside one run of the band, differ only along the loops of , whatever the skew is. This is the localized space of line L6.
Part 3: legality of the chosen transformation
Lemma 5 (unimodular). .
Proof. for a signed permutation matrix, and is unitriangular with determinant .
So is a bijection of , and the keys of distinct iterations are distinct.
Lemma 6 (the band is fully permutable). If line L4 accepts , then for every , with : either is lexicographically positive, or , every , and .
Proof. Line L4 accepts only when the outer part of is lexicographically nonnegative for every , and, for every whose outer part is , the band part of is lexicographically positive. The outer part of is the outer part of . If it is not , it is lexicographically positive.
Now let it be , and let be the band part of . The skew is computed one loop at a time: and for , where over all with outer part . We show by induction on that , and that implies .
For : is lexicographically positive, so , and .
For , let . If , then , because and . If , then , so by induction; then is the first entry of that can be nonzero, so because is lexicographically positive, and . In both cases the second claim also holds at .
At , if then , which is false since is lexicographically positive. So .
The matrix that line L4 builds has the rows , so that ; that is the recurrence above.
Lemma 7 (the tiled order keeps every dependence). For every dependence from to , , .
Proof. Let and . By Lemma 6, either the outer part of is lexicographically positive, and then and in the first part of the key; or and with in every entry and . In the second case, for every , because the floor is monotone. If some tile entry is larger, the first such entry decides, and . If all tile entries are equal, the keys agree up to and , and is nonnegative and nonzero, so its first nonzero entry is positive and . When there are no tile entries and the same argument applies directly. When the band part is empty, so the second case cannot happen and the outer part decides.
Theorem 1 (same result). The nest that runs the iterations of in increasing gives the same final state as the original nest.
Proof. By Lemma 5 the keys are distinct, so the order is a total order on and runs each iteration once. A dependence inside one iteration keeps its order because the body runs as a unit. By Lemma 7, every dependence between two iterations keeps its order. By Theorem 1 of the loop transformation legality page, an order that keeps every dependence pair gives the same final state.
Part 4: the search
Lemma 8 (completeness of line L4). For a set , line L4 finds if and only if some signed permutation that lists the loops of last makes lexicographically positive for every .
Proof. If L4 accepts , then for every the outer part of is lexicographically nonnegative, and if it is , the band part is lexicographically positive. In both cases is lexicographically positive. Conversely, if is lexicographically positive for every , then its outer part is lexicographically nonnegative, and when that part is , its band part is lexicographically positive. L4 tries every signed order of the outer loops and every signed order of the band, so it meets this or an earlier one that passes the same test; the skew then always exists by Lemma 6.
Theorem 2 (cheapest legal set). Let be the sets for which some signed permutation with the loops of last is legal. The algorithm returns a set whose cost in line L7 is the minimum over , and among sets of equal cost the first in the order of line L3.
Proof. is not empty: the identity is legal for , because every is lexicographically positive. Line L3 enumerates every subset of the loops. By Lemma 8, line L5 skips exactly the subsets outside . Line L8 replaces the best only on a strictly smaller cost, so after the loop the best is the first subset of minimum cost.
What the result does not promise
The cost of line L7 is an estimate of the memory accesses per iteration, not a miss count. It does not see the tile size, the size of the cache, or conflicts between arrays in the cache. A tile that is too large for the cache can lose all the reuse that the model counts; the page shows a case with more misses than the original order.
The search covers transformations of the form "signed permutation, then skew of the band". A general unimodular matrix can make a localized space that is not spanned by loop axes. Wolf and Lam also search only over sets of loops, because in practice the reuse spaces are spanned by loop axes. Their SRP heuristic does not try every signed permutation; Lemma 8 holds for the exhaustive search of this implementation.
Complexity
There are subsets. For one subset, line L4 tries at most signed permutations and checks each against distances in ; the skew costs . Line L7 compares the offsets of each set in pairs, and each comparison is a rank computation of on vectors of length at most , for a total of . In all, . Loop nests are shallow; for there are 8 subsets and at most 48 signed permutations each. Line L1 is done once per set. The extra space is for the matrices and for the classes. The implementation produces the tiled order by sorting the iterations on their keys, ; a compiler emits loops instead.
Properties
- Model, not measurement. The cost counts memory accesses per iteration under the assumption that the reuse inside a tile stays in the cache.
- Exact legality. Every transformation it returns keeps every dependence, for any tile size.
- Loop axes only. The localized spaces are spans of loop axes, as in the paper.
- Tile size left open. The choice of and does not depend on ; the tile size is a separate decision.
Variants and improvements
- The SRP heuristic. Wolf and Lam do not try every signed permutation. Their SRP transformation (skew, reversal, permutation) places loops one at a time and runs in for depth and dependences. They also prune the loops first: loops that carry no reuse and can go outermost are set aside, and so are loops that carry reuse but must stay outermost. Only the remaining loops enter the power set. The exhaustive search here is simpler and fast enough for .
- Simpler cost model. McKinley, Carr and Tseng count, for each loop, the cache lines that the nest touches when that loop is innermost, and sort the loops into a memory order. They combine it with permutation, fusion, distribution and reversal.
- Tile size. Lam, Rothberg and Wolf choose the tile size from the cache size and from cache interference; a tile that maps two rows onto the same cache lines loses its reuse.
- Polyhedral scheduling. The Pluto algorithm finds tiling hyperplanes for imperfect nests and affine dependences in the polyhedral model, with a cost on the dependence distances instead of a reuse model.
- Recursion instead of tiles. Cache-oblivious matrix multiplication gets the same kind of locality for every cache size at once, without a tile size.
When to use it
Use it for perfect nests of dense array code with affine subscripts and constant distances, such as stencils, relaxation sweeps and matrix kernels, when the compiler must choose between interchange, reversal, skewing and tiling. If the subscripts or the distances are not known at compile time, the reuse spaces cannot be computed. For imperfect nests, use a polyhedral scheduler. For a single loop order question in a two-deep nest, the loop interchange page is enough.
Pitfalls
- The wrong row in line L1. zeroes the last row only for row-major arrays. For column-major arrays, as in Fortran, zero the first row; otherwise the model finds spatial reuse in the wrong direction and makes the strided loop innermost.
- No skew in line L4. Without the skew, the band of all three SOR loops is not fully permutable: has a negative entry. Tiling it without the skew changes the result.
- A zero distance in line L4. A dependence inside one iteration has . It is never lexicographically positive, so it makes every set fail. Keep only the distances between different iterations.
- Ties in line L8. In the column example, and both cost . With instead of the larger set wins and adds tile loops for no gain.
- Trusting line L7 for the tile size. The cost does not depend on . In the example, tiles of 16 give more misses than the original order; choose from the cache size in line L9.
- Tiling a band of one loop in line L9. That is strip-mining and changes no order, so it adds loop overhead and no locality.
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/wolf-lam-locality-algorithm/. The authors are listed in prov/SBSZSV.jsonl.
"""Wolf and Lam's data locality optimizing algorithm, for small perfect nests.
A nest of depth k has rectangular bounds, a list of constant dependence
distance vectors, and array accesses. An access is (array, H, c): at
iteration i it touches the element H i + c of a row-major array, so the
last subscript walks memory with stride 1.
Reuse is described by vector spaces (Wolf and Lam, PLDI 1991, Section 4):
self-temporal R_ST = ker H
self-spatial R_SS = ker H_S, where H_S is H with its last row zeroed
group reuse two accesses with the same array and H (a uniformly
generated set) share data when H r = c1 - c2 for some r
in the localized space L (temporal), or the same with
H_S and c_S (spatial).
The localized space L is the span of the loops that run inside one tile.
For each candidate set I of loops the cost, in memory accesses per
iteration, is the sum over uniformly generated sets of
(g_S + (g_T - g_S) / l) / (l^e * s^dim(R_ST n L)),
with e = 0 if R_ST n L = R_SS n L and e = 1 otherwise; l is the number of
elements in a cache line and s the trip count of a localized loop.
Wolf and Lam make I innermost and fully permutable with a heuristic over
skewing, reversal and permutation (SRP). This code instead tries every
signed permutation that puts the loops of I innermost and then skews the
band by the construction of the loop skewing page. With k <= 3 that is a
few dozen candidates, and it finds a band whenever a signed permutation
with I innermost is legal.
"""
from fractions import Fraction
from itertools import combinations, permutations, product
# ---------------------------------------------------------------- linear algebra
def _rref(rows, ncols):
m = [[Fraction(x) for x in r] for r in rows]
piv, r = [], 0
for c in range(ncols):
p = next((q for q in range(r, len(m)) if m[q][c] != 0), None)
if p is None:
continue
m[r], m[p] = m[p], m[r]
inv = 1 / m[r][c]
m[r] = [x * inv for x in m[r]]
for q in range(len(m)):
if q != r and m[q][c] != 0:
f = m[q][c]
m[q] = [x - f * y for x, y in zip(m[q], m[r])]
piv.append(c)
r += 1
if r == len(m):
break
return m[:r], piv
def rank(vectors, k):
"""Rank of a list of vectors of length k."""
if not vectors:
return 0
return len(_rref(vectors, k)[1])
def nullspace(M, k):
"""A basis of {x in Q^k : M x = 0}."""
if not M:
return [tuple(Fraction(int(c == j)) for c in range(k)) for j in range(k)]
R, piv = _rref(M, k)
free = [c for c in range(k) if c not in piv]
basis = []
for f in free:
x = [Fraction(0)] * k
x[f] = Fraction(1)
for row, p in zip(R, piv):
x[p] = -row[f]
basis.append(tuple(x))
return basis
def mat_vec(M, v):
return tuple(sum(Fraction(a) * b for a, b in zip(row, v)) for row in M)
def spatial(H):
"""H_S: H with the row of the last (contiguous) subscript set to zero."""
return [list(r) for r in H[:-1]] + [[0] * len(H[-1])]
def reuse_spaces(H, k):
"""(basis of R_ST, basis of R_SS) for the access matrix H."""
return nullspace(H, k), nullspace(spatial(H), k)
def unit(j, k):
return tuple(Fraction(int(c == j)) for c in range(k))
def dim_intersection(A, B, k):
"""dim(span A n span B) = dim A + dim B - dim(A + B)."""
return rank(A, k) + rank(B, k) - rank(list(A) + list(B), k)
def in_image(H, L, v, k):
"""True when H r = v for some r in span L."""
cols = [mat_vec(H, b) for b in L]
n = len(v)
return rank(cols + [tuple(v)], n) == rank(cols, n) if cols else all(x == 0 for x in v)
# ---------------------------------------------------------------- cost model
def uniformly_generated_sets(accesses):
"""Group accesses by (array, H); each group lists its offset vectors."""
groups = {}
for arr, H, c in accesses:
key = (arr, tuple(tuple(r) for r in H))
groups.setdefault(key, [])
if tuple(c) not in groups[key]:
groups[key].append(tuple(c))
return groups
def count_classes(H, offsets, L, k):
"""Number of classes of offsets under c1 ~ c2 iff H r = c1 - c2 for some r in L."""
parent = list(range(len(offsets)))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
for a, b in combinations(range(len(offsets)), 2):
diff = tuple(x - y for x, y in zip(offsets[a], offsets[b]))
if in_image(H, L, diff, k):
parent[find(a)] = find(b)
return len({find(x) for x in range(len(offsets))})
def set_cost(H, offsets, L, k, line, s, spaces=None):
"""Memory accesses per iteration for one uniformly generated set."""
R_ST, R_SS = spaces if spaces is not None else reuse_spaces(H, k)
HS = spatial(H)
off_s = [tuple(list(c[:-1]) + [0]) for c in offsets]
g_T = count_classes(H, offsets, L, k)
g_S = count_classes(HS, off_s, L, k)
dst = dim_intersection(R_ST, L, k)
dss = dim_intersection(R_SS, L, k)
e = 0 if dst == dss else 1
return (Fraction(g_S) + Fraction(g_T - g_S, line)) / (Fraction(line) ** e * Fraction(s) ** dst)
def nest_cost(accesses, I, k, line=8, s=100):
"""Total cost when the loops in I are localized (L = span of their axes)."""
L = [unit(j, k) for j in sorted(I)]
total = Fraction(0)
for (arr, H), offs in uniformly_generated_sets(accesses).items():
total += set_cost([list(r) for r in H], offs, L, k, line, s)
return total
# ---------------------------------------------------------------- legality and the band
def lex_nonneg(v):
for x in v:
if x != 0:
return x > 0
return True
def make_band(distances, I, k):
"""A unimodular T that runs the loops not in I outside and the loops of I
as an innermost fully permutable band, or None.
T = (skew of the band) x (signed permutation). Returns (T, m) with m = |I|.
"""
I = sorted(I)
O = [j for j in range(k) if j not in I]
m = len(I)
for po in permutations(O):
for so in product((1, -1), repeat=len(O)):
outer = [tuple(sg * d[j] for sg, j in zip(so, po)) for d in distances]
if not all(lex_nonneg(v) for v in outer):
continue
free = [d for d, v in zip(distances, outer) if not any(v)]
for pb in permutations(I):
for sb in product((1, -1), repeat=m):
band = [[sg * d[j] for sg, j in zip(sb, pb)] for d in free]
if not all(lex_nonneg(v) and any(v) for v in band):
continue
# Skew loop by loop: b'_l = b_l + f_l (b'_1 + ... + b'_{l-1}).
f = [0] * m
cur = [list(v) for v in band]
for l in range(1, m):
f[l] = max([0] + [-v[l] for v in cur])
for v in cur:
v[l] = v[l] + f[l] * sum(v[:l])
rows = []
for sg, j in zip(so, po):
rows.append([sg * int(c == j) for c in range(k)])
brows = []
for l, (sg, j) in enumerate(zip(sb, pb)):
r = [sg * int(c == j) for c in range(k)]
for q in range(l):
r = [x + f[l] * y for x, y in zip(r, brows[q])]
brows.append(r)
return rows + brows, m
return None
def transformed(T, d):
return tuple(sum(a * x for a, x in zip(row, d)) for row in T)
def wolf_lam(accesses, distances, k, line=8, s=100):
"""Choose the localized loops and the transformation.
Returns a dict with I (the localized loops), cost, T and m (the band size).
"""
groups = uniformly_generated_sets(accesses)
spaces = {key: reuse_spaces([list(r) for r in key[1]], k) for key in groups} # @line L1
best = None # @line L2
subsets = [I for size in range(k + 1) for I in combinations(range(k), size)]
for I in subsets: # @line L3
band = make_band(distances, I, k) # @line L4
if band is None: # @line L5
continue
L = [unit(j, k) for j in I] # @line L6
cost = sum(
(set_cost([list(r) for r in key[1]], offs, L, k, line, s, spaces[key]) for key, offs in groups.items()),
Fraction(0),
) # @line L7
if best is None or cost < best["cost"]: # @line L8
best = {"I": I, "cost": cost, "T": band[0], "m": band[1]}
return best
def tiled_order(points, T, m, B):
"""Iterations in the order of the transformed nest, with the innermost m
loops tiled by B when m >= 2 (line L9)."""
k = len(T)
def key(i):
y = transformed(T, i)
outer, band = y[:k - m], y[k - m:]
tiles = tuple(x // B for x in band) if m >= 2 else () # @line L9
return outer + tiles + band
return sorted(points, key=key)
test_wolf_lam_locality_algorithm.py 341 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/wolf-lam-locality-algorithm/. The authors are listed in prov/SBSZSV.jsonl.
import random
from collections import OrderedDict
from fractions import Fraction
from itertools import combinations, permutations, product
from wolf_lam_locality_algorithm import (
count_classes,
in_image,
make_band,
mat_vec,
nest_cost,
rank,
reuse_spaces,
spatial,
tiled_order,
transformed,
unit,
wolf_lam,
)
# A nest is a box of iterations and a list of statements (write, reads).
# An access is (array, H, c) and touches array[H i + c].
def elem(acc, i):
arr, H, c = acc
return (arr, tuple(sum(a * x for a, x in zip(row, i)) + o for row, o in zip(H, c)))
def points_of(bounds):
return list(product(*[range(lo, hi + 1) for lo, hi in bounds]))
def true_dependences(points, stmts):
"""All pairs of statement instances, in original order, that touch one element with a write."""
inst = [(i, s) for i in points for s in range(len(stmts))]
deps = []
for x in range(len(inst)):
i, s = inst[x]
w1 = elem(stmts[s][0], i)
r1 = {elem(r, i) for r in stmts[s][1]}
for y in range(x + 1, len(inst)):
j, t = inst[y]
w2 = elem(stmts[t][0], j)
r2 = {elem(r, j) for r in stmts[t][1]}
if w1 == w2 or w1 in r2 or w2 in r1:
deps.append((i, j))
return deps
def distances_of(deps):
return sorted({tuple(b - a for a, b in zip(i, j)) for i, j in deps if i != j})
def start_value(e):
name, idx = e
return (ord(name) % 7 + 3 * sum((p + 2) * v for p, v in enumerate(idx))) % 101
def run(order, stmts):
mem = {}
for i in order:
for s, (w, reads) in enumerate(stmts):
vals = [mem.get(elem(r, i), start_value(elem(r, i))) for r in reads]
mem[elem(w, i)] = (sum((n + 1) * v for n, v in enumerate(vals)) * 3 + s + 1) % 1000003
return mem
def random_row(rnd, k):
j = rnd.randrange(k)
row = [0] * k
row[j] = 1
if k > 1 and rnd.random() < 0.2:
l = rnd.choice([x for x in range(k) if x != j])
row[l] = rnd.choice((1, -1))
return row
def random_access(rnd, k, arr):
dims = rnd.randint(1, 2)
H = [random_row(rnd, k) for _ in range(dims)]
c = tuple(rnd.randint(-1, 1) for _ in range(dims))
return (arr, H, c)
def random_nest(rnd, k):
bounds = [(0, rnd.randint(1, 3)) for _ in range(k)]
stmts = []
for _ in range(rnd.randint(1, 2)):
w = random_access(rnd, k, rnd.choice("AB"))
reads = [random_access(rnd, k, rnd.choice("AB")) for _ in range(rnd.randint(1, 3))]
stmts.append((w, reads))
return bounds, stmts
def accesses_of(stmts):
out = []
for w, reads in stmts:
out.append(w)
out.extend(reads)
return out
def det(m):
m = [[Fraction(x) for x in row] for row in m]
n, s = len(m), Fraction(1)
for c in range(n):
p = next((r for r in range(c, n) if m[r][c] != 0), None)
if p is None:
return Fraction(0)
if p != c:
m[c], m[p] = m[p], m[c]
s = -s
s *= m[c][c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
m[r] = [x - f * y for x, y in zip(m[r], m[c])]
return s
def lex_pos(v):
for x in v:
if x != 0:
return x > 0
return False
def order_keeps(order, deps):
pos = {p: n for n, p in enumerate(order)}
return all(pos[i] < pos[j] for i, j in deps if i != j)
def misses(order, accesses, ncols, line, cache_lines):
"""LRU misses when every array is n x ncols, row-major, and a line holds `line` elements."""
cache = OrderedDict()
base = {}
count = 0
for i in order:
for acc in accesses:
name, idx = elem(acc, i)
b = base.setdefault(name, len(base) * 1000000)
addr = b + (idx[0] * ncols + idx[1] if len(idx) == 2 else idx[0])
key = addr // line
if key in cache:
cache.move_to_end(key)
else:
count += 1
cache[key] = True
if len(cache) > cache_lines:
cache.popitem(last=False)
return count
# ---------------------------------------------------------------- examples from the page
COLUMN = [("A", [[0, 1], [1, 0]], (0, 0))]
SOR_H = [[0, 1, 0], [0, 0, 1]]
SOR = [("A", SOR_H, c) for c in [(0, 0), (1, 0), (-1, 0), (0, 1), (0, -1)]]
SOR_D = [(0, 1, 0), (0, 0, 1), (1, 0, 0), (1, -1, 0), (1, 0, -1)]
MATMUL = [
("C", [[1, 0, 0], [0, 1, 0]], (0, 0)),
("A", [[1, 0, 0], [0, 0, 1]], (0, 0)),
("B", [[0, 0, 1], [0, 1, 0]], (0, 0)),
]
def test_column_traversal_is_interchanged():
best = wolf_lam(COLUMN, [], 2, line=8, s=100)
assert best["I"] == (0,)
assert best["cost"] == Fraction(1, 8)
assert best["T"] == [[0, 1], [1, 0]]
pts = points_of([(0, 63), (0, 63)])
order = tiled_order(pts, best["T"], best["m"], 8)
assert misses(pts, COLUMN, 64, 8, 16) == 4096
assert misses(order, COLUMN, 64, 8, 16) == 512
def test_sor_costs_and_skew():
l, s = 8, 100
assert nest_cost(SOR, (2,), 3, l, s) == Fraction(3, l)
assert nest_cost(SOR, (1, 2), 3, l, s) == Fraction(1, l)
assert nest_cost(SOR, (0, 1, 2), 3, l, s) == Fraction(1, l * s)
assert make_band(SOR_D, (0,), 3) is None
best = wolf_lam(SOR, SOR_D, 3, l, s)
assert best["I"] == (0, 1, 2)
T = best["T"]
assert T == [[1, 0, 0], [1, 1, 0], [2, 1, 1]]
assert all(min(transformed(T, d)) >= 0 for d in SOR_D)
# The SOR nest itself: brute-force legality and equal final arrays.
stmts = [(SOR[0], SOR)]
pts = points_of([(0, 2), (1, 4), (1, 4)])
deps = true_dependences(pts, stmts)
assert set(SOR_D) <= set(distances_of(deps))
for B in (2, 3):
order = tiled_order(pts, T, 3, B)
assert order_keeps(order, deps)
assert run(order, stmts) == run(pts, stmts)
# Tiling the same band without the skew breaks a dependence and the result.
bad = tiled_order(pts, [[1, 0, 0], [0, 1, 0], [0, 0, 1]], 3, B)
assert not order_keeps(bad, deps)
assert run(bad, stmts) != run(pts, stmts)
# Fewer misses than the original order on a larger grid.
pts = points_of([(0, 7), (1, 30), (1, 30)])
order = tiled_order(pts, T, 3, 8)
assert misses(order, SOR, 32, 8, 32) < misses(pts, SOR, 32, 8, 32)
def test_matmul_costs():
l, s = 8, 100
assert nest_cost(MATMUL, (1, 2), 3, l, s) == Fraction(2, l * s) + Fraction(1, l)
assert nest_cost(MATMUL, (0, 1, 2), 3, l, s) == Fraction(3, l * s)
best = wolf_lam(MATMUL, [(0, 0, 1)], 3, l, s)
assert best["I"] == (0, 1, 2) and best["m"] == 3
pts = points_of([(0, 15), (0, 15), (0, 15)])
order = tiled_order(pts, best["T"], 3, 4)
acc = MATMUL + [MATMUL[0]]
assert misses(pts, acc, 16, 8, 16) == 4160
assert misses(order, acc, 16, 8, 16) == 416
# ---------------------------------------------------------------- reuse spaces against brute force
def test_reuse_spaces_match_brute_force():
rnd = random.Random(7)
for _ in range(200):
k = rnd.randint(1, 3)
_, H, _ = random_access(rnd, k, "A")
R_ST, R_SS = reuse_spaces(H, k)
assert len(R_ST) == k - rank(H, k)
assert all(not any(mat_vec(H, b)) for b in R_ST)
assert all(not any(mat_vec(spatial(H), b)) for b in R_SS)
for r in product(range(-2, 3), repeat=k):
same_elem = all(sum(a * x for a, x in zip(row, r)) == 0 for row in H)
same_row = all(sum(a * x for a, x in zip(row, r)) == 0 for row in H[:-1])
assert same_elem == (rank(R_ST + [r], k) == len(R_ST))
assert same_row == (rank(R_SS + [r], k) == len(R_SS))
def test_group_classes_match_brute_force():
rnd = random.Random(8)
for _ in range(150):
k = rnd.randint(1, 3)
dims = rnd.randint(1, 2)
# Subscripts that are loop indices plus constants.
H = []
for _ in range(dims):
row = [0] * k
row[rnd.randrange(k)] = 1
H.append(row)
offs = sorted({tuple(rnd.randint(-2, 2) for _ in range(dims)) for _ in range(rnd.randint(1, 4))})
I = tuple(j for j in range(k) if rnd.random() < 0.5)
L = [unit(j, k) for j in I]
# Brute force: c1 ~ c2 when some integer r on the loops of I gives H r = c1 - c2.
rs = []
for vals in product(range(-4, 5), repeat=len(I)):
r = [0] * k
for j, v in zip(I, vals):
r[j] = v
rs.append(tuple(sum(a * x for a, x in zip(row, r)) for row in H))
reach = set(rs)
parent = {c: c for c in offs}
def find(c):
while parent[c] != c:
c = parent[c]
return c
for a, b in combinations(offs, 2):
diff = tuple(x - y for x, y in zip(a, b))
assert (diff in reach) == in_image(H, L, diff, k)
if diff in reach:
parent[find(a)] = find(b)
assert count_classes(H, offs, L, k) == len({find(c) for c in offs})
# ---------------------------------------------------------------- legality on random nests
def test_random_nests_legal_and_same_result():
rnd = random.Random(2025)
for _ in range(70):
k = rnd.randint(1, 3)
bounds, stmts = random_nest(rnd, k)
pts = points_of(bounds)
deps = true_dependences(pts, stmts)
D = distances_of(deps)
assert all(lex_pos(d) for d in D)
want = run(pts, stmts)
best = wolf_lam(accesses_of(stmts), D, k)
assert best is not None
for I in [best["I"]] + [I for n in range(k + 1) for I in combinations(range(k), n)]:
band = make_band(D, I, k)
if band is None:
continue
T, m = band
assert m == len(I) and abs(det(T)) == 1
for d in D:
y = transformed(T, d)
outer, inner = y[:k - m], y[k - m:]
assert lex_pos(outer) or (not any(outer) and min(inner) >= 0 and any(inner))
for B in (1, 2, 3):
order = tiled_order(pts, T, m, B)
assert sorted(order) == pts
assert order_keeps(order, deps)
assert run(order, stmts) == want
def test_band_found_when_a_signed_permutation_is_legal():
rnd = random.Random(31)
for _ in range(300):
k = rnd.randint(1, 3)
D = []
for _ in range(rnd.randint(1, 4)):
while True:
d = tuple(rnd.randint(-2, 2) for _ in range(k))
if lex_pos(d):
break
D.append(d)
for n in range(k + 1):
for I in combinations(range(k), n):
legal = False
for perm in permutations(range(k)):
if sorted(perm[k - n:]) != list(I):
continue
for signs in product((1, -1), repeat=k):
if all(lex_pos([sg * d[j] for sg, j in zip(signs, perm)]) for d in D):
legal = True
assert (make_band(D, I, k) is not None) == legal
if __name__ == "__main__":
test_column_traversal_is_interchanged()
test_sor_costs_and_skew()
test_matmul_costs()
test_reuse_spaces_match_brute_force()
test_group_classes_match_brute_force()
test_random_nests_legal_and_same_result()
test_band_found_when_a_signed_permutation_is_legal()
print("ok")
History
Dennis Gannon, William Jalby and Kyle Gallivan described in 1988 how to estimate the data a loop nest needs in a cache with reference windows of uniformly generated references. Michael Wolf and Monica Lam, at Stanford, gave in 1991 a loop transformation theory in which interchange, reversal and skewing are unimodular matrices, and a nest is tiled after it is made fully permutable. Their PLDI paper of the same year added the reuse vector spaces, the localized space and the cost per iteration, and searched the subsets of the loops for the cheapest one that can be tiled innermost. Lam, Rothberg and Wolf studied in the same year how the tile size and cache conflicts change the result. McKinley, Carr and Tseng in 1996 gave a simpler cost model, and the polyhedral schedulers of the 2000s, such as Pluto, extended tiling to imperfect nests.
References
- Michael E. Wolf and Monica S. Lam, A data locality optimizing algorithm, Proceedings of the ACM SIGPLAN 1991 Conference on Programming Language Design and Implementation (PLDI), 1991, 30-44, Section 4 (self-temporal, self-spatial and group reuse as vector spaces, uniformly generated sets, the localized vector space, memory accesses per iteration) and Section 5 (subsets of the loops tiled innermost, the SRP transformation)
- Michael E. Wolf and Monica S. Lam, A loop transformation theory and an algorithm to maximize parallelism, IEEE Transactions on Parallel and Distributed Systems 2(4), 1991, 452-471, unimodular transformations, fully permutable loop nests, and skewing to make a nest fully permutable
- Dennis Gannon, William Jalby and Kyle Gallivan, Strategies for cache and local memory management by global program transformation, Journal of Parallel and Distributed Computing 5(5), 1988, 587-616, uniformly generated references and reference windows
- Monica S. Lam, Edward E. Rothberg and Michael E. Wolf, The cache performance and optimizations of blocked algorithms, ASPLOS-IV, 1991, 63-74, the choice of tile size and the effect of cache interference on tiled code
- Kathryn S. McKinley, Steve Carr and Chau-Wen Tseng, Improving data locality with loop transformations, ACM Transactions on Programming Languages and Systems 18(4), 1996, 424-453, a simpler cost model in cache lines per loop and a memory order for permutation, fusion, distribution and reversal
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 SBSZSV Edit this page History Report an error Markdown