TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › HyperLogLog: Analysis and Bias Corrections

HyperLogLog: Analysis and Bias Corrections

Count-Min Sketch and HyperLogLog introduced HyperLogLog (Flajolet, Fusy, Gandouet and Meunier, 2007) as a data structure: mm registers, each holding the largest "rank" (position of the first 1 bit) among the hashes routed to it, combined by a harmonic mean, with linear counting for small cardinalities. This lesson explains where its constants come from. The two numbers to understand are the bias constant α∞=12ln⁡2≈0.7213\alpha_\infty = \frac{1}{2\ln 2} \approx 0.7213 and the standard error 1.04/m1.04/\sqrt{m}; both drop out of the distribution of a single register. Then come the bias corrections that practical implementations add, and the place of HyperLogLog among the distinct-count sketches.

64 registers (largest rank seen per register)68991096667915610676610771010788118787977868107878717656996867811136696989905000750005000true distinct countestimatedotted line: exact count

The estimator, once more

With pp index bits and m=2pm = 2^p registers, an item's 64-bit hash sends it to register jj (the top pp bits) and gives it the rank ρ\rho, one plus the number of leading zeros of the remaining 64−p64 - p bits. Register MjM_j keeps the maximum rank seen. The estimate is

E=αm m2(∑j=1m2−Mj)−1.E = \alpha_m\, m^2 \Bigl(\sum_{j=1}^{m} 2^{-M_j}\Bigr)^{-1} .

Each 2Mj2^{M_j} is a rough estimate of the number njn_j of distinct items routed to register jj, about n/mn/m. The harmonic mean m/∑j2−Mjm / \sum_j 2^{-M_j} of these rough estimates, times mm, estimates nn, and αm\alpha_m removes a multiplicative bias. Its predecessor, LogLog (Durand and Flajolet, 2003), used the geometric mean instead, α~ m 21m∑jMj\tilde\alpha\, m\, 2^{\frac{1}{m}\sum_j M_j}. The harmonic mean is less sensitive to the occasional register with a very large value, which is why HyperLogLog's error constant is 1.041.04 rather than LogLog's 1.301.30.

The analysis, sketched

The full analysis (Flajolet et al., 2007) uses Mellin transforms and is long; its core is easy to reproduce. Two simplifications make each register tractable.

  1. Ideal hashing. Ranks are independent with Pr⁡[ρ≥k]=2−(k−1)\Pr[\rho \ge k] = 2^{-(k-1)}.
  2. Poissonization. Pretend the number of items in each register is Poisson with mean λ=n/m\lambda = n/m, independently across registers (the real counts are multinomial; for large nn the difference vanishes, which the paper proves).

Under these assumptions a register is at most kk exactly when none of its items has rank above kk, and items with rank above kk arrive as a Poisson process of rate λ2−k\lambda 2^{-k}, so

Pr⁡[M≤k]=exp⁡(−λ 2−k),k=0,1,2,…\Pr[M \le k] = \exp\bigl(-\lambda\, 2^{-k}\bigr), \qquad k = 0, 1, 2, \ldots

From this law, two quantities decide everything. If E[2−M]≈c/λ\mathbb{E}[2^{-M}] \approx c/\lambda, then ∑j2−Mj≈mc/λ=c m2/n\sum_j 2^{-M_j} \approx m c/\lambda = c\, m^2 / n and the estimate α m2/∑j2−Mj\alpha\, m^2 / \sum_j 2^{-M_j} is unbiased for α=c\alpha = c. The relative variance of ∑j2−Mj\sum_j 2^{-M_j} is 1mVar⁡[2−M]/E[2−M]2\frac{1}{m}\operatorname{Var}[2^{-M}]/\mathbb{E}[2^{-M}]^2, and to first order the reciprocal has the same relative error. The program computes both from the register law.

python · try it yourself
import math

def register_law(lam, kmax=90):
    """Poissonized register: lam items on average; P[M <= k] = exp(-lam * 2^-k)."""
    probs, prev = [], 0.0
    for k in range(kmax):
        cur = math.exp(-lam * 2.0 ** -k)
        probs.append(cur - prev)
        prev = cur
    return probs

print("  lam = n/m   lam * E[2^-M]   Var[2^-M]/E[2^-M]^2   E[M] - log2(lam)")
for lam in [10, 100, 1000, 10**4, 10**5]:
    P = register_law(lam)
    E1 = sum(p * 2.0 ** -k for k, p in enumerate(P))
    E2 = sum(p * 4.0 ** -k for k, p in enumerate(P))
    EM = sum(p * k for k, p in enumerate(P))
    print(f"{lam:11}   {lam * E1:13.5f}   {E2 / E1 ** 2 - 1:19.5f}   {EM - math.log2(lam):16.5f}")
