TExcelTAD

Mergeable Summaries

Large data is rarely in one stream. Logs are written by thousands of servers, a distributed database stores a table in shards, and a monitoring system aggregates per-minute summaries into hours and days. What is needed is a summary that can be computed separately on each part and then combined, with an error guarantee for the combination that is as good as if one machine had seen everything. Agarwal, Cormode, Huang, Phillips, Wei and Yi (2012) called such summaries mergeable and showed, surprisingly, that Misra-Gries is one of them, although its update rule looks inherently sequential.

Definition

A summary S(⋅)S(\cdot) with error parameter ε\varepsilon is mergeable if there is an algorithm that takes S(D1)S(D_1) and S(D2)S(D_2) for two data sets, both built with parameter ε\varepsilon, and outputs a summary of D1∪D2D_1 \cup D_2 (multiset union) that

  1. has the same size bound as a summary built directly, and
  2. has the same error guarantee ε\varepsilon, however many merges were applied and in whatever tree shape.

The second condition is the hard one. A naive merge that adds a little error each time would degrade with the depth of the merge tree; mergeability forbids that. Merges in a tree are the general case: a single stream is the special case where each merge combines a summary with a summary of a single item.

Linear sketches and other easy cases

Several summaries of the course merge exactly: merging the sketches gives the very sketch that the union would have produced.

Summary Merge Why exact
count-min, Count-Sketch, AMS add the arrays entry by entry linear sketches: Af+Ag=A(f+g)Af + Ag = A(f + g)
HyperLogLog register-wise maximum each register is a maximum over the items routed to it
kk minimum values keep the kk smallest hash values of the union the kk smallest of a union are among the kk smallest of each part
keyed reservoir keep the kk smallest keys of the union same reason, with random keys per item (Reservoir Sampling)

All four need the parts to share their randomness: the same hash functions, or keys drawn once per item. The program checks the equality claim for each, on two streams that overlap in part of the universe.

python · try it yourself
import heapq, random

MASK = (1 << 64) - 1
def mix64(x):
    x = (x + 0x9E3779B97F4A7C15) & MASK
    x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
    x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
    return x ^ (x >> 31)

def count_min(stream, d=4, w=64):
    C = [[0] * w for _ in range(d)]
    for x in stream:
        for j in range(d):
            C[j][mix64(x * 4 + j) % w] += 1
    return C
def cm_merge(A, B):
    return [[a + b for a, b in zip(ra, rb)] for ra, rb in zip(A, B)]

def hll(stream, p=6):
    M = [0] * (1 << p)
    for x in stream:
        h = mix64(x)
        j, rest = h >> (64 - p), h & ((1 << (64 - p)) - 1)
        M[j] = max(M[j], 64 - p - rest.bit_length() + 1)
    return M
def hll_merge(A, B):
    return [max(a, b) for a, b in zip(A, B)]

def kmv(stream, k=32):
    return sorted(set(mix64(x) for x in stream))[:k]          # a real stream keeps a heap
def kmv_merge(A, B, k=32):
    return sorted(set(A) | set(B))[:k]

def reservoir(keyed, k=5):                                    # keep the k smallest keys
    return heapq.nsmallest(k, keyed)
def res_merge(A, B, k=5):
    return heapq.nsmallest(k, A + B)

rng = random.Random(3)
A = [rng.randrange(5000) for _ in range(20000)]
B = [rng.randrange(3000, 9000) for _ in range(30000)]
keysA = [(rng.random(), ("A", t)) for t in range(len(A))]
keysB = [(rng.random(), ("B", t)) for t in range(len(B))]
checks = [
    ("count-min (add arrays)", cm_merge(count_min(A), count_min(B)) == count_min(A + B)),
    ("HyperLogLog (register max)", hll_merge(hll(A), hll(B)) == hll(A + B)),
    ("k minimum values (k smallest of union)", kmv_merge(kmv(A), kmv(B)) == kmv(A + B)),
    ("keyed reservoir (k smallest keys)", res_merge(reservoir(keysA), reservoir(keysB)) == reservoir(keysA + keysB)),
]
for name, ok in checks:
    print(f"merge(sketch(A), sketch(B)) == sketch(A + B) for {name}: {ok}")
merge(sketch(A), sketch(B)) == sketch(A + B) for count-min (add arrays): True
merge(sketch(A), sketch(B)) == sketch(A + B) for HyperLogLog (register max): True
merge(sketch(A), sketch(B)) == sketch(A + B) for k minimum values (k smallest of union): True
merge(sketch(A), sketch(B)) == sketch(A + B) for keyed reservoir (k smallest keys): True

