Algorithm Search⌘K

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

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 A[Hi+c]A[H i + c], the iterations that touch the same element differ by a vector in the nullspace of HH. The loops that run inside one tile span the localized space LL, and reuse along a direction in LL 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 LL, 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 kk with rectangular bounds. A set DD of constant dependence distance vectors, each nonzero and lexicographically positive. A list of array accesses A[Hi+c]A[H i + c], where HH is an integer matrix with kk columns and cc a constant vector; all accesses with the same array and the same HH form one uniformly generated set. The arrays are in row-major order. Two numbers for the cost model: ll, the number of elements in a cache line, and ss, an estimate of the trip count of a loop inside a tile.

Output. A set II of loops to localize, and a unimodular matrix TT that keeps every dependence and makes the loops of II 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

  1. WOLF-LAM(accesses A[H i + c], distances D, depth k, line l, trip s)
  2. 1for each uniformly generated set (A, H) do R_ST <- ker H; R_SS <- ker H_S
  3. 2best <- none
  4. 3for each subset I of the loops, smallest first do
  5. 4T <- signed permutation with I innermost, then skew of I, with I fully permutable
  6. 5if no such T is legal then continue
  7. 6L <- span{e_j : j in I}
  8. 7cost <- sum over the sets of (g_S + (g_T - g_S) / l) / (l^e s^dim(R_ST ∩ L))
  9. 8if best = none or cost < best.cost then best <- (I, T, cost)
  10. 9apply best.T and tile the |I| innermost loops by B when |I| >= 2

Line L1 computes the reuse spaces. RST=ker⁡HR_{ST} = \ker H holds the directions in which one access touches the same element again. HSH_S is HH with its last row set to 00, so RSS=ker⁡HSR_{SS} = \ker H_S 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 HH, so one computation serves the whole set.

Lines L3 to L5 test whether the loops of II can run innermost. Line L4 tries every order and every sign (loop reversal) of the loops outside II, then every order and sign of the loops of II, 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 II, so two iterations of one tile differ only on the loops of II, whatever the skew is.

Line L7 is the cost model of the paper. gTg_T is the number of classes of offsets in a set, where c1c_1 and c2c_2 are in one class when Hr=c1−c2H r = c_1 - c_2 for some r∈Lr \in L: the accesses of a class touch the same data within a tile, so the class fetches it once. gSg_S is the same count for HSH_S and the offsets with their last entry set to 00. The classes of gSg_S fetch a cache line; the extra temporal classes inside them cost 1/l1/l each. The term sdim⁡(RST∩L)s^{\dim(R_{ST} \cap L)} divides by ss for each localized direction of self-temporal reuse. e=1e = 1 when RSS∩LR_{SS} \cap L is larger than RST∩LR_{ST} \cap L, which means the access also walks along a cache line inside the tile; then the cost divides by ll. Otherwise e=0e = 0. 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: H=(010001)H = \begin{pmatrix} 0 & 1 & 0 \\ 0 & 0 & 1 \end{pmatrix} with the offsets (0,0)(0,0), (1,0)(1,0), (−1,0)(-1,0), (0,1)(0,1), (0,−1)(0,-1). Line L1 gives RST=span⁡{e1}R_{ST} = \operatorname{span}\{e_1\}: every sweep reads the same array. HS=(010000)H_S = \begin{pmatrix} 0 & 1 & 0 \\ 0 & 0 & 0 \end{pmatrix} gives RSS=span⁡{e1,e3}R_{SS} = \operatorname{span}\{e_1, e_3\}. The distances are (0,1,0)(0,1,0), (0,0,1)(0,0,1), (1,0,0)(1,0,0), (1,−1,0)(1,-1,0) and (1,0,−1)(1,0,-1). The candidates of lines L3 to L8, with l=8l = 8 and s=100s = 100:

localized loops II gTg_T, gSg_S, ee, dim⁡(RST∩L)\dim(R_{ST} \cap L) cost value
none 5, 3, 0, 0 3+2/l3 + 2/l 3.25
{i3}\{i_3\} 3, 3, 1, 0 3/l3/l 0.375
{i2}\{i_2\} 3, 1, 0, 0 1+2/l1 + 2/l 1.25
{i2,i3}\{i_2, i_3\} 1, 1, 1, 0 1/l1/l 0.125
{i1,i2,i3}\{i_1, i_2, i_3\} 1, 1, 1, 1 1/(ls)1/(l s) 0.00125
{i1}\{i_1\}, {i1,i2}\{i_1, i_2\}, {i1,i3}\{i_1, i_3\} not legal