print(f"limits: 1/(2 ln 2) = {1 / (2 * math.log(2)):.5f},  3 ln 2 - 1 = {3 * math.log(2) - 1:.5f},  "
      f"sqrt(3 ln 2 - 1) = {math.sqrt(3 * math.log(2) - 1):.4f}")
  lam = n/m   lam * E[2^-M]   Var[2^-M]/E[2^-M]^2   E[M] - log2(lam)
         10         0.72134               1.07951            1.33275
        100         0.72135               1.07925            1.33274
       1000         0.72135               1.07954            1.33275
      10000         0.72134               1.07954            1.33275
     100000         0.72135               1.07926            1.33274
limits: 1/(2 ln 2) = 0.72135,  3 ln 2 - 1 = 1.07944,  sqrt(3 ln 2 - 1) = 1.0390

So λ E[2−M]→12ln⁡2\lambda\,\mathbb{E}[2^{-M}] \to \frac{1}{2\ln 2}, which is α∞=0.72135\alpha_\infty = 0.72135, and the relative variance of 2−M2^{-M} tends to 3ln⁡2−13\ln 2 - 1, which gives the standard error

3ln⁡2−1m≈1.039m.\frac{\sqrt{3\ln 2 - 1}}{\sqrt{m}} \approx \frac{1.039}{\sqrt{m}} .

(The tiny wobble in the fifth digit is real: these quantities oscillate with log⁡2λ\log_2 \lambda with an amplitude of about 10−510^{-5}, a famous feature of the analysis that is far below the statistical error.) The last column gives LogLog's constant the same way: E[M]≈log⁡2λ+1.33275\mathbb{E}[M] \approx \log_2\lambda + 1.33275, so the geometric-mean estimator needs α~≈2−1.33275≈0.397\tilde\alpha \approx 2^{-1.33275} \approx 0.397. The finite-mm correction αm≈0.7213/(1+1.079/m)\alpha_m \approx 0.7213/(1 + 1.079/m) accounts for the bias of taking a reciprocal of a random sum and is fitted in the paper.

Theorem (Flajolet, Fusy, Gandouet and Meunier, 2007; stated). Under the ideal-hash assumption, for m≥16m \ge 16 the estimate EE is asymptotically unbiased as n→∞n \to \infty, apart from the oscillation mentioned, and its relative standard error is βm/m\beta_m/\sqrt{m} with β∞=3ln⁡2−1≈1.03896\beta_\infty = \sqrt{3\ln 2 - 1} \approx 1.03896.

The program measures both estimators at n=20 000n = 20\,000 with 20 different hash functions.

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)

n, runs = 20000, 20
err = {(name, p): [] for name in ["LogLog", "HyperLogLog"] for p in [6, 8]}
for s in range(runs):
    hashes = [mix64(x ^ (s * 0x9E3779B97F4A7C15 & MASK)) for x in range(n)]
    for p in [6, 8]:
        m = 1 << p
        M = [0] * m
        for h in hashes:
            j, rest = h >> (64 - p), h & ((1 << (64 - p)) - 1)
            r = 64 - p - rest.bit_length() + 1
            if r > M[j]:
                M[j] = r
        loglog = 0.39701 * m * 2 ** (sum(M) / m)                              # geometric mean (Durand-Flajolet)
        hyper = 0.7213 / (1 + 1.079 / m) * m * m / sum(2.0 ** -r for r in M)  # harmonic mean
        err[("LogLog", p)].append(loglog / n - 1)
        err[("HyperLogLog", p)].append(hyper / n - 1)
for (name, p), e in err.items():
    m = 1 << p
    c = 1.30 if name == "LogLog" else 1.04
    rms = math.sqrt(sum(v * v for v in e) / len(e))
    print(f"{name:11} m = {m:3}: rms error {rms:.3f}   theory {c:.2f}/sqrt(m) = {c / math.sqrt(m):.3f}")
LogLog      m =  64: rms error 0.216   theory 1.30/sqrt(m) = 0.163
LogLog      m = 256: rms error 0.075   theory 1.30/sqrt(m) = 0.081
HyperLogLog m =  64: rms error 0.133   theory 1.04/sqrt(m) = 0.130
HyperLogLog m = 256: rms error 0.066   theory 1.04/sqrt(m) = 0.065

Small cardinalities and the bias corrections

