TExcelTAD
Home › Advanced & Succinct Data Structures › The External-Memory (DAM) Model

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 MM words and an unbounded slow memory (disk), both divided into blocks of BB words. So the cache holds M/BM / B 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: M≥2BM \ge 2B at least, often the tall-cache assumption M=Ω(B2)M = \Omega(B^2), which holds for real caches (a 32 KiB L1 cache with 64-byte lines has M/B=512M/B = 512 lines, much more than B=8B = 8 words).

The basic bounds

Task I/Os Compare with RAM
scan NN consecutive words scan⁡(N)=Θ(⌈N/B⌉)\operatorname{scan}(N) = \Theta(\lceil N / B \rceil) Θ(N)\Theta(N)
search a sorted array by binary search Θ(lg⁡(N/B))\Theta(\lg (N / B)) Θ(lg⁡N)\Theta(\lg N)
search a B-tree Θ(log⁡BN)\Theta(\log_B N), optimal for comparison-based search Θ(lg⁡N)\Theta(\lg N)
sort NN items sort⁡(N)=Θ ⁣(NBlog⁡M/BNB)\operatorname{sort}(N) = \Theta\!\left(\frac{N}{B} \log_{M/B} \frac{N}{B}\right) Θ(Nlg⁡N)\Theta(N \lg N)
permute NN items (a given permutation) Θ(min⁡(N,sort⁡(N)))\Theta(\min(N, \operatorname{sort}(N))) Θ(N)\Theta(N)

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 Θ(sort⁡(N))\Theta(\operatorname{sort}(N)). 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 M/BM/B 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 N=216N = 2^{16} words with B=64B = 64 and M=4096M = 4096.

python · try it yourself
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 N/BN/B I/Os, 64 times fewer than random accesses. The binary searches cost about 5.5 I/Os each instead of lg⁡(N/B)=10\lg(N/B) = 10, 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 lg⁡(N/B)\lg(N/B): the last lg⁡B\lg B steps stay inside one block, the first lg⁡(N/B)\lg(N/B) each touch a new one.

Why sorting is not N/BN/B

Sorting needs more than a scan, and the bound has an unusual shape. Two remarks explain it:

  1. The base of the logarithm. Merge sort in the DAM model merges M/BM/B sorted runs at once (one block of each run fits in the cache), so each pass reduces the number of runs by a factor M/BM/B, and each pass is a scan. That gives NBlog⁡M/BNB\frac{N}{B} \log_{M/B} \frac{N}{B}.
  2. Permuting is almost as hard as sorting. Moving item ii to position π(i)\pi(i) by direct writes costs up to one I/O per item. When sort⁡(N)<N\operatorname{sort}(N) < N, 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.
python · try it yourself
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, M/BM/B in the thousands) the logarithm is 1 or 2: sorting costs a couple of scans, far below the NN 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 1/B1/B I/O per element.
  • Merge many streams at once. The fan-in of a merge can be M/BM/B, not 2.
  • Use the fan-out BB. Search trees should branch Θ(B)\Theta(B) ways per node: B-trees revisited.
  • Batch updates. Buffer trees (Arge, 2003) process NN updates in O(sort⁡(N))O(\operatorname{sort}(N)) I/Os total, i.e. O(1Blog⁡M/BNB)O(\frac{1}{B} \log_{M/B} \frac{N}{B}) amortized each, far less than one I/O per update.

Test yourself

What does the DAM model count?

  1. CPU instructions
  2. Block transfers between a cache of MM words and slow memory, in blocks of BB words
  3. Comparisons
  4. Cache hits

Which is the external-memory sorting bound of Aggarwal and Vitter?

  1. Θ(Nlg⁡N)\Theta(N \lg N)
  2. Θ(NBlog⁡M/BNB)\Theta(\frac{N}{B} \log_{M/B} \frac{N}{B})
  3. Θ(N/B)\Theta(N / B)
  4. Θ(NBlg⁡N)\Theta(\frac{N}{B} \lg N)

Why does a binary search on a sorted array cost about lg⁡(N/B)\lg(N/B) I/Os with a cold cache, not lg⁡N\lg N?

  1. Because the array is cached
  2. Because the last lg⁡B\lg B steps of the search fall inside a single block
  3. Because binary search is cache-oblivious
  4. Because BB divides NN