Sorting in External Memory
In the DAM model, sorting items costs
and that bound is tight for comparison-based algorithms (Aggarwal and Vitter, 1988). This lesson proves the upper bound with multiway merge sort, measures it, and sketches the counting argument behind the lower bound. The lesson Merge Sort of Part I is the starting point; only the fan-in changes.
Multiway merge sort
- Run formation. Read items at a time (fill the cache), sort them in memory (free in the model), write them out as a sorted run. That makes runs in I/Os: every block is read once and written once.
- Merge passes. Merge runs at a time into one. The cache holds one block of each input run plus one output block, so can be as large as . A merge of runs with items in total reads and writes each of their blocks once, I/Os, so each pass costs and divides the number of runs by .
With the number of passes is , and the total is
since . Two-way merge sort () needs passes instead: the base of the logarithm is the whole improvement.
EXTERNAL-MERGE-SORT(file, M, B)
1 runs = []
2 for each chunk of M consecutive items // run formation: 2N/B I/Os
3 read the chunk, sort it in memory, write it as a run
4 k = M/B - 1
5 while there is more than one run // each pass: 2N/B I/Os
6 replace each group of k runs by their k-way merge
7 (one buffer block per input run, one for the output, a heap over the run heads)The program implements it with explicit I/O accounting and compares fan-ins on items with and .
import heapq, math, random
def external_merge_sort(data, M, B, fan_in):
"""Multiway merge sort with explicit I/O accounting: every block read or written costs 1."""
ios = 0
blocks = lambda n: -(-n // B) # ceil(n / B)
runs = []
for i in range(0, len(data), M): # pass 0: sort memory-sized chunks into runs
chunk = sorted(data[i:i + M])
ios += 2 * blocks(len(chunk)) # read the chunk, write the run
runs.append(chunk)
passes = 0
while len(runs) > 1: # merge passes: fan_in runs at a time
passes += 1
merged = []
for i in range(0, len(runs), fan_in):
group = runs[i:i + fan_in]
out = list(heapq.merge(*group)) # one input block per run + one output block in memory
ios += sum(blocks(len(r)) for r in group) + blocks(len(out))
merged.append(out)
runs = merged
return runs[0], passes, ios
rng = random.Random(1988)
N, M, B = 1 << 17, 1 << 12, 1 << 6
data = [rng.getrandbits(32) for _ in range(N)]
print(f"N = {N}, M = {M}, B = {B}: N/B = {N // B} blocks, M/B = {M // B} blocks of cache, {N // M} initial runs")
for fan_in in [2, 4, 16, M // B - 1]:
out, passes, ios = external_merge_sort(data, M, B, fan_in)
assert out == sorted(data)
predicted = 2 * (N // B) * (1 + math.ceil(math.log(N / M, fan_in) - 1e-9))
print(f"fan-in {fan_in:2}: {passes} merge passes, {ios:6} I/Os (2N/B (1 + ceil(log_k(N/M))) = {predicted})")N = 131072, M = 4096, B = 64: N/B = 2048 blocks, M/B = 64 blocks of cache, 32 initial runs
fan-in 2: 5 merge passes, 24576 I/Os (2N/B (1 + ceil(log_k(N/M))) = 24576)
fan-in 4: 3 merge passes, 16384 I/Os (2N/B (1 + ceil(log_k(N/M))) = 16384)
fan-in 16: 2 merge passes, 12288 I/Os (2N/B (1 + ceil(log_k(N/M))) = 12288)
fan-in 63: 1 merge passes, 8192 I/Os (2N/B (1 + ceil(log_k(N/M))) = 8192)
The count matches the formula exactly. With fan-in , the 32 runs merge in a single pass: the whole sort costs two reads and two writes of every block, 4 scans of the data. Two-way merging needs 12.
In C++
The same algorithm on a million 32-bit keys with and , a binary heap of run heads doing the 63-way merge, I/Os counted block by block.
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <functional>
#include <queue>
#include <random>
#include <tuple>
#include <vector>
using Run = std::vector<std::uint32_t>;
// k-way merge with a min-heap of (value, run, position); I/Os counted per block of B words.
Run merge_runs(const std::vector<Run>& runs, std::size_t B, long& ios) {
using Item = std::tuple<std::uint32_t, std::size_t, std::size_t>;
std::priority_queue<Item, std::vector<Item>, std::greater<>> heap;
std::size_t total = 0;
for (std::size_t r = 0; r < runs.size(); ++r) {
total += runs[r].size();
if (!runs[r].empty()) { heap.emplace(runs[r][0], r, 0); ++ios; } // first block of each run
}
Run out;
out.reserve(total);
while (!heap.empty()) {
auto [v, r, i] = heap.top();
heap.pop();
out.push_back(v);
if (out.size() % B == 0) ++ios; // an output block is full
if (++i < runs[r].size()) {
if (i % B == 0) ++ios; // next input block of run r
heap.emplace(runs[r][i], r, i);
}
}
if (out.size() % B) ++ios; // last partial block
return out;
}
int main() {
const std::size_t N = 1 << 20, M = 1 << 15, B = 1 << 9; // M/B = 64 blocks of cache
std::mt19937 rng(1988);
std::vector<std::uint32_t> data(N);
for (auto& x : data) x = rng();
long ios = 0;
std::vector<Run> runs;
for (std::size_t i = 0; i < N; i += M) { // run formation: read, sort, write
Run chunk(data.begin() + i, data.begin() + i + M);
std::sort(chunk.begin(), chunk.end());
ios += 2 * (M / B);
runs.push_back(std::move(chunk));
}
std::size_t fan_in = M / B - 1, passes = 0;
while (runs.size() > 1) {
++passes;
std::vector<Run> next;
for (std::size_t i = 0; i < runs.size(); i += fan_in) {
std::vector<Run> group(runs.begin() + i, runs.begin() + std::min(runs.size(), i + fan_in));
next.push_back(merge_runs(group, B, ios));
}
runs.swap(next);
}
std::sort(data.begin(), data.end());
std::printf("N = %zu, %zu runs of M = %zu, fan-in %zu: %zu merge passes, %ld I/Os (N/B = %zu)\n",
N, N / M, M, fan_in, passes, ios, N / B);
std::printf("sorted correctly: %s\n", runs[0] == data ? "yes" : "no");
}N = 1048576, 32 runs of M = 32768, fan-in 63: 1 merge passes, 8192 I/Os (N/B = 2048)
sorted correctly: yes
The lower bound (sketch)
Why can no comparison-based algorithm do better? Aggarwal and Vitter's argument counts information.
Proof sketch
Initially all orderings of the input are possible. The algorithm learns about the order only by comparing items in the cache. When a block of items is read into a cache that already holds other items, comparisons can at most determine how the new items interleave with the old ones, possibilities, and, the first time that block is ever read, the order of its own items, possibilities. So after I/Os the number of orderings distinguished is at most
Sorting requires distinguishing all orderings. Taking logarithms, with , and :
Every algorithm also has to read the input, . The argument extends to permuting (where the comparisons are replaced by counting how many permutations the I/Os can produce), which gives the bound.
The program evaluates the counting bound exactly (with the logarithms of factorials and binomials) and sets it against the merge sort count.
import math
# Aggarwal-Vitter counting argument: each I/O can increase the number of orderings consistent
# with what has been seen by at most a factor C(M, B) * B!, (and B! only the first time a block is read).
def lower_bound_ios(N, M, B):
lg_fact = lambda n: math.lgamma(n + 1) / math.log(2)
need = lg_fact(N) # lg N! bits of information
per_io = math.log2(math.comb(M, B)) # what one read of a block can reveal
first = (N / B) * lg_fact(B) # each block's internal order, once
return max(N / B, (need - first) / per_io)
for N, M, B in [(2 ** 20, 2 ** 12, 2 ** 6), (2 ** 30, 2 ** 20, 2 ** 10)]:
ub = 2 * (N / B) * (1 + math.ceil(math.log(N / M, M // B - 1)))
print(f"N = 2^{int(math.log2(N))}, M = 2^{int(math.log2(M))}, B = 2^{int(math.log2(B))}: "
f"lower bound {lower_bound_ios(N, M, B):12.0f} I/Os, merge sort {ub:12.0f}, N/B {N // B}")N = 2^20, M = 2^12, B = 2^6: lower bound 30998 I/Os, merge sort 98304, N/B 16384
N = 2^30, M = 2^20, B = 2^10: lower bound 1833279 I/Os, merge sort 6291456, N/B 1048576
Multiway merge sort is within a factor of about 3 of the lower bound, for both small and disk-sized parameters; part of the gap is the factor 2 for writing, which the read-only counting argument ignores.
Where the formula comes from, in one example
Take items, and , so blocks and blocks of cache. Run formation produces runs at a cost of I/Os. One merge pass with fan-in up to merges all 64 runs, another I/Os. The total, I/Os, is four scans of the data. Two-way merge sort would need merge passes, 14 scans. And : the asymptotic formula hides the constant 2 for reading and writing and the rounding up of the logarithm, but it predicts the number of passes correctly. On real hardware the logarithm is almost always 1 or 2, which is why external sorting is "a few scans" in practice.
In practice
- Database systems and big-data frameworks sort with exactly this scheme ("external merge sort"), usually with replacement selection for run formation, which produces runs of about on random input.
- On SSDs and in main memory the same reasoning applies with = a page or a cache line; GNU
sorton large files spills sorted runs to temporary files and merges many at once. - The cache-oblivious counterpart, funnelsort, achieves the same bound without knowing and .
Test yourself
What limits the fan-in of a merge pass in external memory?
- The number of runs
- The cache: one block per input run plus one output block must fit, so
- The disk size
- Nothing; any fan-in works
How many I/Os does one merge pass over items cost?
- : every block read once and written once
With runs and , how many merge passes does multiway merge sort need?
- 1
- 5
- 6
- 32