Streaming algorithms and sketches
When data passes once and does not fit in memory, answer using sublinear summaries. Study the streaming model, reservoir sampling, Misra–Gries heavy hitters, Bloom filters, count-min and Count Sketch, HyperLogLog distinct counting and mergeability for distributed systems.
After this lesson you can
- Formulate (ε, δ) streaming guarantees and reason about memory bounds.
- Implement reservoir sampling and prove uniformity.
- Size a Bloom filter and count-min sketch for a target error.
- Implement HyperLogLog with corrections and measure relative error.
- Merge sketches from data fragments and choose the right sketch for each query.
Before you start
Motivation: one pass and very little memory
Three problems that seem trivial until data size is considered:
- Distinct IP addresses. A provider’s router sees tens of millions of packets per second and wants distinct source IPs per minute: a sudden jump indicates a distributed denial-of-service attack. Storing exact seen IPv6 addresses requires memory proportional to their number, in a router data plane with only a few megabytes of SRAM.
- Most visited URLs. A service with billions of daily requests wants the most requested routes per hour and region. A dictionary of exact counts grows with distinct routes, including the long tail of URLs requested once.
- Previously seen documents. A crawler that downloaded ten billion pages must decide for each new link whether it has visited it. A hash table of URLs averaging 80 bytes would need almost a terabyte of RAM.
In all three cases data arrives as a stream, can be read once and does not fit in memory. This lesson gives up exactness in a controlled way: maintain a sublinear sketch, often kilobytes, answering with bounded error and bounded failure probability. With 12 KiB, HyperLogLog counts billions of distinct elements with typical error 0.81%. With 1.2 MB, a Bloom filter answers “have I seen this URL?” for one million URLs with 1% false positives and no false negatives.
Everything builds on universal hashing and k-wise independence: a hash turns arbitrary elements, perhaps adversarially chosen, into values behaving randomly, and Markov, Chebyshev and Chernoff inequalities turn that behavior into guarantees.
The streaming model
Three variants depend on how changes:
- Insert-only (cash register): each adds 1 to . This covers logs and network traffic.
- Turnstile: each update is a pair with possibly negative, and . If additionally always (nothing absent is deleted), it is strict turnstile. General turnstile can subtract yesterday’s window from today’s or compare two streams.
- Sliding window: only the most recent elements count. We do not cover it here.
Typical queries are functions of : number of distinct elements , length , second moment (measuring distribution concentration; Alon, Matias and Szegedy, 1999, studied moments generally), a frequency , elements with or a uniform sample.
That last sentence distinguishes average-case analysis. URLs are not assumed to follow a friendly distribution: the adversary fixes the stream, then hash functions are drawn. This is the universal-hashing contract and has the same caveat: if the adversary sees the functions, the guarantee disappears.
Why something must be sacrificed
Must we approximate and randomize? For distinct count, yes, and the proof is a clean communication argument.
Proof
For each subset , feed the algorithm elements of in increasing order and call the resulting memory state . Show implies . If , ending the stream there gives different answers and , so states differ because the answer depends only on state. If , take and append to both streams: correct answers are and respectively. The algorithm is deterministic, so identical states and continuation would give the same answer; hence . There are subsets and therefore at least states requiring bits.
∎This is a special case of a general technique: memory state is a message the first stream half sends to the second, so a one-way communication complexity lower bound gives a memory lower bound. INDEX (Alice has an -bit vector, Bob an index and must find bit from one Alice message) requires bits even with randomness, implying exact distinct counting needs linear memory even if failure probability is allowed. Conversely, Alon, Matias and Szegedy proved a deterministic algorithm cannot approximate with small relative error without linear memory either. Both concessions, approximation and randomness, are necessary. Even with both, approximating with relative error requires bits (Indyk and Woodruff, 2003, using Gap-Hamming), so HyperLogLog’s is essentially unimprovable.
| Query | Structure | Memory | Guarantee | Merge |
|---|---|---|---|---|
| uniform sample of | reservoir | elements | exact distribution | random keys |
| elements with | Misra–Gries | counters | yes | |
| is present? | Bloom filter | bits per element | no false negatives, false positives | bitwise OR |
| approximate | count-min | counters | with prob. | sum |
| unbiased | Count Sketch | counters | with prob. | sum |
| distinct count | HyperLogLog | 6-bit registers | typical error | maximum |
Reservoir sampling
The simplest problem: retain uniformly random elements from a stream of unknown length. If were known, drawing positions would suffice. Without it, maintain a valid sample of the prefix at every instant.
For the calculation is a telescoping product. Element enters with probability and survives each later with probability :
Prove the general case in the guided exercise by induction on , separating whether the last element belongs to the subset. The theorem says more than “each element is present with probability ”: the entire sample is uniform, so any statistic computed on it has the same distribution as on a sample without replacement drawn knowing . The first lab cell checks this with a chi-square test over all 15 possible subsets.
Three extensions used in practice:
- Skipping (algorithm L). Drawing once per element is costly for a huge stream and small because almost everything is discarded. Li (1994) directly draws how many to skip, reducing expected draws to .
- Weighted sampling. If each element has weight , Efraimidis and Spirakis (2006) assign key with and keep the largest (a size- heap). With , is selected with probability exactly ; with the result is successive sampling without replacement proportional to weights.
- Random keys (bottom-k). Assign each element a key and retain the smallest; this gives exactly the reservoir distribution because all key orders are equiprobable. Two stream samples combine by retaining the smallest in their union. This returns in the merge section.
Frequent elements: Misra–Gries and Space-Saving
Finding exact heavy hitters requires linear memory (by the same type of argument as before). But every element exceeding a fixed stream fraction can be found. The idea, going back to Boyer–Moore majority, is to cancel occurrences of different elements: if one occupies over half the stream, it survives any pairing with different elements.
Proof
’s counter increases only when arrives, so . Difference increases by one only when arrives and is discarded in a decrement step, or has a counter that is decremented. Both happen in decrement steps, at most once per step, so . To bound , count units: every read element contributes one unit to counter sum, and each decrement step destroys (one from each of counters and the discarded element’s). Since final sum is nonnegative, , i.e. . If , then .
∎Amortized cost per element is : a decrement traverses counters, but each decremented unit was created by a previous increment, so total decrement work is at most . A bucket list by counter value (Demaine, López-Ortiz and Munro, 2002) gives worst-case .
Space-Saving (Metwally, Agrawal and El Abbadi, 2005) changes the full-table rule: the newcomer replaces the minimum-count element and inherits . Counter sum is always , estimates become overestimates, , and since , every element with is in the table. The two algorithms are essentially the same: Agarwal and coauthors (2012) proved Space-Saving with counters and Misra–Gries with retain the same information; Space-Saving often estimates top ranks more accurately in practice.
Bloom filter
A Bloom filter answers membership with false positives but no false negatives, using a fraction of exact-set memory. It is the lesson’s oldest sketch: Burton Bloom proposed it in 1970 for a hyphenation dictionary that did not fit in memory.
If was inserted, its bits are 1 and the answer is “possibly present”: no false negatives. A false positive occurs when other keys have set all bits of an absent .
Proof
Each of the written positions is uniform and independent, and a fixed bit avoids each with probability ; hence the first formula and . An absent key has new independent positions; approximating the fraction of 1 bits by its expectation , all hit 1 bits with probability . To optimize, write , so and
Maximize on , symmetric about . With , its derivative is , where . This tends to 0 at , vanishes at and derivative is negative near 0 and positive from to ; hence on , increases to and by symmetry decreases afterward. Maximum of , hence minimum of , is at . Then gives and .
∎The second formula is approximate: bits are not independent (if one is 1 another is slightly likelier 0 because the sum is bounded). Bose and coauthors (2008) showed the exact rate is somewhat higher than , with negligible difference for of thousands of bits onward. The optimum has a nice interpretation: with hashes half the bits are 1, the array has maximum entropy and each of the bits checked by an absent key is 1 with probability , so each hash halves the rate.
Size a filter
Solving for gives the design formula:
A 1% false-positive rate costs 9.6 bits per key and 7 hashes; 0.1% costs 14.4 bits and 10 hashes. Key size does not appear: a filter for 80-byte URLs occupies the same as one for integers. No false-negative-free structure with rate can use fewer than bits in the worst case (Carter, Floyd, Gill, Markowsky and Wegman, 1978), so Bloom pays factor over optimum.
Hash functions and variants
The analysis assumes independent functions. Computing genuine hashes costs time, tempting us to derive positions from one. This must be done correctly:
- Double hashing. Kirsch and Mitzenmacher (2006) proved , with independent , asymptotically retains the same false-positive rate. Two hashes suffice. Avoid being 0 or sharing factors with , which makes the positions repeat.
- Correlated positions. Using or taking pieces of a hash that is too short breaks independence: two keys whose first bit is in one area share almost all the rest. In the lab, with 1% sizing, consecutive positions give 23% false positives.
Variants address limitations of the basic filter:
- Deletion. A standard filter cannot delete: clearing bits also clears bits of other keys, creating false negatives. A counting filter (Fan, Cao, Almeida and Broder, 2000) replaces each bit with a 4-bit counter, incremented on insertion and decremented on deletion, quadrupling memory (with possible, though unlikely, overflow).
- Cuckoo filter. Fan, Andersen, Kaminsky and Mitzenmacher (2014) store an -bit fingerprint per key in a cuckoo hash table with two candidate buckets, the second calculated as the first XOR fingerprint hash, permitting relocation without knowing the key. It supports deletion and for rates below about 3% uses less space than Bloom.
- Blocked filters. To make each query touch one cache line, first choose a 512-bit block by hash and place the positions inside. False-positive rate worsens slightly but speed improves greatly.
Count-min and Count Sketch
Now estimate frequency of any element, not just the most frequent, in the turnstile model.
Each row is a keyless hash table: ’s cell accumulates plus frequencies of all elements colliding with . In strict turnstile those frequencies are nonnegative, so each row overestimates and the minimum is the row with least noise.
The proof uses Markov’s inequality per row (universal suffices to bound expected noise by ) and independence between rows; you will do it in the exercise. Choice is not accidental: it minimizes total memory for given and . With and , counters are needed whether the universe has thousands or billions of elements.
The price is the word additive. Error is measured against , the whole stream size, not . For an element with and relative error is at most 2%. For one with in a stream of , the bound permits estimate .
Two practical count-min improvements:
- Conservative update (Estan and Varghese, 2002). On insertion , increment only cells equal to current minimum , up to . Each cell remains between the frequency of any element hashing to it and its ordinary count-min value, so estimates remain overestimates with the same guarantee and improve substantially in practice. But linearity is lost: deletion is unsupported, and the sum of two conservative sketches remains a valid bound but is no longer the joint stream’s conservative sketch, so some benefit is lost on merging.
- Heavy hitters with count-min. Alongside the sketch maintain a heap of candidates with estimates above . Since , none with is missed, and false candidates have with probability . The log lab uses this.
Count Sketch: random signs and median
Count Sketch (Charikar, Chen and Farach-Colton, 2002) adds a sign function to each row, independent of . Update adds to and each row’s estimate is . Expanding,
If is pairwise independent, for and the estimate is unbiased: noise no longer accumulates but cancels in expectation. Its variance, with also pairwise independent, is
because cross terms have zero expectation. By Chebyshev, with each row errs by more than with probability at most . To move from to the minimum does not work (errors have both signs): take the median of rows.
Proof
If the median is outside , at least half the are outside on the same side. Let be a sum of independent indicators with mean . By Hoeffding’s bound (the additive version of Chernoff), .
∎This is probability amplification again: an estimator correct with constant probability becomes one correct with probability using independent copies. The theorem’s constants are pessimistic; in practice 5 or 7 rows suffice.
Which is better? Count Sketch guarantees with columns and count-min guarantees with . Always , and the difference is small only when nearly all mass is in a handful of elements: with uniform on elements, , and in the lab cell with one million occurrences from a Zipf law of exponent 1.1 on elements, versus . At equal memory, Count Sketch has lower mean error there, especially for frequent elements, and is unbiased; count-min is simpler, never underestimates and has a distribution-independent bound. With strong skew the balance reverses for rare items: the minimum of rows often finds one where shares no cell with a heavy item, whereas Count Sketch’s median still sees those collisions, and count-min has less error (Cormode and Muthukrishnan analyzed this Zipf regime in 2005). The figure shows this by moving the exponent.
Linear sketches and random projections
Count-min and Count Sketch are linear: the sketch is for a random matrix of rows and columns that is not stored (hash functions define it). Each column of has one nonzero element per block of rows, equal to 1 or . Linearity gives turnstile updates, stream differences and merging for free. It is the same idea as the Johnson–Lindenstrauss lemma: a random low-dimensional projection preserves what matters. Indeed, in one Count Sketch row is an unbiased estimator of (if is four-wise independent, variance is controlled as in the Alon–Matias–Szegedy sketch), and Count Sketch matrices are used as sparse projections in numerical linear algebra matrix sketching.
Counting distinct items: Flajolet–Martin to HyperLogLog
Flip a coin until heads and record the number of flips. If told that the record over a series was 20 flips, suspect around rounds: a record of has probability order per round. HyperLogLog applies this idea to a hash.
Let hash each element to a bit string behaving uniformly, and let be the position of the first 1 in , counting from 1. Then : leading zeros are needed. Crucially, duplicates do not matter: a repeated element has the same hash and . If the stream has distinct items and ,
which goes from near 0 to near 1 when crosses . Thus estimates up to a constant factor. This is the Flajolet–Martin (1985) principle. It has two problems: takes only powers of 2 and has huge variance (one lucky element doubles the estimate).
The solution is stochastic averaging: the first hash bits select one of registers and the rest are used for . Each register stores maximum among items landing in it, about of them, so estimates . The registers must be combined. LogLog (Durand and Flajolet, 2003) used the geometric mean and achieved typical error . HyperLogLog uses the harmonic mean, far less sensitive to abnormally large registers.
The paper’s analysis using complex analysis (Mellin transforms and poissonization) proves asymptotically unbiased apart from a tiny oscillation, with typical relative error , with . This gives rule : with registers, 0.81%. We do not reproduce the proof; the lab checks it empirically. Memory also has a nice interpretation: a register stores a number of order , fitting in bits (hence the name). With a 64-bit hash and , and 6 bits suffice: bytes count up to elements with typical error 0.81%.
Corrections
The raw formula fails at extremes, and corrections are part of the algorithm.
Small cardinalities. If is small relative to , most registers remain 0 and each contributes to the sum: with all at 0, , about , even with nothing seen. But in this regime a better estimator is linear counting (Whang, Vander-Zanden and Taylor, 1990): if registers are zero, since each avoids the elements with probability , and solving gives
The paper’s rule: if and , return linear counting.
Large cardinalities. With a 32-bit hash, when approaches hashes of distinct elements begin colliding, and the paper corrects with if . With 64 bits this practically disappears.
HyperLogLog++. Heule, Nunkesser and Hall (2013), at Google, described improvements now used by almost all implementations: 64-bit hash, empirical raw-estimator bias correction for (interpolating simulation tables), an empirical threshold for switching to linear counting, and a sparse representation storing only nonzero (register, value) pairs while there are few items. Bias correction matters: just above threshold the raw estimator overestimates by roughly 2%, measured by a lab cell.
Mergeable sketches
In a distributed system data does not pass through one place: each server, table partition and time interval has its own stream. We need to summarize each piece independently and combine summaries without returning to the data.
| Sketch | Merge | Why it works |
|---|---|---|
| Bloom filter | bitwise OR | bits of are the union of those of and ; identical result |
| count-min, Count Sketch | matrix sum | linear: ; identical result |
| HyperLogLog | register-wise maximum | maximum of over is the maximum of the two maxima; identical result |
| random-key sample | smallest keys of union | each of the smallest of is among its part’s smallest |
| Misra–Gries | add counts and subtract the -th largest | error remains bounded by |
The first three merges are exact: the result is bit-for-bit the same as processing the entire stream through one sketch. Thus these structures underpin approximate analytics at scale. Redis stores 12 KB HyperLogLog using PFADD, PFCOUNT and PFMERGE; BigQuery offers APPROX_COUNT_DISTINCT and HLL_COUNT functions based on HyperLogLog++, and Spark has approx_count_distinct; Apache DataSketches offers production-ready mergeable serializable versions of most sketches here and many others. A typical pattern stores a HyperLogLog per day and country and answers “unique users this week in Europe” by merging 7 × 27 sketches in milliseconds, impossible with exact distinct counters that cannot be added. Likewise monitoring systems use mergeable quantile sketches (KLL, t-digest, DDSketch), in the family of XGBoost’s weighted quantile sketch, allowing large-scale inference services to aggregate latency and usage statistics replica by replica.
Two cautions. First, merging requires identical hash functions and parameters (, , , , seeds). Count-min sketches with different seeds cannot be added, and counters alone do not reveal this. Second, unions merge well; intersections do not. AND of two Bloom filters is not the intersection’s filter (it has more false positives), and estimating with HyperLogLog by inclusion–exclusion, , carries error proportional to , useless for a small intersection. For set similarity use MinHash, covered in corpus deduplication.
Implementation from scratch
Cells build a small sketch library with numpy. All hashes come from a specific universal family, Dietzfelbinger’s multiply, add and shift: for 32-bit keys, with random 64-bit is strongly universal, and numpy uint64 arithmetic is already modulo . Synthetic streams contain to elements so each cell takes seconds in the browser; on your machine with CPython you can multiply them by 10.
First, reservoir and its weighted version. The uniformity test checks not just marginal probabilities but frequency of every one of the possible subsets.
import numpy as np
import random
import heapq
from itertools import combinations
def reservoir(stream, k, rng):
"""Algoritmo R: muestra uniforme de k elementos de un stream de longitud desconocida."""
R = []
for t, x in enumerate(stream): # x es el elemento número t + 1
if t < k:
R.append(x)
else:
j = rng.randrange(t + 1) # uniforme en {0, ..., t}
if j < k: # con probabilidad k / (t + 1)
R[j] = x
return R
rng = random.Random(0)
n, k, reps = 6, 2, 30000
cuenta = {S: 0 for S in combinations(range(n), k)}
for _ in range(reps):
cuenta[tuple(sorted(reservoir(range(n), k, rng)))] += 1
esperado = reps / len(cuenta)
chi2 = sum((c - esperado) ** 2 / esperado for c in cuenta.values())
print(f"{len(cuenta)} subconjuntos de tamaño {k}: frecuencias entre {min(cuenta.values())} y {max(cuenta.values())} (esperado {esperado:.0f})")
print(f"chi cuadrado = {chi2:.1f} con {len(cuenta) - 1} grados de libertad (el 95 % de las veces queda por debajo de 23.7)")
def reservoir_ponderado(stream, k, rng):
"""Efraimidis-Spirakis (A-Res): clave u^(1/w) y se quedan las k mayores."""
H = []
for x, w in stream:
clave = rng.random() ** (1.0 / w)
if len(H) < k:
heapq.heappush(H, (clave, x))
elif clave > H[0][0]:
heapq.heapreplace(H, (clave, x))
return [x for _, x in H]
pesos = [1, 2, 3, 4]
veces = np.zeros(len(pesos))
for _ in range(20000):
veces[reservoir_ponderado(list(enumerate(pesos)), 1, rng)[0]] += 1
print("k = 1, frecuencia de cada elemento:", np.round(veces / 20000, 3), " w / W:", np.round(np.array(pesos) / sum(pesos), 3))Now heavy hitters on a Zipf stream of elements with 99 counters. Space-Saving uses a “lazy” heap: each increment adds a new entry and stale entries are discarded when extracting the minimum.
from collections import Counter
def misra_gries(stream, k):
C = {}
for x in stream:
if x in C:
C[x] += 1
elif len(C) < k:
C[x] = 1
else: # se cancelan k + 1 apariciones distintas
for y in list(C):
C[y] -= 1
if C[y] == 0:
del C[y]
return C
def space_saving(stream, k):
C, heap = {}, [] # montículo perezoso de (cuenta, elemento)
for x in stream:
if x in C:
C[x] += 1
elif len(C) < k:
C[x] = 1
else:
while heap[0][0] != C.get(heap[0][1]): # descarta entradas caducadas
heapq.heappop(heap)
c, y = heapq.heappop(heap)
del C[y]
C[x] = c + 1 # hereda la cuenta del expulsado
heapq.heappush(heap, (C[x], x))
return C
gen = np.random.default_rng(1)
U, s, N = 10_000, 1.1, 100_000
p = 1 / np.arange(1, U + 1) ** s
p /= p.sum()
stream = gen.choice(U, size=N, p=p).tolist()
f = Counter(stream)
k = 99
mg, ss = misra_gries(stream, k), space_saving(stream, k)
err_mg = [f[x] - mg.get(x, 0) for x in f]
err_ss = [ss[x] - f[x] for x in ss]
print(f"Misra-Gries: infraestima como mucho {max(err_mg)} (cota n/(k+1) = {N // (k + 1)}); nunca sobreestima: {min(err_mg) >= 0}")
print(f"Space-Saving: sobreestima como mucho {max(err_ss)} (cota n/k = {N / k:.0f}); nunca infraestima: {min(err_ss) >= 0}")
pesados = [x for x in f if f[x] > N / (k + 1)]
print(f"{len(pesados)} elementos con f > n/(k+1); todos tienen contador en Misra-Gries: {all(x in mg for x in pesados)}")
print(" x f MG SS")
for x, c in f.most_common(5):
print(f"{x:4d} {c:6d} {mg.get(x, 0):6d} {ss.get(x, 0):6d}")
def fusionar_mg(A, B, k):
C = Counter(A) + Counter(B)
if len(C) <= k:
return dict(C)
resta = sorted(C.values(), reverse=True)[k] # la (k+1)-ésima mayor cuenta
return {x: c - resta for x, c in C.items() if c > resta}
M = fusionar_mg(misra_gries(stream[: N // 2], k), misra_gries(stream[N // 2:], k), k)
print(f"fusión de las dos mitades: {len(M)} contadores, error máximo {max(f[x] - M.get(x, 0) for x in f)} (cota {N // (k + 1)})")Misra–Gries underestimates all top positions by the same amount, decrement-step count , here well below bound ; Space-Saving gets top items exactly because it never evicted them. Merging preserves the bound.
A Bloom filter sized for 1% with keys and three ways to choose positions:
import sys
class MultiplyAddShift:
"""h(x) = ((a x + b) mod 2^64) >> 32 para claves de 32 bits: familia fuertemente universal."""
def __init__(self, gen):
self.a, self.b = gen.integers(0, 2**64, size=2, dtype=np.uint64) # a, b uniformes de 64 bits
def __call__(self, x):
x = np.asarray(x, dtype=np.uint64)
return (self.a * x + self.b) >> np.uint64(32) # en [0, 2^32)
def a_rango(h, m):
return (h * np.uint64(m)) >> np.uint64(32) # [0, 2^32) -> [0, m) sin módulo
class Bloom:
def __init__(self, m, k, gen, modo="independientes"):
self.m, self.k, self.modo = m, k, modo
self.bits = np.zeros(m, dtype=bool) # un byte por bit, por claridad
self.h = [MultiplyAddShift(gen) for _ in range(max(k, 2))]
def posiciones(self, x):
if self.modo == "independientes":
return [a_rango(h(x), self.m) for h in self.h[: self.k]]
g1 = a_rango(self.h[0](x), self.m)
if self.modo == "doble": # Kirsch-Mitzenmacher: g1 + i g2
g2 = 1 + a_rango(self.h[1](x), self.m - 1)
return [(g1 + np.uint64(i) * g2) % np.uint64(self.m) for i in range(self.k)]
return [(g1 + np.uint64(i)) % np.uint64(self.m) for i in range(self.k)] # consecutivas: mal
def add(self, x):
for pos in self.posiciones(x):
self.bits[pos] = True
def contiene(self, x):
r = np.ones(np.shape(x), dtype=bool)
for pos in self.posiciones(x):
r &= self.bits[pos]
return r
def dimensionar(n, p):
m = int(np.ceil(-n * np.log(p) / np.log(2) ** 2))
return m, max(1, round(m / n * np.log(2)))
gen = np.random.default_rng(2)
n, objetivo = 100_000, 0.01
m, kb = dimensionar(n, objetivo)
claves = gen.permutation(np.unique(gen.integers(0, 2**32, size=3 * n, dtype=np.uint64)))[: 2 * n] # 2n claves distintas
dentro, fuera = claves[:n], claves[n:]
print(f"n = {n}, objetivo {objetivo}: m = {m} bits ({m / 8 / 1024:.0f} KiB, {m / n:.2f} bits por clave), k = {kb}")
for modo in ["independientes", "doble", "consecutivas"]:
B = Bloom(m, kb, gen, modo)
B.add(dentro)
assert B.contiene(dentro).all() # nunca hay falsos negativos
print(f" {modo:15s} falsos positivos {B.contiene(fuera).mean():.4f} (teoría {(1 - np.exp(-kb * n / m)) ** kb:.4f})")
conjunto = set(dentro.tolist())
bytes_set = sys.getsizeof(conjunto) + sum(sys.getsizeof(x) for x in conjunto)
print(f"memoria: set de Python {bytes_set / 2**20:.1f} MiB frente a {m / 8 / 2**10:.0f} KiB del filtro con los bits empaquetados")Count-min and Count Sketch on a million occurrences of Zipf-distributed elements. Count-min receives the stream in ten blocks, showing block processing equals processing one by one (it is linear):
gen = np.random.default_rng(3)
U, s, N = 100_000, 1.1, 1_000_000
p = 1 / np.arange(1, U + 1) ** s
p /= p.sum()
stream = gen.choice(U, size=N, p=p).astype(np.uint64)
f = np.bincount(stream.astype(np.int64), minlength=U)
class CountMin:
def __init__(self, w, d, gen):
self.w, self.d = w, d
self.h = [MultiplyAddShift(gen) for _ in range(d)]
self.C = np.zeros((d, w), dtype=np.int64)
def _col(self, r, xs):
return a_rango(self.h[r](xs), self.w).astype(np.int64)
def update(self, xs):
for r in range(self.d):
self.C[r] += np.bincount(self._col(r, xs), minlength=self.w)
def query(self, xs):
return np.min([self.C[r, self._col(r, xs)] for r in range(self.d)], axis=0)
def merge(self, otro):
self.C += otro.C # mismas funciones hash: basta sumar
class CountSketch(CountMin):
def __init__(self, w, d, gen):
super().__init__(w, d, gen)
self.g = [MultiplyAddShift(gen) for _ in range(d)] # signos, independientes de las columnas
def _signo(self, r, xs):
return 1 - 2 * (self.g[r](xs) >> np.uint64(31)).astype(np.int64)
def update(self, xs):
for r in range(self.d):
self.C[r] += np.bincount(self._col(r, xs), weights=self._signo(r, xs), minlength=self.w).astype(np.int64)
def query(self, xs):
return np.median([self._signo(r, xs) * self.C[r, self._col(r, xs)] for r in range(self.d)], axis=0)
eps, delta = 1e-3, 1e-2
w, d = int(np.ceil(np.e / eps)), int(np.ceil(np.log(1 / delta)))
cm = CountMin(w, d, gen)
for bloque in np.array_split(stream, 10):
cm.update(bloque)
cs = CountSketch(w, d, gen)
cs.update(stream)
xs = np.arange(U, dtype=np.uint64)
e_cm, e_cs = cm.query(xs) - f, cs.query(xs) - f
print(f"w = {w}, d = {d}: {w * d} contadores frente a {U} elementos del universo")
print(f"count-min: error mínimo {e_cm.min()} (nunca infraestima), medio {e_cm.mean():.1f}, máximo {e_cm.max()}")
print(f" fracción con error > eps N = {eps * N:.0f}: {np.mean(e_cm > eps * N):.4f} (garantía: <= {delta})")
print(f"Count Sketch: error medio {e_cs.mean():+.2f} (insesgado), |error| medio {np.abs(e_cs).mean():.1f}, máximo {np.abs(e_cs).max():.0f}")
print(f"||f||_1 = {N}, ||f||_2 = {np.sqrt((f.astype(float) ** 2).sum()):.0f}")
top = np.argsort(-f)[:10]
raros = np.where((f > 0) & (f <= 5))[0]
for nombre, e in [("count-min", e_cm), ("Count Sketch", e_cs)]:
print(f"{nombre:13s} error relativo medio: 10 más frecuentes {np.mean(np.abs(e[top]) / f[top]):.3%}, elementos con f <= 5 {np.mean(np.abs(e[raros]) / f[raros]):.0%}")The count-min guarantee holds with enormous slack: the theorem allows 1% of elements to exceed while observed maximum error is a few hundred because Markov’s bound is pessimistic. Relative error for elements with is thousands of percent in both sketches: the figure’s noise floor. Count Sketch has lower mean error but higher maximum error because its tails extend both ways.
Finally HyperLogLog with a 64-bit hash. For first-1 position use the bit length of the remaining bits, given exactly by np.frexp because these numbers have fewer than 53 bits and are represented without rounding in float64.
def splitmix64(x):
"""Hash de 64 bits (finalizador de SplitMix64) vectorizado: una biyección de uint64."""
z = np.asarray(x, dtype=np.uint64) + np.uint64(0x9E3779B97F4A7C15)
z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
return z ^ (z >> np.uint64(31))
class HyperLogLog:
def __init__(self, p=14):
self.p, self.m = p, 1 << p
self.M = np.zeros(self.m, dtype=np.uint8)
self.alpha = 0.7213 / (1 + 1.079 / self.m)
def add_hashes(self, h):
q = 64 - self.p
j = (h >> np.uint64(q)).astype(np.int64) # p bits altos: el registro
resto = h & np.uint64((1 << q) - 1) # los 64 - p bits restantes
rho = q - np.frexp(resto.astype(np.float64))[1] + 1 # posición del primer 1
np.maximum.at(self.M, j, rho.astype(np.uint8))
def add(self, xs):
self.add_hashes(splitmix64(xs))
def estimate(self, corregir=True):
E = self.alpha * self.m ** 2 / np.sum(2.0 ** -self.M.astype(float))
V = int(np.sum(self.M == 0))
if corregir and E <= 2.5 * self.m and V > 0:
return self.m * np.log(self.m / V) # conteo lineal
return E
def merge(self, otro):
self.M = np.maximum(self.M, otro.M)
gen = np.random.default_rng(11)
# enteros aleatorios de 62 bits: con n = 10^6, la probabilidad de que dos coincidan es menor que n^2 / 2^63 < 10^-6
print(" n estimación error sin corrección")
for n in [10, 100, 1_000, 10_000, 100_000, 1_000_000]:
xs = gen.integers(0, 2**62, size=n)
H = HyperLogLog(14)
H.add(np.concatenate([xs, xs[: n // 2]])) # con repeticiones
e = H.estimate()
print(f"{n:8d} {e:12.0f} {e / n - 1:+8.2%} {H.estimate(False) / n - 1:+16.1%}")
errores = []
for _ in range(40):
H = HyperLogLog(10)
H.add(gen.integers(0, 2**62, size=50_000))
errores.append(H.estimate() / 50_000 - 1)
print(f"m = 1024, 40 repeticiones con n = 50 000: desviación típica {np.std(errores):.4f}; teoría 1.04/sqrt(m) = {1.04 / 32:.4f}")
todos = gen.integers(0, 2**62, size=1_000_000)
A, B = HyperLogLog(14), HyperLogLog(14)
A.add(todos[:600_000])
B.add(todos[400_000:])
nA, nB = A.estimate(), B.estimate()
A.merge(B)
print(f"unión fusionada: {A.estimate():.0f} (real 1 000 000); intersección por inclusión-exclusión: {nA + nB - A.estimate():.0f} (real 200 000)")
print(f"memoria: {A.m} registros de 6 bits = {A.m * 6 // 8} bytes")Without correction, with 10 elements the raw estimate exceeds ten thousand: the of empty registers. With correction, error is small throughout. Merging two 600 000-element sketches gives the union with usual typical error, but inclusion–exclusion intersection inherits errors of the three terms, about 4900, 4900 and 8100 ( of , and ). Since sketches share elements, errors partly cancel: across 30 seeds, intersection-error standard deviation is about 5000, 2.5% of 200 000. This run had error about 2000, 1%, with some luck. The serious issue is that error scales with set sizes, not intersection size: with intersection 2000 it would still be thousands, larger than the intersection itself.
The final cell measures raw-estimator bias just above the threshold, the reason for HyperLogLog++ correction. With threshold is 2560:
gen = np.random.default_rng(22)
reps = 300
print(" n n/m error medio desviación usa conteo lineal")
for n in [1500, 2300, 2500, 2700, 3000, 3500, 4000, 5000, 8000]:
e, lineal = [], 0
for _ in range(reps):
H = HyperLogLog(10)
H.add(gen.integers(0, 2**62, size=n))
e.append(H.estimate() / n - 1)
lineal += H.estimate() != H.estimate(corregir=False)
print(f"{n:5d} {n / 1024:6.2f} {np.mean(e):+11.2%} {np.std(e):11.2%} {lineal / reps:14.0%}")
print(f"(error estándar de cada media: unos {0.03 / np.sqrt(reps):.2%})")Far from the threshold both estimators are nearly unbiased: linear counting on the left and harmonic mean from roughly . In between, not so. With , in some runs raw estimate falls below and linear counting wins; in others it exceeds it and harmonic mean wins, overestimating in that region: mean rises about 1.4% and deviation grows. Just above, with , harmonic mean overestimates by nearly 2% on average, over half its own 3.25% typical error; bias falls to a few tenths near and vanishes near . A simulation with 8000 repetitions per point (standard error about 0.04 percentage points) gives , , , , and for , , , , and , and for . HyperLogLog++ subtracts that bias using a simulation table.
Streaming log analysis
Now a complete problem: a synthetic 300 000-request web log with three columns (IP, route and status code), read in chunks of 10 000 lines as if arriving over the network. One pass produces distinct IPs with HyperLogLog, most frequent routes with count-min and candidates, and a uniform 1000-line sample using random keys. Strings become integers with pd.util.hash_array, pandas’ vectorized 64-bit hash. Finally pandas calculates exact answers.
import pandas as pd
gen = np.random.default_rng(5)
n_ips, n_rutas, N = 50_000, 300, 300_000
ips = np.array([f"{a}.{b}.{c}.{d}" for a, b, c, d in gen.integers(1, 255, size=(n_ips, 4))])
rutas = np.array([f"/api/recurso/{i}" for i in range(n_rutas)])
actividad = gen.pareto(1.2, n_ips) + 1 # unas pocas IP generan mucho tráfico
p_ruta = 1 / np.arange(1, n_rutas + 1) ** 1.05
log = pd.DataFrame({
"ip": ips[gen.choice(n_ips, size=N, p=actividad / actividad.sum())],
"ruta": rutas[gen.choice(n_rutas, size=N, p=p_ruta / p_ruta.sum())],
"estado": gen.choice([200, 304, 404, 500], size=N, p=[0.86, 0.08, 0.05, 0.01]),
})
def hash64(col):
return pd.util.hash_array(col.to_numpy()) # uint64
def resumir(trozos, semilla):
"""Una pasada: HLL de IP, count-min de rutas con candidatos y muestra bottom-k."""
hll = HyperLogLog(12)
cm = CountMin(2048, 5, np.random.default_rng(6)) # semilla fija: sketches fusionables
candidatos, k_muestra, vistos = {}, 1000, 0
claves, muestra = np.empty(0), log.iloc[:0]
g = np.random.default_rng(semilla)
for trozo in trozos:
vistos += len(trozo)
hll.add_hashes(hash64(trozo["ip"]))
h32 = hash64(trozo["ruta"]) & np.uint64(0xFFFFFFFF) # claves de 32 bits para el count-min
cm.update(h32)
rutas_t, idx = np.unique(trozo["ruta"].to_numpy(), return_index=True)
for r, e, h in zip(rutas_t, cm.query(h32[idx]), h32[idx]):
if e >= 0.005 * vistos: # candidata: más del 0.5 % de lo visto
candidatos[r] = h
claves = np.concatenate([claves, g.random(len(trozo))]) # claves aleatorias: se quedan las k menores
muestra = pd.concat([muestra, trozo])
sel = np.argsort(claves)[:k_muestra]
claves, muestra = claves[sel], muestra.iloc[sel]
return hll, cm, candidatos, muestra
trozos = [log.iloc[i:i + 10_000] for i in range(0, N, 10_000)]
hll, cm, cand, muestra = resumir(trozos, 7)
exacto = log["ip"].nunique()
print(f"IP distintas: HyperLogLog {hll.estimate():.0f}, exacto {exacto} ({hll.estimate() / exacto - 1:+.2%}; error típico {1.04 / 64:.1%})")
vc = log["ruta"].value_counts()
est = {r: cm.query(np.array([h], dtype=np.uint64))[0] for r, h in cand.items()}
top = sorted(est, key=est.get, reverse=True)[:6]
print(f"\n{'ruta':16s} {'count-min':>9s} {'exacto':>7s}")
for r in top:
print(f"{r:16s} {est[r]:9d} {vc[r]:7d}")
print("las 6 más frecuentes coinciden con las exactas:", top == list(vc.index[:6]))
print("\nproporción de cada código de estado:")
print(pd.DataFrame({"muestra (1000)": muestra["estado"].value_counts(normalize=True),
"log completo": log["estado"].value_counts(normalize=True)}).round(3).to_string())With 300 routes and 2048 columns, count-min barely has collisions among frequent routes and estimates are exact or nearly so; HyperLogLog with registers (3 KiB) differs by 2.9%, 1.8 times its 1.6% typical error (in one run a deviation that large or larger occurs about once in fourteen, a useful reminder that typical error is not a maximum); the 1000-line sample reproduces status-code proportions with expected sampling error, order points for 200. The real interest is merging: if the log came from two servers, each with its own summary, the combined result would be identical.
hll1, cm1, cand1, m1 = resumir(trozos[:12], 8) # servidor 1: 120 000 líneas
hll2, cm2, cand2, m2 = resumir(trozos[12:], 9) # servidor 2: 180 000 líneas
hll1.merge(hll2)
cm1.merge(cm2)
print("HLL fusionado idéntico al de una sola pasada:", np.array_equal(hll1.M, hll.M))
print("count-min fusionado idéntico:", np.array_equal(cm1.C, cm.C))
e1, e2 = log.iloc[:120_000]["ip"].nunique(), log.iloc[120_000:]["ip"].nunique()
print(f"IP distintas en la unión: HyperLogLog fusionado {hll1.estimate():.0f}, exacto {exacto}")
print(f"exactos por servidor: {e1} + {e2} = {e1 + e2}, que cuenta dos veces las {e1 + e2 - exacto} IP comunes")Merged HyperLogLog registers and count-min counters are bit-for-bit identical to one pass: merging these two sketches is exact. Exact distinct counts from each server cannot instead be added, because IPs visiting both are counted twice; this makes mergeable sketches useful in databases.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. First case: . What is ?
Step 1 of 4. Why ?
HLL: add(xs) receives an integer array (possibly with duplicates), passes it through splitmix64 and updates registers; estimate() returns the HyperLogLog estimate with and small-cardinality correction (linear counting if and zero registers exist). Use the high bits for the register and position of the first 1 among the remaining , counting from 1. Tests check relative error below 3% at several cardinalities from 500 to 600 000. Vectorize with numpy: a Python loop per element would be too slow.import numpy as np
def splitmix64(x):
"""Hash de 64 bits vectorizado (finalizador de SplitMix64)."""
z = np.asarray(x, dtype=np.uint64) + np.uint64(0x9E3779B97F4A7C15)
z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
return z ^ (z >> np.uint64(31))
class HLL:
def __init__(self, p=14):
self.p = p
self.m = 1 << p
self.M = np.zeros(self.m, dtype=np.uint8)
def add(self, xs):
"""Añade un array de enteros (puede tener repeticiones)."""
h = splitmix64(xs)
# tu código: registro j (p bits altos), rho (primer 1 en los 64 - p bits restantes)
# y M[j] = max(M[j], rho)
def estimate(self):
# tu código: media armónica con alpha_m y corrección para cardinales pequeños
return 0.0Summary
- The streaming model measures memory, per-item time and passes, and guarantees hold for any stream fixed before hash selection. Exact distinct counting costs bits: both approximation and randomness are needed.
- Reservoir sampling maintains a uniform -item sample from an unknown-length stream; random keys make it mergeable, and keys make it weighted.
- Misra–Gries and Space-Saving find every element above (or ) using counters, with error .
- A Bloom filter has no false negatives and false-positive rate , minimized at ; target costs bits per key regardless of key size. Its hashes must be independent and it does not support deletion.
- Count-min guarantees with probability using counters (Markov per row, independence across rows); Count Sketch is unbiased with error (Chebyshev per row, median across rows). Both are random linear projections and their error is additive: unhelpful for rare items.
- HyperLogLog counts distinct items with 6-bit registers and typical error (0.81% with 12 KiB), thanks to the harmonic mean of ; small-cardinality linear counting and HyperLogLog++ bias correction are part of the algorithm.
- Bloom (OR), count-min and Count Sketch (sum), and HyperLogLog (maximum) merge exactly with shared parameters and seeds: hence their importance to approximate analytics in databases and monitoring systems.