Cache-Oblivious Algorithms and Matrix Transposition
Every algorithm in the external-memory lessons so far uses and : the fan-in of the merge, the node size of the B-tree. Real machines have several levels of cache with different block sizes, and the parameters differ from machine to machine. A cache-oblivious algorithm (Frigo, Leiserson, Prokop and Ramachandran, 1999) is analysed in the same DAM model but does not know or : its code contains neither. If it is optimal for every and , it is optimal at every level of the memory hierarchy at once.
The ideal-cache model
The model is the DAM model with two changes:
- The algorithm cannot choose what to fetch or evict. A block is fetched when a word in it is accessed, and the cache evicts blocks with the optimal offline policy (evict the block whose next use is furthest in the future).
- The cache is fully associative: any block can go into any slot.
Both are justified by known results. LRU with a cache of size incurs at most twice the misses of the optimal policy with size (Sleator and Tarjan, 1985, the competitive analysis of paging), so for algorithms whose miss count changes by a constant factor when halves ("regular" algorithms), bounds with the optimal policy carry over to LRU. Associativity can be simulated with hashing at a constant factor in expectation. The programs here simulate LRU directly.
The tall-cache assumption (the cache has at least as many blocks as a block has words) is needed by several cache-oblivious algorithms, including the one below.
The divide-and-conquer recipe
The characteristic cache-oblivious technique is recursion down to constant size. At some level of the recursion the subproblems fit in the cache, whatever is, and from then on they cost only the misses needed to load them once. The analysis picks that level ("the recursion reaches subproblems of size about ") although the algorithm never knows where it is.
Matrix transposition
Write for an matrix stored row by row. The naive loop reads row by row (good: consecutive addresses) but writes column by column: consecutive writes are words apart, each in a different block. Unless blocks fit in the cache, every write misses: misses instead of the needed to read and write both matrices once.
Recursive transposition. Split the longer side of the current submatrix in half and transpose the two halves recursively; stop at a constant-size block.
TRANSPOSE(A, B, r0, c0, rows, cols) // B[j][i] = A[i][j] for the rows x cols block at (r0, c0)
1 if rows * cols <= constant
2 transpose the block with two loops
3 else if rows >= cols
4 TRANSPOSE(A, B, r0, c0, rows/2, cols)
5 TRANSPOSE(A, B, r0 + rows/2, c0, rows - rows/2, cols)
6 else
7 TRANSPOSE(A, B, r0, c0, rows, cols/2)
8 TRANSPOSE(A, B, r0, c0 + cols/2, rows, cols - cols/2)Analysis. Each split halves the longer side, so the sides of a submatrix always stay within a factor 2 of each other. Follow the recursion down to the first level where the submatrices have sides between and , for a small constant . A submatrix of occupies at most blocks (each row may also cut a block at each end), and its image in at most . By the tall-cache assumption , so the terms add at most a constant factor and both pieces together take blocks: for small enough they fit in the cache, and transposing the submatrix costs misses, each block loaded once. The submatrices at that level partition the matrix, so the total is
which is optimal. The program simulates an LRU cache for several pairs on a matrix and compares the naive loop, the recursive version, and a cache-aware tiled version that uses tiles (it must be told ).
from collections import OrderedDict
class LRUCache:
def __init__(self, M, B):
self.B, self.capacity, self.blocks, self.misses = B, M // B, OrderedDict(), 0
def access(self, addr):
b = addr // self.B
if b in self.blocks: self.blocks.move_to_end(b)
else:
self.misses += 1
self.blocks[b] = True
if len(self.blocks) > self.capacity: self.blocks.popitem(last=False)
def naive(n, touch): # B[j][i] = A[i][j], row by row
for i in range(n):
for j in range(n):
touch(i * n + j); touch(n * n + j * n + i)
def recursive(n, touch, r0=0, c0=0, rows=None, cols=None):
rows = n if rows is None else rows
cols = n if cols is None else cols
if rows * cols <= 16: # tiny base case; no B or M anywhere in the code
for i in range(r0, r0 + rows):
for j in range(c0, c0 + cols):
touch(i * n + j); touch(n * n + j * n + i)
elif rows >= cols: # split the longer side in half
h = rows // 2
recursive(n, touch, r0, c0, h, cols)
recursive(n, touch, r0 + h, c0, rows - h, cols)
else:
h = cols // 2
recursive(n, touch, r0, c0, rows, h)
recursive(n, touch, r0, c0 + h, rows, cols - h)
def tiled(n, touch, t): # cache-aware: tiles of t x t, with t chosen from B
for bi in range(0, n, t):
for bj in range(0, n, t):
for i in range(bi, bi + t):
for j in range(bj, bj + t):
touch(i * n + j); touch(n * n + j * n + i)
n = 128
print(f"transpose a {n} x {n} matrix: {2 * n * n} accesses; lower bound 2n^2/B misses")
for M, B in [(512, 8), (2048, 16), (8192, 32), (256, 32)]:
res = []
for name, run in [("naive", lambda t: naive(n, t)), ("recursive", lambda t: recursive(n, t)),
("tiled B x B", lambda t: tiled(n, t, B))]:
c = LRUCache(M, B)
run(c.access)
res.append(f"{name} {c.misses:5}")
print(f"M = {M:4}, B = {B:2} (2n^2/B = {2 * n * n // B:4}): " + ", ".join(res))transpose a 128 x 128 matrix: 32768 accesses; lower bound 2n^2/B misses
M = 512, B = 8 (2n^2/B = 4096): naive 18432, recursive 4096, tiled B x B 4096
M = 2048, B = 16 (2n^2/B = 2048): naive 17408, recursive 2048, tiled B x B 2048
M = 8192, B = 32 (2n^2/B = 1024): naive 1024, recursive 1024, tiled B x B 1024
M = 256, B = 32 (2n^2/B = 1024): naive 16896, recursive 7680, tiled B x B 16896
- With a tall cache, the recursive version hits the bound exactly, like the tiled version, without knowing . The naive loop misses on almost every write.
- When (third row), all the blocks of consecutive columns fit, and even the naive loop is optimal.
- In the last row the cache has only blocks of words: . The tall-cache assumption fails and the recursive version is 7.5 times above the bound. Real caches are tall: an L1 cache of 32 KiB has 512 lines of 8 words.
In C++
The same experiment with an LRU cache built from std::list and std::unordered_map, on a matrix.
#include <cstdio>
#include <list>
#include <unordered_map>
#include <utility>
// A fully associative LRU cache of M/B blocks that counts misses.
class LRUCache {
long B, capacity;
std::list<long> order; // most recent at the front
std::unordered_map<long, std::list<long>::iterator> where;
public:
long misses = 0;
LRUCache(long M, long b) : B(b), capacity(M / b) {}
void access(long addr) {
long blk = addr / B;
auto it = where.find(blk);
if (it != where.end()) { order.splice(order.begin(), order, it->second); return; }
++misses;
order.push_front(blk);
where[blk] = order.begin();
if (static_cast<long>(order.size()) > capacity) { where.erase(order.back()); order.pop_back(); }
}
};
// Transpose the rows x cols block at (r0, c0) of an n x n matrix A (at address 0) into B (at n*n).
template <class F>
void transpose_rec(long n, long r0, long c0, long rows, long cols, F& touch) {
if (rows * cols <= 16) {
for (long i = r0; i < r0 + rows; ++i)
for (long j = c0; j < c0 + cols; ++j) { touch(i * n + j); touch(n * n + j * n + i); }
} else if (rows >= cols) {
transpose_rec(n, r0, c0, rows / 2, cols, touch);
transpose_rec(n, r0 + rows / 2, c0, rows - rows / 2, cols, touch);
} else {
transpose_rec(n, r0, c0, rows, cols / 2, touch);
transpose_rec(n, r0, c0 + cols / 2, rows, cols - cols / 2, touch);
}
}
int main() {
const long n = 256;
for (auto [M, B] : {std::pair{1024L, 16L}, std::pair{4096L, 32L}, std::pair{16384L, 64L}}) {
LRUCache naive(M, B), rec(M, B);
for (long i = 0; i < n; ++i)
for (long j = 0; j < n; ++j) { naive.access(i * n + j); naive.access(n * n + j * n + i); }
auto touch = [&](long a) { rec.access(a); };
transpose_rec(n, 0, 0, n, n, touch);
std::printf("n = %ld, M = %5ld, B = %2ld: naive %6ld misses, recursive %5ld, bound 2n^2/B = %ld\n",
n, M, B, naive.misses, rec.misses, 2 * n * n / B);
}
}n = 256, M = 1024, B = 16: naive 69632 misses, recursive 8192, bound 2n^2/B = 8192
n = 256, M = 4096, B = 32: naive 67584 misses, recursive 4096, bound 2n^2/B = 4096
n = 256, M = 16384, B = 64: naive 66560 misses, recursive 2048, bound 2n^2/B = 2048
Matrix multiplication
The same recipe multiplies matrices: split , and into four quadrants and compute the eight half-size products recursively. At the level where three blocks fit in the cache, of side about , each block product costs misses, and there are of them, so the total is misses under the tall-cache assumption, without knowing or . The naive -- loop walks down a column of for every entry of and misses on almost every access to . The program counts both on matrices.
from collections import OrderedDict
class LRUCache:
def __init__(self, M, B):
self.B, self.capacity, self.blocks, self.misses = B, M // B, OrderedDict(), 0
def access(self, addr):
b = addr // self.B
if b in self.blocks: self.blocks.move_to_end(b)
else:
self.misses += 1
self.blocks[b] = True
if len(self.blocks) > self.capacity: self.blocks.popitem(last=False)
n = 32 # C = A * B, all n x n, row-major, one after another
A, Bm, C = 0, n * n, 2 * n * n
def naive(touch):
for i in range(n):
for j in range(n):
for k in range(n):
touch(A + i * n + k); touch(Bm + k * n + j); touch(C + i * n + j)
def rec(touch, i0=0, j0=0, k0=0, s=n): # 8 recursive products of half-size blocks
if s == 4:
for i in range(i0, i0 + s):
for j in range(j0, j0 + s):
for k in range(k0, k0 + s):
touch(A + i * n + k); touch(Bm + k * n + j); touch(C + i * n + j)
return
h = s // 2
for di in (0, h):
for dj in (0, h):
for dk in (0, h):
rec(touch, i0 + di, j0 + dj, k0 + dk, h)
for M, B in [(256, 8), (512, 16)]:
out = []
for name, f in [("naive i-j-k", naive), ("recursive", rec)]:
c = LRUCache(M, B)
f(c.access)
out.append(f"{name} {c.misses:6}")
bound = n ** 3 / (B * M ** 0.5)
print(f"n = {n}, M = {M}, B = {B}: " + ", ".join(out) + f"; n^3/(B sqrt M) = {bound:.0f}")n = 32, M = 256, B = 8: naive i-j-k 33024, recursive 1280; n^3/(B sqrt M) = 256
n = 32, M = 512, B = 16: naive i-j-k 32896, recursive 512; n^3/(B sqrt M) = 91
The recursive version is 25 to 60 times better than the naive loop and within a small constant factor of ; the exact constant depends on how many blocks of the three matrices compete for the cache.
Other cache-oblivious results
| Problem | Cache-oblivious bound | Note |
|---|---|---|
| scanning, reversing an array | trivially oblivious | |
| matrix transposition | tall cache | |
| matrix multiplication (recursive, 8 subproducts) | optimal for the standard algorithm (Hong and Kung's bound) | |
| static search tree | van Emde Boas layout | |
| sorting | funnelsort, tall cache | |
| dynamic B-tree (search, insert, delete) | (updates amortized) | Bender, Demaine and Farach-Colton (2000) |
| priority queue | amortized | funnel heaps |
Brodal and Fagerberg (2003) showed that the tall-cache assumption is necessary for cache-oblivious sorting to match the cache-aware bound: without it, no cache-oblivious algorithm achieves for all and .
Test yourself
What distinguishes a cache-oblivious algorithm?
- It never misses the cache
- It is analysed in the DAM model but its code does not depend on or , so it is efficient at every level of a memory hierarchy
- It uses only scanning
- It runs only on machines without a cache
Why does the naive transposition loop incur about misses on large matrices?
- It reads column by column
- It writes column by column, so consecutive writes fall in different blocks, and the blocks of a column strip do not fit in the cache
- It uses recursion
- Because of the tall-cache assumption
What does the tall-cache assumption guarantee in the transposition analysis?
- That the matrix fits in the cache
- That a submatrix touches only blocks, because each of its rows is at least about words long
- That LRU is optimal
- That is a power of two