TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Flajolet-Martin and k Minimum Values

Flajolet-Martin and k Minimum Values

Counting distinct items, F0F_0, 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 Ω(n)\Omega(n) 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 F0F_0 uniform random values reveal F0F_0. 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, kk minimum values.

The bit-pattern idea

Let hh map items to uniformly random 64-bit words. A hash value ends in at least zz zero bits with probability 2−z2^{-z}. Among F0F_0 distinct items, the largest number of trailing zeros ZZ is therefore around log⁡2F0\log_2 F_0: if 2z≫F02^z \gg F_0 it is unlikely that any item reaches zz zeros, and if 2z≪F02^z \ll F_0 it is very likely that some item does.

Theorem (after Alon, Matias and Szegedy, 1996). Let hh be drawn from a pairwise independent family, ZZ the largest number of trailing zeros of h(x)h(x) over the stream, and F^=2Z+1/2\hat F = 2^{Z + 1/2}. For every c>2c > 2,

Pr⁡[F0c≤F^≤c F0]≥1−22c.\Pr\Bigl[\frac{F_0}{c} \le \hat F \le c\, F_0\Bigr] \ge 1 - \frac{2\sqrt{2}}{c} .
Proof

For each zz, let YzY_z be the number of distinct items whose hash has at least zz trailing zeros, a sum of F0F_0 pairwise independent indicators with probability 2−z2^{-z}. So E[Yz]=F0/2z\mathbb{E}[Y_z] = F_0/2^z and Var⁡[Yz]≤F0/2z\operatorname{Var}[Y_z] \le F_0/2^z.

Overestimate. Let aa be the smallest integer with 2a+1/2≥cF02^{a + 1/2} \ge c F_0. Then F^≥cF0\hat F \ge cF_0 requires Z≥aZ \ge a, that is Ya≥1Y_a \ge 1, and by Markov Pr⁡[Ya≥1]≤F0/2a≤2/c\Pr[Y_a \ge 1] \le F_0/2^a \le \sqrt{2}/c.

Underestimate. Let bb be the largest integer with 2b+1/2≤F0/c2^{b + 1/2} \le F_0 / c. Then F^≤F0/c\hat F \le F_0/c requires Z≤bZ \le b, that is Yb+1=0Y_{b+1} = 0, and by Chebyshev Pr⁡[Yb+1=0]≤Var⁡[Yb+1]/E[Yb+1]2≤2b+1/F0≤2/c\Pr[Y_{b+1} = 0] \le \operatorname{Var}[Y_{b+1}]/\mathbb{E}[Y_{b+1}]^2 \le 2^{b+1}/F_0 \le \sqrt{2}/c.

Together the failure probability is at most 22/c2\sqrt{2}/c. (Alon, Matias and Szegedy state the bound 2/c2/c for their variant of the estimator.) □\square

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 mm substreams, each keeps a bitmap of the trailing-zero counts it has seen, RjR_j is the position of the lowest unset bit of bitmap jj, and

F^0=mφ 21m∑jRj,φ≈0.77351,\hat F_0 = \frac{m}{\varphi}\, 2^{\frac{1}{m}\sum_j R_j}, \qquad \varphi \approx 0.77351 ,

with a relative standard error of about 0.78/m0.78/\sqrt{m} (Flajolet and Martin, 1985; the constant φ\varphi corrects a bias found by their analysis, which assumes an ideal hash function and is stated here).

python · try it yourself
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 0.78/640.78/\sqrt{64}.

kk minimum values

The order-statistic view is simpler to analyse. Map every item to h(x)h(x) uniform in [0,1)[0, 1) and keep the kk smallest distinct hash values; let vkv_k be the largest of them. If F0F_0 points are thrown uniformly into [0,1)[0, 1), the kk-th smallest is around k/F0k/F_0, so F0≈k/vkF_0 \approx k/v_k.

text
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 S

Theorem (stated; Beyer, Haas, Reinwald, Sismanis and Gemulla, 2007, and Bar-Yossef, Jayram, Kumar, Sivakumar and Trevisan, 2002). With an ideal hash function and k≥3k \ge 3, the estimator (k−1)/vk(k - 1)/v_k is unbiased for F0F_0, and its relative standard deviation is at most 1/k−21/\sqrt{k - 2}. With a pairwise independent hash, k=O(1/ε2)k = O(1/\varepsilon^2) still gives a (1±ε)(1 \pm \varepsilon)-approximation with constant probability (Bar-Yossef et al., 2002, by a Chebyshev argument on the number of hashes below (1±ε)k/F0(1 \pm \varepsilon)k/F_0), so the space is O(ε−2log⁡n)O(\varepsilon^{-2}\log n) bits, and the median trick gives probability 1−δ1 - \delta.

The unbiasedness comes from a neat fact: vkv_k for F0F_0 uniform points has the Beta(k,F0−k+1)(k, F_0 - k + 1) distribution, and E[1/vk]=F0/(k−1)\mathbb{E}[1/v_k] = F_0/(k-1), which is why the numerator is k−1k - 1 rather than kk.

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 A∪BA \cup B is the kk smallest of the two sketches' values together (Mergeable Summaries).
  • Jaccard similarity J=∣A∩B∣/∣A∪B∣J = \lvert A \cap B \rvert / \lvert A \cup B \rvert: among the kk smallest values of the union, the fraction present in both sketches estimates JJ. This is the MinHash idea of Broder (1997).
  • Intersection size =J⋅∣A∪B∣= J \cdot \lvert A \cup B \rvert, 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 k=256k = 256 and 12 different hash functions.

python · try it yourself
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 1/k−21/\sqrt{k-2}. 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 Jk≈57Jk \approx 57 of the sampled values. Small intersections of large sets are hard for every sketch.

In C++

KMV with std::set holding the kk smallest values (insertion O(log⁡k)O(\log k), and only for values below the current maximum, which after a while is rare).

cpp · try it yourself
#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 O(log⁡log⁡n)O(\log\log n) bits hash values of O(log⁡n)O(\log n) bits
error for kk (or mm) units about 1.04/m1.04/\sqrt{m} for HyperLogLog about 1/k1/\sqrt{k}
merge register-wise maximum kk 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?

  1. They are removed by a hash table
  2. Equal items have equal hash values, and both sketches depend only on the set of hash values (a maximum, or the kk smallest distinct values)
  3. The stream has no duplicates
  4. They are counted once by a Bloom filter

What accuracy does a single Flajolet-Martin estimator 2Z+1/22^{Z + 1/2} guarantee with a pairwise independent hash?

  1. 1±ε1 \pm \varepsilon for any ε\varepsilon
  2. Within a factor cc of F0F_0 with probability at least 1−22/c1 - 2\sqrt{2}/c, for c>22c > 2\sqrt{2}
  3. Exact with probability 1/21/2
  4. An additive error of F0\sqrt{F_0}

Why does the KMV estimator use (k−1)/vk(k - 1)/v_k rather than k/vkk/v_k?

  1. To handle hash collisions
  2. Because E[1/vk]=F0/(k−1)\mathbb{E}[1/v_k] = F_0/(k - 1) for the kk-th smallest of F0F_0 uniform points, so (k−1)/vk(k-1)/v_k is unbiased
  3. Because one value is reserved
  4. It makes no difference

How does a KMV sketch estimate the Jaccard similarity of two sets?

  1. By comparing the two estimates
  2. As the fraction of the kk smallest hash values of the union that occur in both sketches
  3. By intersecting the full sets
  4. By the ratio of the two vkv_k values