Flajolet-Martin and k Minimum Values
Counting distinct items, , is the most requested streaming statistic: unique visitors, distinct source addresses, the number of different values in a database column (which a query optimizer needs to choose a plan). Exactly, it takes bits. Approximately, it takes almost nothing, thanks to one observation of Flajolet and Martin (1985): hash every item to a random-looking number, and look at the extremes of the hash values. Duplicates hash to the same value, so they change nothing, and the extremes of uniform random values reveal . This lesson develops the idea in two forms: the bit-pattern estimators (Flajolet-Martin, and its refinement HyperLogLog in the next lesson) and the order-statistic estimator, minimum values.
The bit-pattern idea
Let map items to uniformly random 64-bit words. A hash value ends in at least zero bits with probability . Among distinct items, the largest number of trailing zeros is therefore around : if it is unlikely that any item reaches zeros, and if it is very likely that some item does.
Theorem (after Alon, Matias and Szegedy, 1996). Let be drawn from a pairwise independent family, the largest number of trailing zeros of over the stream, and . For every ,
Proof
For each , let be the number of distinct items whose hash has at least trailing zeros, a sum of pairwise independent indicators with probability . So and .
Overestimate. Let be the smallest integer with . Then requires , that is , and by Markov .
Underestimate. Let be the largest integer with . Then requires , that is , and by Chebyshev .
Together the failure probability is at most . (Alon, Matias and Szegedy state the bound for their variant of the estimator.)
One estimator gives only a constant-factor approximation. Flajolet and Martin's original algorithm, PCSA (probabilistic counting with stochastic averaging), sharpens it without hashing each item many times: the hash splits the stream into substreams, each keeps a bitmap of the trailing-zero counts it has seen, is the position of the lowest unset bit of bitmap , and
with a relative standard error of about (Flajolet and Martin, 1985; the constant corrects a bias found by their analysis, which assumes an ideal hash function and is stated here).
import math
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 tz(h): # number of trailing zero bits (64 for h = 0)
return (h & -h).bit_length() - 1 if h else 64
def ams_fm(stream, salt):
"""Alon-Matias-Szegedy version of Flajolet-Martin: 2^(z + 1/2), z = max trailing zeros."""
z = 0
for x in stream:
z = max(z, tz(mix64(x ^ salt)))
return 2 ** (z + 0.5)
def pcsa(stream, salt, m=64):
"""Flajolet-Martin with stochastic averaging: m bitmaps, R_j = lowest bit not set."""
maps = [0] * m
for x in stream:
h = mix64(x ^ salt)
maps[h % m] |= 1 << tz(h // m)
R = [tz(~b) for b in maps] # position of the lowest 0 bit
return m / 0.77351 * 2 ** (sum(R) / m)
n = 2000
stream = [i * 7919 % 100003 for i in range(n)] * 2 # 2000 distinct items, each twice
ratios = sorted(ams_fm(stream, s * 0x9E3779B97F4A7C15 & MASK) / n for s in range(200))
for c in [3, 4, 8]:
inside = sum(1 / c <= r <= c for r in ratios) / len(ratios)
print(f"single estimator within a factor {c} of n: {inside:.0%} of 200 hash functions (bound: >= {1 - 2 * math.sqrt(2) / c:.0%})")
errs = [pcsa(stream, s * 0x9E3779B97F4A7C15 & MASK) / n - 1 for s in range(20)]
print(f"PCSA with 64 bitmaps, 20 hash functions: mean relative error {sum(errs) / 20:+.3f}, "
f"rms {math.sqrt(sum(e * e for e in errs) / 20):.3f} (theory about 0.78/sqrt(64) = {0.78 / 8:.3f})")single estimator within a factor 3 of n: 72% of 200 hash functions (bound: >= 6%)
single estimator within a factor 4 of n: 72% of 200 hash functions (bound: >= 29%)
single estimator within a factor 8 of n: 88% of 200 hash functions (bound: >= 65%)
PCSA with 64 bitmaps, 20 hash functions: mean relative error -0.024, rms 0.093 (theory about 0.78/sqrt(64) = 0.098)
The single estimator is a coarse thing: the AMS guarantee holds, but a factor of 3 is the realistic accuracy. Averaging over 64 bitmaps brings the error to about 10%, matching .
minimum values
The order-statistic view is simpler to analyse. Map every item to uniform in and keep the smallest distinct hash values; let be the largest of them. If points are thrown uniformly into , the -th smallest is around , so .
k minimum values (KMV)
1 S ← empty (holds at most k distinct hash values)
2 for each item x:
3 v ← h(x)
4 if v ∉ S and (|S| < k or v < max S): insert v, and if |S| > k remove max S
5 estimate: if |S| < k: |S| (exact) else: (k − 1) / max STheorem (stated; Beyer, Haas, Reinwald, Sismanis and Gemulla, 2007, and Bar-Yossef, Jayram, Kumar, Sivakumar and Trevisan, 2002). With an ideal hash function and , the estimator is unbiased for , and its relative standard deviation is at most . With a pairwise independent hash, still gives a -approximation with constant probability (Bar-Yossef et al., 2002, by a Chebyshev argument on the number of hashes below ), so the space is bits, and the median trick gives probability .
The unbiasedness comes from a neat fact: for uniform points has the Beta distribution, and , which is why the numerator is rather than .
KMV's strength is that the sketch is a uniform sample of the distinct items (those with the smallest hashes), so it supports set operations:
- Union. The KMV sketch of is the smallest of the two sketches' values together (Mergeable Summaries).
- Jaccard similarity : among the smallest values of the union, the fraction present in both sketches estimates . This is the MinHash idea of Broder (1997).
- Intersection size , estimated from the two.
The program compares yesterday's 30 000 users with today's 25 000, of whom 10 000 are the same, using and 12 different hash functions.
import heapq, math
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)
class KMV:
"""The k smallest distinct hash values, kept in a max-heap (negated) plus a set."""
def __init__(self, k, salt):
self.k, self.salt, self.heap, self.members = k, salt, [], set()
def add(self, x):
h = mix64(x ^ self.salt)
if h in self.members:
return
if len(self.heap) < self.k:
heapq.heappush(self.heap, -h); self.members.add(h)
elif h < -self.heap[0]:
self.members.discard(-heapq.heappushpop(self.heap, -h)); self.members.add(h)
def estimate(self):
if len(self.heap) < self.k:
return len(self.heap) # fewer than k distinct: exact
return (self.k - 1) / (-self.heap[0] / 2 ** 64) # (k - 1) / (k-th smallest hash in [0, 1))
A = range(0, 30000) # 30000 users yesterday
B = range(20000, 45000) # 25000 today; 10000 in both
k = 256
errs, jac, inter = [], [], []
for s in range(12):
salt = s * 0x9E3779B97F4A7C15 & MASK
a, b = KMV(k, salt), KMV(k, salt)
for x in A: a.add(x)
for x in B: b.add(x)
union = sorted(a.members | b.members)[:k] # KMV of the union, from the two sketches
vk = union[-1] / 2 ** 64
est = (k - 1) / vk
errs.append(est / 45000 - 1)
both = sum(h in a.members and h in b.members for h in union)
jac.append(both / k)
inter.append(both / k * est) # |A and B| = Jaccard * |A or B|
rms = math.sqrt(sum(e * e for e in errs) / len(errs))
print(f"k = {k}: union size 45000, relative errors of 12 runs: rms {rms:.3f} (theory 1/sqrt(k - 2) = {1 / math.sqrt(k - 2):.3f})")
print(f"Jaccard similarity: true {10000 / 45000:.3f}, estimates " + " ".join(f"{j:.3f}" for j in jac[:6]))
print("intersection (true 10000), estimates " + " ".join(f"{v:.0f}" for v in inter[:6]))k = 256: union size 45000, relative errors of 12 runs: rms 0.061 (theory 1/sqrt(k - 2) = 0.063)
Jaccard similarity: true 0.222, estimates 0.238 0.223 0.195 0.211 0.219 0.234
intersection (true 10000), estimates 10475 9187 9356 9766 10729 10897
The union estimate's spread matches . The intersection is estimated with a larger relative error (up to about 9% here), because it is a product of two estimates and the Jaccard part rests on only of the sampled values. Small intersections of large sets are hard for every sketch.
In C++
KMV with std::set holding the smallest values (insertion , and only for values below the current maximum, which after a while is rare).
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <iterator>
#include <random>
#include <set>
#include <unordered_set>
std::uint64_t mix64(std::uint64_t x) { // splitmix64 finalizer
x += 0x9E3779B97F4A7C15ULL;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ULL;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBULL;
return x ^ (x >> 31);
}
class KMV {
std::size_t k;
std::uint64_t salt;
std::set<std::uint64_t> S; // the k smallest distinct hash values
public:
KMV(std::size_t k, std::uint64_t salt) : k(k), salt(salt) {}
void add(std::uint64_t x) {
std::uint64_t h = mix64(x ^ salt);
if (S.size() < k) { S.insert(h); return; }
auto last = std::prev(S.end());
if (h < *last && !S.count(h)) { S.erase(last); S.insert(h); }
}
double estimate() const {
if (S.size() < k) return double(S.size());
return (k - 1) / (double(*S.rbegin()) / 18446744073709551616.0); // divide by 2^64
}
};
int main() {
std::mt19937_64 rng(1985);
std::unordered_set<std::uint64_t> exact;
KMV small(64, 1), large(1024, 1);
for (int t = 0; t < 1000000; ++t) {
std::uint64_t x = rng() % 300000; // about 290 000 distinct values
small.add(x); large.add(x); exact.insert(x);
}
double n = double(exact.size());
std::printf("distinct: %.0f\n", n);
std::printf("k = 64: estimate %.0f (%+.1f%%, theory std %.1f%%)\n", small.estimate(),
100 * (small.estimate() / n - 1), 100 / std::sqrt(62.0));
std::printf("k = 1024: estimate %.0f (%+.1f%%, theory std %.1f%%)\n", large.estimate(),
100 * (large.estimate() / n - 1), 100 / std::sqrt(1022.0));
}distinct: 289265
k = 64: estimate 323758 (+11.9%, theory std 12.7%)
k = 1024: estimate 290354 (+0.4%, theory std 3.1%)
Bit patterns or order statistics?
| Flajolet-Martin / HyperLogLog | KMV | |
|---|---|---|
| memory per unit of accuracy | registers of bits | hash values of bits |
| error for (or ) units | about for HyperLogLog | about |
| merge | register-wise maximum | smallest of the union |
| set operations | union only (intersections by inclusion-exclusion, poorly) | union, Jaccard, intersection, filters |
HyperLogLog wins on memory by a factor of about 10 at equal accuracy, KMV on flexibility; the Theta sketches of Apache DataSketches are KMV variants for exactly that reason.
Test yourself
Why do duplicates not affect Flajolet-Martin or KMV?
- They are removed by a hash table
- Equal items have equal hash values, and both sketches depend only on the set of hash values (a maximum, or the smallest distinct values)
- The stream has no duplicates
- They are counted once by a Bloom filter
What accuracy does a single Flajolet-Martin estimator guarantee with a pairwise independent hash?
- for any
- Within a factor of with probability at least , for
- Exact with probability
- An additive error of
Why does the KMV estimator use rather than ?
- To handle hash collisions
- Because for the -th smallest of uniform points, so is unbiased
- Because one value is reserved
- It makes no difference
How does a KMV sketch estimate the Jaccard similarity of two sets?
- By comparing the two estimates
- As the fraction of the smallest hash values of the union that occur in both sketches
- By intersecting the full sets
- By the ratio of the two values