The asymptotic analysis says nothing about small nn. When nn is not much larger than mm, many registers are still 0, each contributes 20=12^0 = 1 to the sum, and the raw estimate is far too large: with n=0n = 0 it is αmm\alpha_m m, not 0. The original paper therefore switches to linear counting (Whang, Vander-Zanden and Taylor, 1990) when E≤52mE \le \frac{5}{2}m: with VV empty registers out of mm, the estimate mln⁡(m/V)m \ln(m/V) comes from E[V]≈me−n/m\mathbb{E}[V] \approx m e^{-n/m}, the fraction of empty bins after nn random balls. The program measures the bias and error of both for m=256m = 256 over a range of nn.

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 registers(n, p, salt):
    M = [0] * (1 << p)
    for x in range(n):
        h = mix64(x ^ salt)
        j, rest = h >> (64 - p), h & ((1 << (64 - p)) - 1)
        r = 64 - p - rest.bit_length() + 1
        if r > M[j]:
            M[j] = r
    return M

def raw_hll(M):
    m = len(M)
    return 0.7213 / (1 + 1.079 / m) * m * m / sum(2.0 ** -r for r in M)

def hll(M):
    m, E = len(M), raw_hll(M)
    zeros = M.count(0)
    return m * math.log(m / zeros) if E <= 2.5 * m and zeros else E

p, runs = 8, 25
m = 1 << p
print(f"m = {m} registers, {runs} runs per n; mean relative error (bias) and rms error")
print("     n   raw bias   raw rms   corrected bias   corrected rms")
for n in [50, 200, 400, 640, 800, 1500, 4000, 6000]:
    raw, cor = [], []
    for s in range(runs):
        M = registers(n, p, s * 0x9E3779B97F4A7C15 & MASK)
        raw.append(raw_hll(M) / n - 1)
        cor.append(hll(M) / n - 1)
    rms = lambda e: math.sqrt(sum(v * v for v in e) / len(e))
    print(f"{n:6}   {sum(raw) / runs:+8.3f}   {rms(raw):7.3f}   {sum(cor) / runs:+14.3f}   {rms(cor):13.3f}")
print(f"switch to linear counting while E <= 2.5 m = {2.5 * m:.0f}; theory rms 1.04/sqrt(m) = {1.04 / math.sqrt(m):.3f}")
m = 256 registers, 25 runs per n; mean relative error (bias) and rms error
     n   raw bias   raw rms   corrected bias   corrected rms
    50     +3.178     3.178           +0.006           0.043
   200     +0.480     0.481           -0.003           0.058
   400     +0.121     0.128           +0.019           0.057
   640     +0.038     0.065           +0.040           0.068
   800     +0.009     0.061           +0.009           0.061
  1500     +0.012     0.063           +0.012           0.063
  4000     +0.014     0.073           +0.014           0.073
  6000     -0.006     0.076           -0.006           0.076
switch to linear counting while E <= 2.5 m = 640; theory rms 1.04/sqrt(m) = 0.065

The raw estimate is useless below a few times mm (a bias of +318% at n=50n = 50), linear counting is excellent there, and above the switch the two coincide. Right at the switch, around n≈2.5mn \approx 2.5m, a small bias remains (+4% here), because neither estimator is accurate in the transition. Practical implementations go further:

  • HyperLogLog++ (Heule, Nunkesser and Hall, 2013, at Google) uses a 64-bit hash, which removes the original paper's large-range correction for 32-bit hashes, subtracts an empirically measured bias for E≤5mE \le 5m (tables interpolated by nearest neighbours), chooses between linear counting and the corrected estimate by a per-precision threshold, and stores registers sparsely (a list of (index, rank) pairs) while few are non-zero, so a sketch of a small set costs little memory.
  • Improved estimators (Ertl, 2017) derive an estimator from the register histogram that is accurate over the whole range without empirical tables, and maximum-likelihood estimators reach slightly lower variance.

Space

Each register holds a rank of at most log⁡2n+1\log_2 n + 1, so it needs ⌈log⁡2(log⁡2n+1)⌉\lceil \log_2(\log_2 n + 1) \rceil bits, 6 bits for any realistic nn: hence the name. For relative error ε\varepsilon the total is O(ε−2log⁡log⁡n)O(\varepsilon^{-2} \log\log n) bits. The optimal bound is Θ(ε−2+log⁡n)\Theta(\varepsilon^{-2} + \log n) bits, reached by Kane, Nelson and Woodruff (2010) with a more complex algorithm; HyperLogLog's extra log⁡log⁡n\log\log n factor is the price of its simplicity, and nobody pays it reluctantly: m=214m = 2^{14} registers, 12 KiB, give 0.81% error for any nn up to 2642^{64}.

