The External-Memory (DAM) Model
On a real machine, reading a word from main memory costs about a hundred times as much as an arithmetic operation, and reading from an SSD or disk costs thousands to millions of times more. But memory is always moved in blocks: a cache line of 64 bytes, a page of 4 KiB, a disk block of many kilobytes. A program that uses every word of each block it fetches can be orders of magnitude faster than one that touches one word per block. The RAM model cannot see this difference. The external-memory model, also called the disk-access model (DAM) or I/O model (Aggarwal and Vitter, 1988), is the simplest model that can.
The disk model of Part I motivated B-trees with the same picture. This section makes it a model with proofs.
The model
- A fast memory (cache) of words and an unbounded slow memory (disk), both divided into blocks of words. So the cache holds blocks.
- Computation happens only on data in the cache, and is free.
- The cost of an algorithm is the number of block transfers (I/Os) between the two memories.
- The algorithm decides which blocks to fetch and which to evict. (In the cache-oblivious model of a later lesson, an optimal replacement policy does it instead; LRU is within a constant factor of that with a cache of twice the size.)
Typical requirements: at least, often the tall-cache assumption , which holds for real caches (a 32 KiB L1 cache with 64-byte lines has lines, much more than words).
The basic bounds
| Task | I/Os | Compare with RAM |
|---|---|---|
| scan consecutive words | ||
| search a sorted array by binary search | ||
| search a B-tree | , optimal for comparison-based search | |
| sort items | ||
| permute items (a given permutation) |
The sorting bound is due to Aggarwal and Vitter (1988), who proved it is tight for comparison-based sorting in the model, together with the permuting bound. It is the most important number in the model: many problems (list ranking, graph traversal, computational geometry) turn out to cost . The next lesson proves the upper bound with multiway merge sort.
A simulated cache
To count I/Os, the programs in this section simulate a cache of blocks with LRU replacement: every access to a word whose block is not cached is a miss (one I/O), and the least recently used block is evicted when the cache is full. The first program compares three access patterns on an array of words with and .
from collections import OrderedDict
import random
class LRUCache:
def __init__(self, M, B):
self.B, self.capacity = B, M // B
self.blocks = OrderedDict()
self.misses = 0
def access(self, addr):
b = addr // self.B
if b in self.blocks:
self.blocks.move_to_end(b) # most recently used
else:
self.misses += 1
self.blocks[b] = True
if len(self.blocks) > self.capacity:
self.blocks.popitem(last=False) # evict the least recently used block
N, B, M = 1 << 16, 64, 1 << 12
rng = random.Random(1988)
c = LRUCache(M, B)
for i in range(N): c.access(i)
print(f"scan of N = {N} words: {c.misses:6} I/Os (N/B = {N // B})")
c = LRUCache(M, B)
for _ in range(N): c.access(rng.randrange(N))
print(f"N random accesses: {c.misses:6} I/Os (about N(1 - M/N) = {N - M})")
c = LRUCache(M, B)
q = 1000
for _ in range(q):
x, lo, hi = rng.randrange(N), 0, N
while lo < hi: # binary search over positions 0..N-1
mid = (lo + hi) // 2
c.access(mid)
if mid < x: lo = mid + 1
else: hi = mid
print(f"{q} binary searches: {c.misses:6} I/Os, {c.misses / q:.1f} each (lg(N/B) = {(N // B).bit_length() - 1})")scan of N = 65536 words: 1024 I/Os (N/B = 1024)
N random accesses: 61427 I/Os (about N(1 - M/N) = 61440)
1000 binary searches: 5452 I/Os, 5.5 each (lg(N/B) = 10)
The scan uses each block fully and costs I/Os, 64 times fewer than random accesses. The binary searches cost about 5.5 I/Os each instead of , because the cache keeps the top of the implicit search tree (the first few midpoints, shared by all searches). With a cold cache each search costs about : the last steps stay inside one block, the first each touch a new one.
Why sorting is not
Sorting needs more than a scan, and the bound has an unusual shape. Two remarks explain it:
- The base of the logarithm. Merge sort in the DAM model merges sorted runs at once (one block of each run fits in the cache), so each pass reduces the number of runs by a factor , and each pass is a scan. That gives .
- Permuting is almost as hard as sorting. Moving item to position by direct writes costs up to one I/O per item. When , which is the usual case, sorting the items by destination is cheaper than moving them one by one. Aggarwal and Vitter showed that one of the two is always optimal.
import math
def sort_io(N, M, B):
return (N / B) * max(1.0, math.log(N / B) / math.log(M / B))
print(f"{'N':>12} {'M':>10} {'B':>6} | {'scan N/B':>10} {'sort(N)':>12} {'N lg N':>14} {'N (permute naively)':>20}")
for N, M, B in [(2 ** 24, 2 ** 20, 2 ** 10), (2 ** 30, 2 ** 24, 2 ** 12), (2 ** 30, 2 ** 15, 2 ** 3)]:
print(f"{N:>12} {M:>10} {B:>6} | {N // B:>10} {sort_io(N, M, B):>12.0f} {N * math.log2(N):>14.0f} {N:>20}") N M B | scan N/B sort(N) N lg N N (permute naively)
16777216 1048576 1024 | 16384 22938 402653184 16777216
1073741824 16777216 4096 | 262144 393216 32212254720 1073741824
1073741824 32768 8 | 134217728 301989888 32212254720 1073741824
For disk-like parameters (large blocks, in the thousands) the logarithm is 1 or 2: sorting costs a couple of scans, far below the I/Os of naive permuting. Only with tiny blocks and a small cache (the last row) does the factor grow, and even then sorting beats naive permuting.
Design rules the model teaches
- Scan, don't jump. Sequential access costs I/O per element.
- Merge many streams at once. The fan-in of a merge can be , not 2.
- Use the fan-out . Search trees should branch ways per node: B-trees revisited.
- Batch updates. Buffer trees (Arge, 2003) process updates in I/Os total, i.e. amortized each, far less than one I/O per update.
Test yourself
What does the DAM model count?
- CPU instructions
- Block transfers between a cache of words and slow memory, in blocks of words
- Comparisons
- Cache hits
Which is the external-memory sorting bound of Aggarwal and Vitter?
Why does a binary search on a sorted array cost about I/Os with a cold cache, not ?
- Because the array is cached
- Because the last steps of the search fall inside a single block
- Because binary search is cache-oblivious
- Because divides