External-Memory & Cache-Oblivious Algorithms
The I/O model, B-trees, and algorithms that are fast on every level of cache.
With 8 GiB of memory and 1 MiB disk blocks, a terabyte of 8-byte keys sorts in just two passes over the disk, and no comparison-based algorithm can do fundamentally better. Aggarwal and Vitter (1988) explained why with three numbers: the data size , the memory size and the block size . A decade later, Frigo, Leiserson, Prokop and Ramachandran showed that many algorithms reach the optimal number of block transfers without knowing or at all, which makes them optimal at every level of a memory hierarchy at once.
What you’ll learn
- State the external-memory model and its four fundamental bounds: scanning, sorting, permuting and searching.
- Derive the multiway merge sort bound , and sketch Aggarwal and Vitter's counting lower bound.
- Prove the search lower bound, and show that the van Emde Boas layout achieves transfers without knowing .
- Analyze cache-oblivious matrix transposition and multiplication under the tall-cache assumption.
- State what obliviousness cannot do: the factor for searching, and the tall cache that optimal sorting requires.
The external-memory model
| Problem | I/Os | In internal memory |
|---|---|---|
| scan items | ||
| sort items | ||
| permute items | ||
| search among sorted items |
Two surprises hide in this table. First, has an enormous base. With 1 MiB blocks and 8 GiB of memory, , and a terabyte ( bytes) is blocks, so . Sorting it takes two passes over the data: one to form sorted runs, one to merge all 128 of them at once.
Second, permuting is as hard as sorting. Moving each item straight to its destination costs up to one I/O per item, in all, whereas is usually far smaller, because one I/O moves items. The best way to apply a known permutation is therefore, typically, to sort the items by their destinations.
A file occupies blocks and memory holds blocks. Multiway merge sort forms sorted runs of items, then merges about runs at a time. How many passes over the data does it make, run formation included?
Show the answer
3
Run formation is one pass and leaves runs. Each merge pass divides the number of runs by about : , two merge passes. In total passes, matching . Each pass reads and writes every block, so the sort costs about I/Os.
Sorting: multiway merging and its lower bound
Runs. Read items, sort them in memory, write them back; repeat. One pass of I/Os leaves sorted runs.
Merges. Keep one block of each of runs in memory, plus one output block. Repeatedly move the smallest item to the output, writing the output block when it is full and reading a run's next block when its current one is used up. One pass merges every group of runs and costs I/Os:
Total. Since , the run pass and the merge passes combine into one logarithm; replacing by changes only the constant, because :
Track how many of the input orders are still consistent with what the algorithm knows. Comparisons are free, so when a block enters memory the algorithm learns how its items compare with the items already there. That splits the remaining orders into at most classes, the possible positions of the new items among the old ones, times for the order within the block if this is its first visit (blocks written by the algorithm were in memory together, so their internal order is already known):
There are only first inputs. After inputs the algorithm must have narrowed the possibilities down to one order, so
Take logarithms, with , and :
The Optimal lesson External Sorting turns this into practice, including replacement selection, which produces runs of expected length on random input. The same counting argument gives the permuting bound .
Searching without knowing B
A B-tree with keys per node matches this bound: I/Os per search, insertion and deletion (see the Optimal lesson B-Trees & B+ Trees). With keys and 255 keys per block, the bound demands at least 4 I/Os, against about 22 for binary search on a sorted array, which misses on all but its last probes.
But a B-tree must know . Can one layout of a plain binary search tree be good for every block size at once? Prokop (1999) found one, named after van Emde Boas's recursive priority queue. To lay out a complete binary tree of height , cut it at half its height into a top tree and about bottom trees, each of height about . Store the top tree first and then the bottom trees one after another, each laid out recursively in the same way.
Follow the recursion down to the first level at which the pieces have at most nodes. Their parents had more than nodes and each cut halves the height, so each of these base trees has height at least about . A base tree is stored contiguously in at most words, so it spans at most 2 blocks, whatever the alignment:
A root-to-leaf path of length about passes through base trees one after another, spending at least levels in each, so it visits at most about of them:
Two blocks per base tree give the bound. Nothing in the layout depends on : only the analysis picks a level of the recursion, and a different simply picks a different level.
| Layout of a tree with 65,535 keys | Blocks of 16 nodes | Blocks of 256 nodes |
|---|---|---|
| sorted array (binary search) | 13 | 9 |
| breadth-first order, as in a binary heap | 14 | 10 |
| van Emde Boas order | 8 | 4 |
| the bound | 18 | 10 |
Cache-oblivious algorithms
The recipe is divide and conquer. Recursion halves a problem until, at some level, a subproblem fits in the cache; the analysis charges the misses at that level, which the algorithm itself never needs to know. Matrix transposition is the classic first example:
def transpose(A, T, r0, r1, c0, c1):
"""Set T[c][r] = A[r][c] for r in [r0, r1) and c in [c0, c1), without knowing M or B."""
if (r1 - r0) * (c1 - c0) <= 16: # small base case
for r in range(r0, r1):
for c in range(c0, c1):
T[c][r] = A[r][c]
elif r1 - r0 >= c1 - c0: # split the longer side in half
rm = (r0 + r1) // 2
transpose(A, T, r0, rm, c0, c1)
transpose(A, T, rm, r1, c0, c1)
else:
cm = (c0 + c1) // 2
transpose(A, T, r0, r1, c0, cm)
transpose(A, T, r0, r1, cm, c1)Splitting the longer side keeps the pieces nearly square. With a tall cache, the recursion reaches pieces whose sides lie between about and and which fit in the cache together with their transposes; each costs misses for elements, so an transpose costs misses, as much as a scan. The plain double loop costs misses on large matrices, because one of the two matrices is always walked by columns.
Split each matrix into four blocks and compute the eight block products recursively. The overhead per call is misses, so above the cache-sized level the recurrence is
Let be the size at which three blocks fit in the cache, , so . A subproblem of that size is loaded once, at misses (the tall cache makes , so each block row spans whole lines), and then runs without further misses:
The recursion tree has leaves of that size, and they dominate the cost:
That matches tiling and the Hong–Kung lower bound, with no tile size to tune. Sorting has an oblivious optimum too: funnelsort (Frigo et al., 1999), which merges through a recursive tree of buffered mergers called funnels, sorts with misses under a tall cache.
Why is a cache-oblivious algorithm that is optimal for every and in the two-level model also optimal on a machine with L1, L2 and L3 caches and DRAM?
- Because a cache-oblivious algorithm never uses memory beyond the L1 cache
- Because each adjacent pair of levels acts as a two-level cache with its own and , and the analysis held for all of them at once
- Because a cache-oblivious algorithm measures and when it starts
- Because recursive algorithms never miss in multilevel caches
Show the answer
B. Because each adjacent pair of levels acts as a two-level cache with its own and , and the analysis held for all of them at once
The algorithm never consults or , so one and the same execution can be analyzed with L1's parameters, with L2's, and so on, and it is optimal for each pair simultaneously, assuming inclusive levels and LRU-like replacement, up to the constant factors the regularity argument allows.
Limits, dynamic structures and the frontier
Dynamic structures. Bender, Demaine and Farach-Colton (2000; journal version 2005) built a cache-oblivious B-tree that searches in transfers and updates in amortized. It keeps the items in a packed-memory array, an array with evenly spread gaps that re-spreads a region whenever it becomes too dense, indexed by a tree in van Emde Boas layout.
Insertions can be much cheaper than searches. A B-tree pays I/Os per insertion. Buffering insertions and pushing them down in batches, as in the buffer tree (Arge, 2003), the -tree and the log-structured merge tree (O'Neil, Cheng, Gawlick & O'Neil, 1996) behind LevelDB and RocksDB, brings an insertion down to amortized I/Os while a search costs , for any . Brodal and Fagerberg (2003) proved this trade-off between insertions and searches optimal.
Key takeaways
- The external-memory model counts block transfers: scanning costs , sorting , permuting and searching ; the huge base makes external sorting a matter of a few passes.
- Multiway merge sort matches the sorting bound, and a count of the input orders proves it optimal for comparison-based algorithms that move items without encoding them.
- Cache-oblivious algorithms use neither nor yet are optimal for all of them, hence at every level of a hierarchy: recursive transposition and multiplication, funnelsort, and the van Emde Boas layout with at most transfers per search.
- Obliviousness has proven limits: a factor for searching, a tall cache for sorting, and no optimal permuting for all and .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In the external-memory model with large blocks, what is asymptotically the cheapest way to apply a known permutation to items on disk?
- Move each item directly to its destination: I/Os, the minimum possible
- Load all the items into memory first
- Scan once: I/Os suffice for any permutation
- Sort the items by destination, which costs , usually far below I/Os
Show the answer
D. Sort the items by destination, which costs , usually far below I/Os
Aggarwal and Vitter proved that permuting costs I/Os. For realistic and , is a small multiple of , far below , so sorting by destination wins.
Why can no comparison-based structure search sorted items in fewer than about I/Os?
- Each I/O brings at most new items into memory, and comparing the query with them leaves at most possible intervals, so each I/O divides the outcomes by at most
- Because a B-tree has height , and B-trees are the only external search structures
- Because the search must read every block of the file
- Because binary search needs probes and each probe is an I/O
Show the answer
A. Each I/O brings at most new items into memory, and comparing the query with them leaves at most possible intervals, so each I/O divides the outcomes by at most
It is an information argument: divisions by at most are needed to isolate one of outcomes. B-trees and the van Emde Boas layout reach it up to a constant factor.
The van Emde Boas layout searches in transfers for every block size . What does it give up against a B-tree tuned to one known ?
- Nothing: both need exactly transfers
- A constant factor: no cache-oblivious search structure can guarantee fewer than transfers, while a B-tree needs
- A factor of , like binary search
- It cannot support search at all once exceeds
Show the answer
B. A constant factor: no cache-oblivious search structure can guarantee fewer than transfers, while a B-tree needs
Bender, Brodal, Fagerberg, Ge, He, Hu, Iacono and López-Ortiz (2003) proved the lower bound, a provable separation between knowing and not knowing it; randomized variants of the layout approach it.
What does the tall-cache assumption say, and where is it known to be necessary?
- The cache holds at least about as many lines as a line holds words; without it, no cache-oblivious comparison-based sort is optimal for all and
- The cache must be at least as large as one block; scanning needs it
- Cache lines must be taller than they are wide; transposition needs it
- The data must fit in words; searching needs it
Show the answer
A. The cache holds at least about as many lines as a line holds words; without it, no cache-oblivious comparison-based sort is optimal for all and
means lines. Brodal and Fagerberg (2003) proved that optimal cache-oblivious comparison-based sorting needs such an assumption, and that even with it, no cache-oblivious algorithm permutes optimally for all and .
Further reading
- A. Aggarwal & J. S. Vitter, "The input/output complexity of sorting and related problems," Communications of the ACM 31(9) (1988), 1116–1127.
- M. Frigo, C. E. Leiserson, H. Prokop & S. Ramachandran, "Cache-oblivious algorithms," Proceedings of FOCS (1999); journal version in ACM Transactions on Algorithms 8(1) (2012).
- M. A. Bender, E. D. Demaine & M. Farach-Colton, "Cache-oblivious B-trees," SIAM Journal on Computing 35(2) (2005), 341–358; first presented at FOCS 2000.
- G. S. Brodal & R. Fagerberg, "On the limits of cache-obliviousness," Proceedings of STOC (2003).
- J. S. Vitter, "Algorithms and data structures for external memory," Foundations and Trends in Theoretical Computer Science 2(4) (2008).