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 with error parameter is mergeable if there is an algorithm that takes and for two data sets, both built with parameter , and outputs a summary of (multiset union) that
- has the same size bound as a summary built directly, and
- has the same error guarantee , 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: |
| HyperLogLog | register-wise maximum | each register is a maximum over the items routed to it |
| minimum values | keep the smallest hash values of the union | the smallest of a union are among the smallest of each part |
| keyed reservoir | keep the 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.
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 counters each, built from streams of lengths and , can hold up to distinct items. Adding them gives a valid summary with too many counters. The merge then cancels in bulk, exactly as a decrement step cancels distinct items:
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 be the result of any tree of merges over summaries of streams with total length , and let be the sum of the counts in . Then for every item : the same guarantee as one pass over the concatenated stream.
Proof. Use the invariant " and ", where is the summary's total count. It holds for every summary built by single-stream updates (Misra-Gries). Suppose it holds for and , with totals and . Adding (line 1) keeps and gives error at most , with total . In line 4 every estimate drops by at most , while the total drops by at least : the largest counts each lose exactly . So the error grows by at most and the term grows by at least . The invariant survives, and by induction it holds for any merge tree.
The size bound is clear: after line 4 only the items whose count exceeded the -th largest remain, at most . The program splits a Zipf stream of 96 000 items over 16 machines, summarizes each shard with , merges the 16 summaries in a binary tree and compares the result with one pass over the whole stream.
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 -th largest count in linear time. Eight shards of a skewed stream are merged one after another (a chain, the deepest possible merge tree).
#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 for rank error with probability , and a variant of it reaches the optimal . 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 from streams of lengths and still merge: draw from the hypergeometric distribution (how many of positions drawn without replacement from fall among the first ), then take random members of the first reservoir and of the second.
Test yourself
What does mergeability require beyond 'the summary of a union can be computed from the summaries of the parts'?
- Nothing
- The merged summary keeps the same size bound and the same error guarantee, however many merges are done and in whatever tree
- The merge must be linear
- The parts must have the same size
In the Misra-Gries merge, why does subtracting the -th largest count keep the error bound ?
- Because is small
- Because each estimate drops by at most while the total drops by at least , so the bound grows at least as much as the error
- Because only items are affected
- Because the parts are disjoint
How are two HyperLogLog sketches with the same hash function merged?
- Add the registers
- Take the register-wise maximum
- Average the estimates
- Keep the sketch with the larger estimate