Every set with i1i_1 inside and some other loop outside fails line L5. The outermost loop is then i2i_2 or i3i_3. The distances (0,1,0)(0, 1, 0) and (1,−1,0)(1, -1, 0) have opposite signs at i2i_2, and (0,0,1)(0, 0, 1) and (1,0,−1)(1, 0, -1) have opposite signs at i3i_3, 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 (i1,i2,i3)(i_1, i_2, i_3) and skews by T=(100110211)T = \begin{pmatrix} 1 & 0 & 0 \\ 1 & 1 & 0 \\ 2 & 1 & 1 \end{pmatrix}. The distances become (0,1,1)(0,1,1), (0,0,1)(0,0,1), (1,1,2)(1,1,2), (1,0,1)(1,0,1) and (1,1,1)(1,1,1), 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 30×3030 \times 30 interior of a 32×3232 \times 32 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 i2,i3i_2, i_3 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 RST=0R_{ST} = 0 and RSS=span⁡{e1}R_{SS} = \operatorname{span}\{e_1\}. Localizing {i}\{i\} costs 1/l1/l and localizing {j}\{j\} costs 11, so the algorithm picks {i}\{i\} and interchanges the loops. For 64×6464 \times 64 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 ii and i+ri + r exactly when Hr=0H r = 0, and the same row exactly when HSr=0H_S r = 0. Two accesses of one set touch the same element at ii and i′i' exactly when H(i′−i)=c1−c2H(i' - i) = c_1 - c_2; with i′−i∈Li' - i \in L this is an equivalence relation on the offsets, because HLH L is a subspace.

The chosen nest keeps every dependence. TT is a signed permutation followed by a unitriangular skew, so det⁡T=±1\det T = \pm 1. For each distance, the outer part of TdT d is lexicographically positive, or it is 00 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 ⌊b/B⌋\lfloor b / B \rfloor 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 II exactly when some signed permutation with the loops of II 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 kk and a box of iterations P⊂ZkP \subset \mathbb{Z}^k. DD is a finite set of nonzero distance vectors, each lexicographically positive. Every dependence of the nest goes from an iteration ii to the iteration i+di + d with d∈Dd \in D, or stays inside one iteration; the body of one iteration runs as a unit, with its statements in text order. An access A[Hi+c]A[H i + c] touches, at iteration ii, the element of array AA with subscripts Hi+cH i + c, where HH is an integer matrix with kk columns and cc 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. HSH_S is HH with its last row set to 00.

For a set II of loops, line L4 looks for a signed permutation matrix QQ, whose rows are ±ej\pm e_j, that lists the loops outside II first and the loops of II last, and for a lower unitriangular integer matrix SS of size m=∣I∣m = |I|. It then sets

T=(100S)Q.T = \begin{pmatrix} 1 & 0 \\ 0 & S \end{pmatrix} Q .

For y=Txy = T x we write y=(o,b)y = (o, b), with oo the first k−mk - m entries (the outer part) and bb the last mm entries (the band part). Line L9 runs the iterations in the order of the key

κ(i)=(o, ⌊b1/B⌋,…,⌊bm/B⌋, b)where (o,b)=Ti,\kappa(i) = \bigl(o,\ \lfloor b_1 / B \rfloor, \dots, \lfloor b_m / B \rfloor,\ b\bigr) \quad\text{where } (o, b) = T i,

compared lexicographically, with the floor entries left out when m≤1m \le 1. 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 ii and i+ri + r if and only if r∈ker⁡Hr \in \ker H.

Proof. H(i+r)+c=Hi+cH(i + r) + c = H i + c if and only if Hr=0H r = 0. □\square

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 ii and i+ri + r if and only if r∈ker⁡HSr \in \ker H_S.

Proof. The subscripts at i+ri + r and at ii differ by HrH r. They agree in all places but the last exactly when every row of HH except the last gives 00 on rr, which is HSr=0H_S r = 0. □\square

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 HSH_S. Since ker⁡H⊆ker⁡HS\ker H \subseteq \ker H_S, temporal reuse is a special case of spatial reuse.

Lemma 3 (group reuse). Let two accesses have the same array and the same HH and offsets c1,c2c_1, c_2. Access 1 at iteration ii and access 2 at iteration i′i' touch the same element if and only if H(i′−i)=c1−c2H (i' - i) = c_1 - c_2. For a subspace LL, the relation c1∼c2  ⟺  c1−c2∈HLc_1 \sim c_2 \iff c_1 - c_2 \in H L is an equivalence relation on the offsets.

