TExcelTAD
Home › Advanced & Succinct Data Structures › Sorting in External Memory

Sorting in External Memory

In the DAM model, sorting NN items costs

sort⁡(N)=Θ ⁣(NBlog⁡M/BNB) I/Os\operatorname{sort}(N) = \Theta\!\left(\frac{N}{B} \log_{M/B} \frac{N}{B}\right) \text{ I/Os}

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

  1. Run formation. Read MM items at a time (fill the cache), sort them in memory (free in the model), write them out as a sorted run. That makes N/MN/M runs in 2N/B2N/B I/Os: every block is read once and written once.
  2. Merge passes. Merge kk runs at a time into one. The cache holds one block of each input run plus one output block, so kk can be as large as M/B−1M/B - 1. A merge of runs with N′N' items in total reads and writes each of their blocks once, 2N′/B2N'/B I/Os, so each pass costs 2N/B2N/B and divides the number of runs by kk.

With k=M/B−1=Θ(M/B)k = M/B - 1 = \Theta(M/B) the number of passes is ⌈log⁡k(N/M)⌉\lceil \log_{k} (N/M) \rceil, and the total is

2NB(1+⌈log⁡M/B−1NM⌉)=O ⁣(NBlog⁡M/BNB)\frac{2N}{B}\left(1 + \left\lceil \log_{M/B - 1} \frac{N}{M} \right\rceil\right) = O\!\left(\frac{N}{B} \log_{M/B} \frac{N}{B}\right)

since log⁡M/B(N/M)=log⁡M/B(N/B)−1\log_{M/B} (N/M) = \log_{M/B} (N/B) - 1. Two-way merge sort (k=2k = 2) needs log⁡2(N/M)\log_2 (N/M) passes instead: the base of the logarithm is the whole improvement.

text
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 2172^{17} items with M=212M = 2^{12} and B=26B = 2^6.

python · try it yourself
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 M/B−1=63M/B - 1 = 63, 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 M=215M = 2^{15} and B=29B = 2^9, a binary heap of run heads doing the 63-way merge, I/Os counted block by block.

cpp · try it yourself
#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 N!N! orderings of the input are possible. The algorithm learns about the order only by comparing items in the cache. When a block of BB items is read into a cache that already holds M−BM - B other items, comparisons can at most determine how the new BB items interleave with the M−BM - B old ones, (MB)\binom{M}{B} possibilities, and, the first time that block is ever read, the order of its own BB items, B!B! possibilities. So after tt I/Os the number of orderings distinguished is at most

(B!)N/B(MB)t(B!)^{N/B} \binom{M}{B}^{t}

Sorting requires distinguishing all N!N! orderings. Taking logarithms, with lg⁡N!≈Nlg⁡N\lg N! \approx N \lg N, lg⁡(B!)N/B≈Nlg⁡B\lg (B!)^{N/B} \approx N \lg B and lg⁡(MB)≈Blg⁡(M/B)\lg \binom{M}{B} \approx B \lg (M/B):

t≥Nlg⁡(N/B)Blg⁡(M/B)⋅(1−o(1))=Ω ⁣(NBlog⁡M/BNB)t \ge \frac{N \lg (N/B)}{B \lg (M/B)} \cdot (1 - o(1)) = \Omega\!\left(\frac{N}{B} \log_{M/B} \frac{N}{B}\right)

Every algorithm also has to read the input, t≥N/Bt \ge N/B. The argument extends to permuting (where the comparisons are replaced by counting how many permutations the I/Os can produce), which gives the min⁡(N,sort⁡(N))\min(N, \operatorname{sort}(N)) bound.

The program evaluates the counting bound exactly (with the logarithms of factorials and binomials) and sets it against the merge sort count.

python · try it yourself
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 N=230N = 2^{30} items, M=224M = 2^{24} and B=212B = 2^{12}, so N/B=218N/B = 2^{18} blocks and M/B=212M/B = 2^{12} blocks of cache. Run formation produces N/M=64N/M = 64 runs at a cost of 2⋅2182 \cdot 2^{18} I/Os. One merge pass with fan-in up to 40954095 merges all 64 runs, another 2⋅2182 \cdot 2^{18} I/Os. The total, 2202^{20} I/Os, is four scans of the data. Two-way merge sort would need lg⁡64=6\lg 64 = 6 merge passes, 14 scans. And NBlog⁡M/BNB=218⋅1812=1.5⋅218\frac{N}{B} \log_{M/B} \frac{N}{B} = 2^{18} \cdot \frac{18}{12} = 1.5 \cdot 2^{18}: 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 2M2M on random input.
  • On SSDs and in main memory the same reasoning applies with BB = a page or a cache line; GNU sort on large files spills sorted runs to temporary files and merges many at once.
  • The cache-oblivious counterpart, funnelsort, achieves the same bound without knowing MM and BB.

Test yourself

What limits the fan-in of a merge pass in external memory?

  1. The number of runs
  2. The cache: one block per input run plus one output block must fit, so k≤M/B−1k \le M/B - 1
  3. The disk size
  4. Nothing; any fan-in works

How many I/Os does one merge pass over NN items cost?

  1. NN
  2. 2N/B2N/B: every block read once and written once
  3. N/B⋅lg⁡NN/B \cdot \lg N
  4. M/BM/B

With N/M=32N/M = 32 runs and M/B=64M/B = 64, how many merge passes does multiway merge sort need?

  1. 1
  2. 5
  3. 6
  4. 32