Merging Misra-Gries summaries

Two Misra-Gries summaries with k−1k - 1 counters each, built from streams of lengths m1m_1 and m2m_2, can hold up to 2(k−1)2(k-1) distinct items. Adding them gives a valid summary with too many counters. The merge then cancels in bulk, exactly as a decrement step cancels kk distinct items:

text
Merge of two Misra-Gries summaries (Agarwal et al., 2012)
1  S ← C1 + C2                         (add the counts of equal items)
2  if S has at most k − 1 items: return S
3  c ← the k-th largest count in S
4  subtract c from every count; drop the items whose count is now ≤ 0
5  return S                            (at most k − 1 items remain)

Theorem (Agarwal et al., 2012). Let CC be the result of any tree of merges over summaries of streams with total length mm, and let m′m' be the sum of the counts in CC. Then fx−m−m′k≤f^x≤fxf_x - \frac{m - m'}{k} \le \hat f_x \le f_x for every item xx: the same guarantee as one pass over the concatenated stream.

Proof. Use the invariant "f^x≤fx\hat f_x \le f_x and fx−f^x≤(m−m′)/kf_x - \hat f_x \le (m - m')/k", where m′m' is the summary's total count. It holds for every summary built by single-stream updates (Misra-Gries). Suppose it holds for C1C_1 and C2C_2, with totals m1′m_1' and m2′m_2'. Adding (line 1) keeps f^x≤fx\hat f_x \le f_x and gives error at most m1−m1′k+m2−m2′k\frac{m_1 - m_1'}{k} + \frac{m_2 - m_2'}{k}, with total m1′+m2′m_1' + m_2'. In line 4 every estimate drops by at most cc, while the total drops by at least kckc: the kk largest counts each lose exactly cc. So the error grows by at most cc and the term (m−m′)/k(m - m')/k grows by at least kc/k=ckc/k = c. The invariant survives, and by induction it holds for any merge tree. □\square

The size bound is clear: after line 4 only the items whose count exceeded the kk-th largest remain, at most k−1k - 1. The program splits a Zipf stream of 96 000 items over 16 machines, summarizes each shard with k=40k = 40, merges the 16 summaries in a binary tree and compares the result with one pass over the whole stream.

python · try it yourself
import random
from collections import Counter

def mg_build(stream, k):
    C = {}
    for x in stream:
        if x in C:
            C[x] += 1
        elif len(C) < k - 1:
            C[x] = 1
        else:
            for y in list(C):
                C[y] -= 1
                if C[y] == 0:
                    del C[y]
    return C

def mg_merge(A, B, k):
    """Add the counters, then subtract the k-th largest count and keep what stays positive."""
    S = Counter(A)
    S.update(B)
    if len(S) < k:
        return dict(S)
    ck = sorted(S.values(), reverse=True)[k - 1]
    return {x: c - ck for x, c in S.items() if c > ck}

rng = random.Random(2012)
U = 30000
cum, s = [], 0.0
for i in range(U):
    s += 1 / (i + 1) ** 1.2
    cum.append(s)
stream = rng.choices(range(U), cum_weights=cum, k=96000)
true = Counter(stream)
m, k = len(stream), 40

shards = [stream[i * 6000:(i + 1) * 6000] for i in range(16)]    # 16 machines
level = [mg_build(sh, k) for sh in shards]
merges = 0
while len(level) > 1:                                             # merge in a binary tree
    level = [mg_merge(level[i], level[i + 1], k) for i in range(0, len(level), 2)]
    merges += len(level)
merged = level[0]
single = mg_build(stream, k)
for name, C in [("one pass", single), (f"16 shards, {merges} merges", merged)]:
    worst = max(true[x] - C.get(x, 0) for x in true)
    over = max(C.get(x, 0) - true[x] for x in true)
    bound = (m - sum(C.values())) / k
    print(f"{name:24} counters {len(C):2}  worst undercount {worst:5}  bound (m - m')/k {bound:7.1f}  overcount {over}")
print("top 5 true:  ", [x for x, _ in true.most_common(5)])
print("top 5 merged:", sorted(merged, key=merged.get, reverse=True)[:5])
one pass                 counters 28  worst undercount  1585  bound (m - m')/k  1585.0  overcount 0
16 shards, 15 merges     counters 36  worst undercount  1577  bound (m - m')/k  1577.4  overcount 0
top 5 true:   [0, 1, 2, 3, 4]
top 5 merged: [0, 1, 2, 3, 4]

The merged summary is as accurate as the one-pass summary, and both come within one unit of the bound on their worst item. No error accumulated over four levels of merging, which is the point of the theorem.

In C++

The merge as a function on std::unordered_map summaries, with std::nth_element to find the kk-th largest count in linear time. Eight shards of a skewed stream are merged one after another (a chain, the deepest possible merge tree).

cpp · try it yourself
#include <algorithm>
#include <bit>
#include <cstdint>
#include <cstdio>
#include <functional>
#include <random>
#include <unordered_map>
#include <vector>

using Summary = std::unordered_map<std::uint64_t, std::int64_t>;

void mg_add(Summary& C, std::uint64_t x, std::size_t k) {
    if (auto it = C.find(x); it != C.end()) { ++it->second; return; }
    if (C.size() < k - 1) { C.emplace(x, 1); return; }
    for (auto it = C.begin(); it != C.end();) if (--it->second == 0) it = C.erase(it); else ++it;
}

Summary mg_merge(const Summary& A, const Summary& B, std::size_t k) {
    Summary S = A;
    for (auto& [x, c] : B) S[x] += c;
    if (S.size() < k) return S;
    std::vector<std::int64_t> counts;
    for (auto& [x, c] : S) counts.push_back(c);
    std::nth_element(counts.begin(), counts.begin() + (k - 1), counts.end(), std::greater<>());
    std::int64_t ck = counts[k - 1];                     // the k-th largest count
    Summary out;
    for (auto& [x, c] : S) if (c > ck) out.emplace(x, c - ck);
    return out;
}

int main() {
    std::mt19937_64 rng(2012);
    const std::size_t k = 16, shards = 8, per = 125000;
    std::unordered_map<std::uint64_t, std::int64_t> exact;
    Summary acc;
    for (std::size_t s = 0; s < shards; ++s) {
        Summary C;
        for (std::size_t t = 0; t < per; ++t) {
            std::uint64_t r = rng();
            std::uint64_t x = (r & 1) ? std::countr_zero(r >> 1) : (r >> 8) % 50000;
            mg_add(C, x, k);
            ++exact[x];
        }
        acc = mg_merge(acc, C, k);
    }
    std::int64_t total = 0, worst = 0;
    for (auto& [x, c] : acc) total += c;
    for (auto& [x, f] : exact) worst = std::max(worst, f - (acc.count(x) ? acc.at(x) : 0));
    const std::int64_t m = shards * per;
    std::printf("m = %lld, k = %zu, %zu counters after %zu merges\n", (long long)m, k, acc.size(), shards);
    std::printf("worst undercount %lld <= (m - m')/k = %.1f\n", (long long)worst, double(m - total) / k);
}
m = 1000000, k = 16, 6 counters after 8 merges
worst undercount 43273 <= (m - m')/k = 43274.9

Beyond Misra-Gries

  • Space-Saving is mergeable through its equivalence with Misra-Gries (Space-Saving).
  • Quantile summaries (the GK summary of Greenwald and Khanna, 2001) are not known to be mergeable with the same space; Agarwal et al. gave a randomized mergeable quantile summary, and the later KLL sketch (Karnin, Lang and Liberty, 2016) is mergeable with space O(1εlog⁡2log⁡1δ)O(\frac{1}{\varepsilon}\log^2\log\frac{1}{\delta}) for rank error εm\varepsilon m with probability 1−δ1 - \delta, and a variant of it reaches the optimal O(1εlog⁡log⁡1δ)O(\frac{1}{\varepsilon}\log\log\frac{1}{\delta}). The course does not cover quantiles in detail.
  • Samples: a uniform sample without replacement merges through keys, as above. Without stored keys, two reservoirs of size kk from streams of lengths m1m_1 and m2m_2 still merge: draw XX from the hypergeometric distribution (how many of kk positions drawn without replacement from m1+m2m_1 + m_2 fall among the first m1m_1), then take XX random members of the first reservoir and k−Xk - X of the second.

Test yourself

What does mergeability require beyond 'the summary of a union can be computed from the summaries of the parts'?

  1. Nothing
  2. The merged summary keeps the same size bound and the same error guarantee, however many merges are done and in whatever tree
  3. The merge must be linear
  4. The parts must have the same size

In the Misra-Gries merge, why does subtracting the kk-th largest count cc keep the error bound (m−m′)/k(m - m')/k?

  1. Because cc is small
  2. Because each estimate drops by at most cc while the total m′m' drops by at least kckc, so the bound grows at least as much as the error
  3. Because only kk items are affected
  4. Because the parts are disjoint

How are two HyperLogLog sketches with the same hash function merged?

  1. Add the registers
  2. Take the register-wise maximum
  3. Average the estimates
  4. Keep the sketch with the larger estimate