Proof. Hi+c1=Hi′+c2H i + c_1 = H i' + c_2 is the same as H(i′−i)=c1−c2H(i' - i) = c_1 - c_2. The image HLH L is a subspace, so it contains 00, it is closed under negation, and it is closed under addition: these give reflexivity, symmetry and transitivity. □\square

Because ∼\sim is already transitive, the union of all pairs with c1∼c2c_1 \sim c_2, which the implementation forms, gives exactly its classes. The number of classes is gTg_T; the same with HSH_S and the offsets with their last entry set to 00 is gSg_S.

The test c1−c2∈HLc_1 - c_2 \in H L is over the rational numbers. When every row of HH is a unit vector, that is, every subscript is a loop index plus a constant, and LL is spanned by unit vectors, a rational solution rr can be replaced by an integer one: the entries of HrH r are entries of rr, so we can set each needed entry of rr to the integer entry of c1−c2c_1 - c_2. 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 oo differ by a vector of span⁡{ej:j∈I}\operatorname{span}\{e_j : j \in I\}.

Proof. The first k−mk - m rows of TT are the first k−mk - m rows of QQ, which are ±ej\pm e_j for the loops j∉Ij \notin I. So oo lists the entries ±ij\pm i_j, j∉Ij \notin I. If two iterations have the same oo, their difference is 00 at every j∉Ij \notin I. □\square

So the iterations inside one tile, and for large tiles inside one run of the band, differ only along the loops of II, whatever the skew SS is. This is the localized space LL of line L6.

Part 3: legality of the chosen transformation

Lemma 5 (unimodular). det⁡T=±1\det T = \pm 1.

Proof. det⁡Q=±1\det Q = \pm 1 for a signed permutation matrix, and SS is unitriangular with determinant 11. □\square

So i↦Tii \mapsto T i is a bijection of Zk\mathbb{Z}^k, and the keys κ(i)\kappa(i) of distinct iterations are distinct.

Lemma 6 (the band is fully permutable). If line L4 accepts (Q,S)(Q, S), then for every d∈Dd \in D, with (o,b)=Td(o, b) = T d: either oo is lexicographically positive, or o=0o = 0, every bl≥0b_l \ge 0, and b≠0b \ne 0.

Proof. Line L4 accepts QQ only when the outer part of QdQ d is lexicographically nonnegative for every dd, and, for every dd whose outer part is 00, the band part uu of QdQ d is lexicographically positive. The outer part of TdT d is the outer part of QdQ d. If it is not 00, it is lexicographically positive.

Now let it be 00, and let uu be the band part of QdQ d. The skew is computed one loop at a time: b1=u1b_1 = u_1 and bl=ul+fl(b1+⋯+bl−1)b_l = u_l + f_l (b_1 + \dots + b_{l-1}) for l≥2l \ge 2, where fl=max⁡(0,max⁡(−ul))f_l = \max(0, \max(-u_l)) over all dd with outer part 00. We show by induction on ll that b1,…,bl≥0b_1, \dots, b_l \ge 0, and that b1=⋯=bl=0b_1 = \dots = b_l = 0 implies u1=⋯=ul=0u_1 = \dots = u_l = 0.

For l=1l = 1: uu is lexicographically positive, so u1≥0u_1 \ge 0, and b1=u1b_1 = u_1.

For l≥2l \ge 2, let σ=b1+⋯+bl−1≥0\sigma = b_1 + \dots + b_{l-1} \ge 0. If σ≥1\sigma \ge 1, then bl=ul+flσ≥ul+fl≥0b_l = u_l + f_l \sigma \ge u_l + f_l \ge 0, because fl≥0f_l \ge 0 and fl≥−ulf_l \ge -u_l. If σ=0\sigma = 0, then b1=⋯=bl−1=0b_1 = \dots = b_{l-1} = 0, so u1=⋯=ul−1=0u_1 = \dots = u_{l-1} = 0 by induction; then ulu_l is the first entry of uu that can be nonzero, so ul≥0u_l \ge 0 because uu is lexicographically positive, and bl=ul≥0b_l = u_l \ge 0. In both cases the second claim also holds at ll.

At l=ml = m, if b=0b = 0 then u=0u = 0, which is false since uu is lexicographically positive. So b≠0b \ne 0. □\square

