TExcelTAD
Home › Advanced & Succinct Data Structures › Cache-Oblivious Algorithms and Matrix Transposition

Cache-Oblivious Algorithms and Matrix Transposition

Every algorithm in the external-memory lessons so far uses MM and BB: 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 MM or BB: its code contains neither. If it is optimal for every MM and BB, 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:

  1. 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).
  2. The cache is fully associative: any block can go into any slot.

Both are justified by known results. LRU with a cache of size 2M2M incurs at most twice the misses of the optimal policy with size MM (Sleator and Tarjan, 1985, the competitive analysis of paging), so for algorithms whose miss count changes by a constant factor when MM 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 M=Ω(B2)M = \Omega(B^2) (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 MM 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 MM") although the algorithm never knows where it is.

Matrix transposition

Write B=ATB = A^T for an n×nn \times n matrix stored row by row. The naive loop reads AA row by row (good: consecutive addresses) but writes BB column by column: consecutive writes are nn words apart, each in a different block. Unless nn blocks fit in the cache, every write misses: Θ(n2)\Theta(n^2) misses instead of the Θ(n2/B)\Theta(n^2/B) 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.

text
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 cM/2c\sqrt{M}/2 and cMc\sqrt{M}, for a small constant cc. A k×k′k \times k' submatrix of AA occupies at most k(k′/B+2)k(k'/B + 2) blocks (each row may also cut a block at each end), and its image in BB at most k′(k/B+2)k'(k/B + 2). By the tall-cache assumption B≤cM≤2kB \le c\sqrt{M} \le 2k, so the +2+2 terms add at most a constant factor and both pieces together take O(kk′/B)=O(M/B)O(kk'/B) = O(M/B) blocks: for small enough cc they fit in the cache, and transposing the submatrix costs O(kk′/B)O(kk'/B) misses, each block loaded once. The submatrices at that level partition the matrix, so the total is

Q(n)=O ⁣(n2B)misses, for every M and B with M=Ω(B2)Q(n) = O\!\left(\frac{n^2}{B}\right) \quad \text{misses, for every } M \text{ and } B \text{ with } M = \Omega(B^2)

which is optimal. The program simulates an LRU cache for several pairs (M,B)(M, B) on a 128×128128 \times 128 matrix and compares the naive loop, the recursive version, and a cache-aware tiled version that uses B×BB \times B tiles (it must be told BB).

python · try it yourself
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 2n2/B2n^2/B exactly, like the tiled version, without knowing BB. The naive loop misses on almost every write.
  • When nB≤MnB \le M (third row), all the blocks of nn consecutive columns fit, and even the naive loop is optimal.
  • In the last row the cache has only 88 blocks of 3232 words: M=256<B2=1024M = 256 < B^2 = 1024. 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 256×256256 \times 256 matrix.

cpp · try it yourself
#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 AA, BB and CC into four quadrants and compute the eight half-size products Cij+=AikBkjC_{ij} \mathrel{+}= A_{ik} B_{kj} recursively. At the level where three blocks fit in the cache, of side about M/3\sqrt{M/3}, each block product costs O(M/B)O(M/B) misses, and there are (n/M)3(n / \sqrt{M})^3 of them, so the total is O(n2/B+n3/(BM))O(n^2/B + n^3/(B\sqrt{M})) misses under the tall-cache assumption, without knowing MM or BB. The naive ii-jj-kk loop walks down a column of BB for every entry of CC and misses on almost every access to BB. The program counts both on 32×3232 \times 32 matrices.

python · try it yourself
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 n3/(BM)n^3/(B\sqrt{M}); 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 O(N/B+1)O(N/B + 1) trivially oblivious
matrix transposition O(n2/B)O(n^2/B) tall cache
matrix multiplication (recursive, 8 subproducts) O(n2/B+n3/(BM))O(n^2/B + n^3/(B\sqrt{M})) optimal for the standard algorithm (Hong and Kung's bound)
static search tree O(log⁡BN)O(\log_B N) van Emde Boas layout
sorting O(NBlog⁡M/BNB)O(\frac{N}{B} \log_{M/B} \frac{N}{B}) funnelsort, tall cache
dynamic B-tree (search, insert, delete) O(log⁡BN)O(\log_B N) (updates amortized) Bender, Demaine and Farach-Colton (2000)
priority queue O(1Blog⁡M/BNB)O(\frac{1}{B} \log_{M/B} \frac{N}{B}) 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 O(sort⁡(N))O(\operatorname{sort}(N)) for all MM and BB.

Test yourself

What distinguishes a cache-oblivious algorithm?

  1. It never misses the cache
  2. It is analysed in the DAM model but its code does not depend on MM or BB, so it is efficient at every level of a memory hierarchy
  3. It uses only scanning
  4. It runs only on machines without a cache

Why does the naive transposition loop incur about n2n^2 misses on large matrices?

  1. It reads AA column by column
  2. It writes BB column by column, so consecutive writes fall in different blocks, and the nn blocks of a column strip do not fit in the cache
  3. It uses recursion
  4. Because of the tall-cache assumption

What does the tall-cache assumption M=Ω(B2)M = \Omega(B^2) guarantee in the transposition analysis?

  1. That the matrix fits in the cache
  2. That a Θ(M)×Θ(M)\Theta(\sqrt{M}) \times \Theta(\sqrt{M}) submatrix touches only O(M/B)O(M/B) blocks, because each of its rows is at least about BB words long
  3. That LRU is optimal
  4. That nn is a power of two