Sub topic 6
The (ε, δ) Guarantee
This chapter assumes you can read the sketch from the earlier chapters: a table of d rows and w columns, one hash function per row, an update that increments one counter per row, and a query that returns the minimum of the item's d counters. You should also know expected value and independence from basic probability. Here we state exactly what the sketch promises, check it in code, and mark where the promise stops.
The statement
Let a stream contain non-negative counts. Let a_i be the true count of item i. Let N be the total of all counts so far, so N = Σ a_j. Let â_i be the sketch's estimate. Build the sketch with:
w = ⌈e / ε⌉columnsd = ⌈ln(1/δ)⌉rows- pairwise independent hash functions, chosen independently for each row
Then, for any single item i, two things hold:
â_i ≥ a_i, always. This is the one-sided error from the previous chapter. It is deterministic and does not depend on luck.â_i ≤ a_i + εN, with probability at least1 − δ.
Together, that gives:
a_i ≤ â_i ≤ a_i + εN (upper inequality holds with probability ≥ 1 − δ)ε is the error budget as a fraction of the stream length. δ is the probability that a query exceeds that budget.
Reading the two parameters
- ε (epsilon) is the additive error, measured against the whole stream. With
ε = 0.001andN = 10,000,000, an estimate may be too high by up to 10,000. - δ (delta) is the failure probability. With
δ = 0.01, about 1 query in 100 may exceed the ε budget. Even then the estimate is still never below the true count.
The sketch has two knobs because it has two dimensions. Width w controls how much noise each row contains. Depth d controls how likely it is that every row is noisy at once.
| ε | δ | w = ⌈e/ε⌉ | d = ⌈ln(1/δ)⌉ | Counters (w·d) |
|---|---|---|---|---|
| 0.1 | 0.1 | 28 | 3 | 84 |
| 0.01 | 0.01 | 272 | 5 | 1,360 |
| 0.001 | 0.01 | 2,719 | 5 | 13,595 |
| 0.001 | 10⁻⁶ | 2,719 | 14 | 38,066 |
| 0.01 | 10⁻⁹ | 272 | 21 | 5,712 |
Width grows as 1/ε. Depth grows only as ln(1/δ). Making ε ten times smaller costs about ten times the memory. Making δ a million times smaller costs about 2.7 times more rows (from 5 to 14 in the table). Confidence is cheap, and precision is expensive. The table has no column for the number of distinct items, because the memory does not depend on it.
Why it holds
The full proof appears in a later chapter. Here is the shape of the argument, because it explains what the guarantee covers.
Fix an item i and one row r. The counter that i hashes to holds a_i plus the counts of every other item that collides with i in that row. Call that extra amount X_r:
X_r = Σ over j ≠ i of a_j · [h_r(j) = h_r(i)]With pairwise independent hashing, any other item j lands in the same column as i with probability 1/w. So by linearity of expectation:
E[X_r] = Σ a_j / w ≤ N / w ≤ εN / eX_r is never negative, so Markov's inequality applies:
P(X_r > εN) ≤ E[X_r] / (εN) ≤ 1/eA single row therefore overshoots the budget with probability at most 1/e ≈ 0.37. The query returns the minimum over rows, so it exceeds the budget only if every row does. Rows use independent hash functions, so these events are independent:
P(all d rows overshoot) ≤ (1/e)^d = e^(−d) ≤ δThe last step uses d ≥ ln(1/δ). This is where the formula for d comes from. The formula for w comes from choosing the width so that Markov gives exactly 1/e.
Checking the guarantee empirically
The script below builds a sketch, feeds it a skewed stream, and compares estimates with exact counts. It uses integer items, because Python's hash() of an integer is the integer itself and is stable across processes.
import math
import random
from collections import Counter
class CountMinSketch:
def __init__(self, epsilon, delta, seed=0):
self.w = math.ceil(math.e / epsilon)
self.d = math.ceil(math.log(1 / delta))
self.p = (1 << 61) - 1
rng = random.Random(seed)
self.params = [
(rng.randrange(1, self.p), rng.randrange(0, self.p))
for _ in range(self.d)
]
self.table = [[0] * self.w for _ in range(self.d)]
self.total = 0
def _cols(self, item):
x = hash(item) % self.p
for a, b in self.params:
yield ((a * x + b) % self.p) % self.w
def add(self, item, count=1):
for row, col in zip(self.table, self._cols(item)):
row[col] += count
self.total += count
def estimate(self, item):
return min(row[col] for row, col in zip(self.table, self._cols(item)))
epsilon, delta = 0.01, 0.01
n_items, n_events = 5000, 100_000
rng = random.Random(1)
weights = [1 / (rank + 1) for rank in range(n_items)] # Zipf-like skew
stream = rng.choices(range(n_items), weights=weights, k=n_events)
cms = CountMinSketch(epsilon, delta)
truth = Counter()
for item in stream:
cms.add(item)
truth[item] += 1
budget = epsilon * cms.total
undercounts = 0
violations = 0
worst = 0
for item, true_count in truth.items():
err = cms.estimate(item) - true_count
undercounts += err < 0
violations += err > budget
worst = max(worst, err)
print(f"table: {cms.d} rows x {cms.w} columns")
print(f"budget epsilon*N = {budget:.0f}, worst observed error = {worst}")
print(f"undercounts: {undercounts}")
print(f"items over budget: {violations} of {len(truth)} "
f"({violations / len(truth):.4f}, delta = {delta})")Two results are worth checking. The undercount number must be exactly 0 for every seed and every stream, because that half of the guarantee is deterministic. The fraction of items over budget should be at or below δ. On a skewed stream like this it is usually much lower, often 0. The worst observed error is typically well under the budget. Try epsilon = 0.001 with the same stream and compare the worst error.
What the guarantee does not say
Most misuse of count-min sketches comes from reading the guarantee too generously.
The error is relative to N, not to the item
The bound is εN, an absolute amount that is the same for every item. For a rare item with a_i = 3 in a stream of ten million with ε = 0.001, the estimate could legitimately be 10,003. The relative error is enormous even though the guarantee holds.
For an item that makes up a fraction φ of the stream (a_i = φN), the relative error is at most ε/φ. The sketch is useful for heavy items and weak for the long tail. Choose ε to be well below the smallest frequency you care about. To separate items at 1% of the stream from noise, ε = 0.001 is a sensible starting point and ε = 0.01 is not.
The guarantee is per query
The 1 − δ probability applies to one chosen item. If you query m items, the expected number of violations is up to mδ. For a bound that holds for all n distinct items at once, apply a union bound: each item may fail with probability at most δ/n. That means setting d = ⌈ln(n/δ)⌉. The cost is only logarithmic in n, but it is a different depth from the one in the table above.
The probability is over the hash choice
The randomness is in the choice of hash parameters (a, b). The stream is treated as fixed beforehand. If an adversary can see your hash parameters, or can adapt the stream to your query results, they can force collisions and the bound no longer applies. Keep seeds private in adversarial settings.
The bound needs non-negative counts
The proof uses X_r ≥ 0 for Markov's inequality, and the "never undercounts" property relies on counters only growing. With deletions (the turnstile model, covered in a later chapter), both statements change.
The bound is a worst case
Markov's inequality is loose. The per-row failure bound of 1/e is a ceiling, and real rows on skewed data usually collide with far less than N/w of total weight. Observed errors are often much smaller than εN. Do not shrink the table below the formulas because your test run looks good. The formulas are what you can promise on streams you haven't seen.
Common errors
- Using
Nas the number of distinct items.Nis the sum of all counts. Ten million events over 100 distinct items still givesN = 10,000,000. - Reading
εNas a percentage of the item's count. It is a percentage of the stream. - Using ε and δ as if they were independent of the hash family. Without pairwise independence,
E[X_r] ≤ N/wcan fail. A weak hash, such as taking raw bytes modulow, can break the guarantee on structured keys. - Reusing the same hash for several rows. Rows must be independent for
e^(−d)to hold. Identical rows give the failure probability of a single row,1/e.
Exercise
You need an error of at most 0.05% of the stream length with failure probability at most 0.001. How many columns and rows do you need, and how many counters is that?
Show answer
w = ⌈e / 0.0005⌉ = ⌈5436.56⌉ = 5437 columns. d = ⌈ln(1000)⌉ = ⌈6.908⌉ = 7 rows. Total: 5437 × 7 = 38,059 counters.
Exercise
A sketch with ε = 0.001 has processed N = 2,000,000 events. A query returns an estimate of 1,500 for item X. What can you say about X's true count, and with what certainty?
Show answer
The true count is at most 1,500, with certainty, because estimates never undercount. With probability at least 1 − δ it is also at least 1,500 − εN = 1,500 − 2,000 = −500, which is no information beyond zero. So the true count lies between 0 and 1,500. The sketch cannot tell you that X is frequent. To learn more you would need a smaller ε.
Exercise
Your service queries 10,000 distinct items per minute, each with δ = 0.01. Roughly how many answers per minute may exceed the εN budget, and how would you change the sketch if you wanted all 10,000 to be within budget with probability 0.99?
Show answer
Up to about 10,000 × 0.01 = 100 answers per minute, by the per-query guarantee (the actual number is usually lower, since the bound is a worst case). For a simultaneous guarantee, use a union bound with per-item failure δ/m = 0.01/10,000 = 10⁻⁶, so d = ⌈ln(10⁶)⌉ = 14 rows instead of 5. Width stays the same.