The matrix SS that line L4 builds has the rows sl=el+fl(s1+⋯+sl−1)s_l = e_l + f_l (s_1 + \dots + s_{l-1}), so that sl⋅u=ul+fl(b1+⋯+bl−1)s_l \cdot u = u_l + f_l (b_1 + \dots + b_{l-1}); that is the recurrence above.

Lemma 7 (the tiled order keeps every dependence). For every dependence from ii to j=i+dj = i + d, d∈Dd \in D, κ(i)<κ(j)\kappa(i) < \kappa(j).

Proof. Let (o,b)=Ti(o, b) = T i and (o′,b′)=Tj=Ti+Td(o', b') = T j = T i + T d. By Lemma 6, either the outer part of TdT d is lexicographically positive, and then o′>oo' > o and κ(j)>κ(i)\kappa(j) > \kappa(i) in the first part of the key; or o′=oo' = o and b′=b+δb' = b + \delta with δ≥0\delta \ge 0 in every entry and δ≠0\delta \ne 0. In the second case, ⌊bl′/B⌋≥⌊bl/B⌋\lfloor b'_l / B \rfloor \ge \lfloor b_l / B \rfloor for every ll, because the floor is monotone. If some tile entry is larger, the first such entry decides, and κ(j)>κ(i)\kappa(j) > \kappa(i). If all tile entries are equal, the keys agree up to bb and b′b', and b′−b=δb' - b = \delta is nonnegative and nonzero, so its first nonzero entry is positive and b′>bb' > b. When m≤1m \le 1 there are no tile entries and the same argument applies directly. When m=0m = 0 the band part is empty, so the second case cannot happen and the outer part decides. □\square

Theorem 1 (same result). The nest that runs the iterations of PP in increasing κ\kappa 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 PP 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. □\square

Lemma 8 (completeness of line L4). For a set II, line L4 finds (Q,S)(Q, S) if and only if some signed permutation QQ that lists the loops of II last makes QdQ d lexicographically positive for every d∈Dd \in D.

Proof. If L4 accepts QQ, then for every dd the outer part of QdQ d is lexicographically nonnegative, and if it is 00, the band part is lexicographically positive. In both cases QdQ d is lexicographically positive. Conversely, if QdQ d is lexicographically positive for every dd, then its outer part is lexicographically nonnegative, and when that part is 00, 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 QQ or an earlier one that passes the same test; the skew then always exists by Lemma 6. □\square

Theorem 2 (cheapest legal set). Let F\mathcal{F} be the sets II for which some signed permutation with the loops of II last is legal. The algorithm returns a set I∗∈FI^* \in \mathcal{F} whose cost in line L7 is the minimum over F\mathcal{F}, and among sets of equal cost the first in the order of line L3.

Proof. F\mathcal{F} is not empty: the identity is legal for I=∅I = \emptyset, because every d∈Dd \in D is lexicographically positive. Line L3 enumerates every subset of the loops. By Lemma 8, line L5 skips exactly the subsets outside F\mathcal{F}. Line L8 replaces the best only on a strictly smaller cost, so after the loop the best is the first subset of minimum cost. □\square

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 2k2^k subsets. For one subset, line L4 tries at most k! 2kk!\,2^k signed permutations and checks each against DD distances in O(kD)O(k D); the skew costs O(k2D)O(k^2 D). Line L7 compares the offsets of each set in pairs, and each comparison is a rank computation of O(k3)O(k^3) on vectors of length at most kk, for a total of O(k3A2)O(k^3 A^2). In all, O(4kk! kD+2kk3A2)O(4^k k!\, k D + 2^k k^3 A^2). Loop nests are shallow; for k=3k = 3 there are 8 subsets and at most 48 signed permutations each. Line L1 is done once per set. The extra space is O(k2)O(k^2) for the matrices and O(A)O(A) for the classes. The implementation produces the tiled order by sorting the NN iterations on their keys, O(Nlog⁡N)O(N \log N); 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 II and TT does not depend on BB; 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 O(n2d)O(n^2 d) for depth nn and dd 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 k≤4k \le 4.
  • 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. HSH_S 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: (1,−1,0)(1, -1, 0) has a negative entry. Tiling it without the skew changes the result.
  • A zero distance in line L4. A dependence inside one iteration has d=0d = 0. 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, {i}\{i\} and {i,j}\{i, j\} both cost 1/l1/l. With ≤\le 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 BB. In the example, tiles of 16 give more misses than the original order; choose BB 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.

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

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

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