In C++

HyperLogLog with p=12p = 12 (4096 one-byte registers), std::countl_zero for the rank, linear counting for small sets, and the register-wise maximum to merge two sites' sketches.

cpp · try it yourself
#include <algorithm>
#include <bit>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <vector>

std::uint64_t mix64(std::uint64_t x) {
    x += 0x9E3779B97F4A7C15ULL;
    x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ULL;
    x = (x ^ (x >> 27)) * 0x94D049BB133111EBULL;
    return x ^ (x >> 31);
}

class HyperLogLog {
    int p;
    std::vector<std::uint8_t> M;                                // one byte per register (6 bits would do)
public:
    explicit HyperLogLog(int p) : p(p), M(std::size_t(1) << p, 0) {}
    void add(std::uint64_t x) {
        std::uint64_t h = mix64(x);
        std::size_t j = h >> (64 - p);                          // top p bits pick the register
        std::uint64_t rest = h << p;                            // the other 64 - p bits, left-aligned
        int rank = rest ? std::countl_zero(rest) + 1 : 64 - p + 1;
        M[j] = std::max<std::uint8_t>(M[j], rank);
    }
    void merge(const HyperLogLog& o) { for (std::size_t j = 0; j < M.size(); ++j) M[j] = std::max(M[j], o.M[j]); }
    double estimate() const {
        double m = double(M.size()), sum = 0;
        int zeros = 0;
        for (auto r : M) { sum += std::ldexp(1.0, -r); zeros += r == 0; }
        double E = 0.7213 / (1 + 1.079 / m) * m * m / sum;
        if (E <= 2.5 * m && zeros) E = m * std::log(m / zeros);      // linear counting for small n
        return E;
    }
};

int main() {
    HyperLogLog a(12), b(12);                                   // 4096 registers: 1.04/64 = 1.6%
    for (std::uint64_t x = 0; x < 600000; ++x) a.add(x);         // site A: users 0 .. 599 999
    for (std::uint64_t x = 400000; x < 1000000; ++x) b.add(x);   // site B: users 400 000 .. 999 999
    std::printf("A: %.0f (true 600000)\nB: %.0f (true 600000)\n", a.estimate(), b.estimate());
    a.merge(b);
    std::printf("A or B after merging: %.0f (true 1000000)\n", a.estimate());
    HyperLogLog tiny(12);
    for (std::uint64_t x = 0; x < 1000; ++x) tiny.add(x);
    std::printf("1000 items, linear counting range: %.0f\n", tiny.estimate());
}
A: 617902 (true 600000)
B: 602165 (true 600000)
A or B after merging: 1020719 (true 1000000)
1000 items, linear counting range: 997

The merged sketch estimates the union of the two sites without double counting the 200 000 shared users, which is the property that makes HyperLogLog the default distinct counter of distributed analytics systems.

Test yourself

Where does the constant α∞=1/(2ln⁡2)≈0.7213\alpha_\infty = 1/(2 \ln 2) \approx 0.7213 come from?

  1. It is fitted to experiments only
  2. From the register law Pr⁡[M≤k]=e−λ2−k\Pr[M \le k] = e^{-\lambda 2^{-k}}: λ E[2−M]→1/(2ln⁡2)\lambda\,\mathbb{E}[2^{-M}] \to 1/(2\ln 2), so it makes the harmonic-mean estimator unbiased for large nn
  3. From the number of bits per register
  4. From linear counting

What does the constant 1.041.04 in HyperLogLog's standard error 1.04/m1.04/\sqrt{m} come from?

  1. 3ln⁡2−1\sqrt{3 \ln 2 - 1}, the limiting relative standard deviation of 2−M2^{-M} for one register
  2. ln⁡2+1/3\ln 2 + 1/3
  3. The ratio of harmonic to geometric mean
  4. It is the LogLog constant

Why is the raw HyperLogLog estimate badly biased for small nn?

  1. Because the hash function collides
  2. Because empty registers each contribute 20=12^0 = 1 to the sum, so the estimate stays near αmm\alpha_m m even for tiny nn; linear counting on the number of empty registers is used instead
  3. Because αm\alpha_m is too large
  4. Because registers overflow

How many bits does a HyperLogLog register need for streams of up to 2642^{64} distinct items?

  1. 64
  2. 6, since the rank is at most about 65
  3. 1
  4. log⁡2m\log_2 m