Two Tables, Two Different Error Stories
Suppose a service records events such as account increments, and must estimate any account frequency without storing every key. Hashing saves memory by letting keys share counters, but sharing creates collision noise. Count-Min Sketch (CMS) and Count Sketch use several independently hashed rows to control that noise. Their tables look similar; their error stories are different.
Think of estimating red marbles in shared boxes. CMS puts only positive quantities into a box. A box containing the red marbles reports the truth or too much, never too little, so the least contaminated box is useful. Count Sketch gives every key a reproducible plus or minus sign. Unrelated contributions can cancel, so a row may be high or low; the median rejects extreme rows.
Let \(f_a=5,f_b=2,f_c=1\). If a CMS row hashes \(a\) and \(b\) together, its estimate for \(a\) is \(7\). A second row isolating \(a\) gives \(5\), and the minimum is exact. In Count Sketch, suppose \(a\) has sign \(+1\) and colliding \(b\) has sign \(-1\). That row gives \(3\); another could give \(7\). Their errors are centered around \(5\), and the median across rows is the robust aggregator.
This deep dive builds on frequency estimation: a stream defines a frequency vector \(f\), and a sketch stores a compact summary. A cash-register stream has nonnegative increments. A strict turnstile stream allows deletions but keeps every current frequency nonnegative. A general turnstile stream permits signed frequencies. Standard CMS one-sided error needs nonnegative collision mass; Count Sketch naturally handles signed coordinates. Conservative update increments only CMS counters currently supporting the minimum and can improve empirical error, but it changes linearity and merge behavior. Signed hashing is Count Sketch's independent map \(s_r:U\to\{-1,+1\}\). An inner product \(\langle f,g\rangle=\sum_i f_i g_i\) connects signed sketches to similarity and second-moment methods.
Count-Min keeps nonnegative collision mass and takes a minimum, producing a one-sided \(\ell_1\)-scaled error; Count Sketch randomizes collision signs and takes a median, producing a two-sided \(\ell_2\)-scaled error. The aggregation rule is justified by the noise model, not by the table shape.
| Concept | Intuitive meaning | Exact example | Non-example or boundary | Main assumption | Question answered |
|---|---|---|---|---|---|
| Cash-register stream | Counts only accumulate | \((a,+3),(b,+1)\) | A deletion \((a,-1)\) | Every update is nonnegative | Is collision noise only additive? |
| Strict turnstile | Deletions occur but counts stay nonnegative | \(+5,-2\) leaves \(f_a=3\) | A queried state with \(f_a=-1\) | Current frequency vector is nonnegative | Can CMS retain one-sidedness? |
| General turnstile | Coordinates may be signed | \(f_a=-4,f_b=7\) | Insertion-only clicks | Signed arithmetic has meaning | Is a signed estimator required? |
| Collision noise | Other keys occupy the queried bucket | CMS row gives \(5+2=7\) | A collision-free exact map | Suitable hash distribution | What creates point error? |
| Conservative update | Raise only counters at the current CMS minimum | \(5,7,5\to6,7,6\) | Incrementing every row | Usually insertion-only | Can observed CMS bias shrink? |
| Signed hashing | Stable random \(\pm1\) per key and row | \(5-2=3\) | Reusing the update sign | Unbiased, sufficiently independent signs | Can noise cancel in expectation? |
| Median | Middle row estimate | Median of \(3,5,11\) is \(5\) | Arithmetic mean | A majority of rows are good | How is success amplified? |
| Inner product | Sum coordinatewise products | \(\langle(2,1),(3,-1)\rangle=5\) | Concatenating vectors | Common coordinate universe | How does the idea extend? |
Two Tables, Two Different Error Stories
The exact frequency is \(6\). CMS row counters are \(9,6,8\); Count-Sketch signed row estimates are \(9,3,6\).
- CMS gives \(\min(9,6,8)=6\). Checkpoint: each row is at least the truth because collision mass is nonnegative.
- Count Sketch gives \(\operatorname{median}(9,3,6)=6\). Checkpoint: row errors appear on both sides.
- Perturb the second CMS row with a signed collider of \(-4\), making it \(2\). The minimum becomes \(2\), disproving one-sidedness for general turnstile data.
- Expected result: both aggregators can be exact, but their proof obligations differ.
Reflection: if deletions occur but all frequencies remain nonnegative, which invariant must hold exactly when the query is answered?
Minimum Counters and Median Signed Rows
Let \(U\) be the key universe, \(f\) the final frequency vector, \(w\) the width, and \(d\) the depth. Row \(r\) has a bucket hash \(h_r:U\to\{0,\ldots,w-1\}\). CMS adds update \(\Delta\) to \(C_{r,h_r(i)}\). For a nonnegative vector, \[ C_{r,h_r(i)}=f_i+X_r,\qquad X_r=\sum_{j\ne i:h_r(j)=h_r(i)}f_j\ge0. \] Therefore \(\widehat f_i^{CMS}=\min_r C_{r,h_r(i)}\ge f_i\). With pairwise-independent uniform bucket hashes, \[ \mathbb E[X_r]\le\frac{\lVert f\rVert_1}{w}. \] Choose \(w=\lceil e/\varepsilon\rceil\). Markov's inequality gives \(\Pr[X_r\ge\varepsilon\lVert f\rVert_1]\le1/e\). Independent rows make the probability that all \(d\) rows fail at most \(e^{-d}\). With \(d=\lceil\ln(1/\delta)\rceil\), \[ f_i\le\widehat f_i^{CMS}\le f_i+\varepsilon\lVert f\rVert_1 \] with probability at least \(1-\delta\).
Count Sketch also has an unbiased sign hash \(s_r:U\to\{-1,+1\}\). It stores \(C_{r,h_r(i)}\leftarrow C_{r,h_r(i)}+s_r(i)\Delta\). The corrected row estimate is \[ Y_r=s_r(i)C_{r,h_r(i)} =f_i+\sum_{j\ne i:h_r(j)=h_r(i)}s_r(i)s_r(j)f_j. \] Suitable pairwise-independent signs make the collision terms mean zero, so \(\mathbb E[Y_r]=f_i\), and cross terms vanish: \[ \operatorname{Var}(Y_r)\le\frac{\lVert f_{-i}\rVert_2^2}{w}. \] For \(w=\lceil3/\varepsilon^2\rceil\), Chebyshev gives \(\Pr[|Y_r-f_i|\ge\varepsilon\lVert f_{-i}\rVert_2]\le1/3\). With an odd \(d=\Theta(\log(1/\delta))\) of independent rows, a Chernoff amplification shows that the median is accurate with probability at least \(1-\delta\). Exact depth constants depend on the selected tail bound and should be documented.
CMS uses positivity plus Markov and needs at least one good row. Count Sketch uses cancellation plus variance and needs a majority of good rows. Taking a minimum of signed estimates is a boundary-case error: more rows create more chances for a negative extreme. Using a median for ordinary CMS discards the standard “one clean row” argument and can retain unnecessary positive collision mass.
flowchart TD
A[Frequency vector and point query] --> B{Collision mass nonnegative?}
B -->|yes| C[CMS row is frequency plus noise]
C --> D[Expected noise bounded by l1 over width]
D --> E[Markov gives one good row]
E --> F[Independent rows plus minimum]
F --> G[One-sided epsilon l1 bound]
B -->|no| H[Add independent random signs]
H --> I[Count-Sketch row is unbiased]
I --> J[Variance bounded by l2 squared over width]
J --> K[Chebyshev gives good-row probability]
K --> L[Independent rows plus median]
L --> M[Two-sided epsilon l2 bound]
B -->|ignored| N[Minimum may underestimate]
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
class A,B navy;
class C,D,E,F,G teal;
class H,I,J,K,L,M purple;
class N crimson;
CMS with \(w=\lceil e/\varepsilon\rceil\) and \(d=\lceil\ln(1/\delta)\rceil\) gives \(f_i\le\widehat f_i\le f_i+\varepsilon\lVert f\rVert_1\) for nonnegative frequencies. Count Sketch uses \(w=\Theta(1/\varepsilon^2)\), signed hashes, and \(d=\Theta(\log(1/\delta))\) to obtain two-sided \(O(\varepsilon\lVert f_{-i}\rVert_2)\) error; the independence contract is part of the theorem.
One-Sided Bias versus Unbiased Noise
Let \(f_q=10\), with other frequencies \(6,3,1\). If \(q\) collides with the \(3\) and \(1\), one CMS row reports \(14\), an error of \(+4\). If Count-Sketch signs are \(s(q)=+1,s(3)=-1,s(1)=+1\), that row reports \(8\), an error of \(-2\). Fresh signs could report \(12\); over valid sign randomness, the errors cancel in expectation.
Count Sketch does not always dominate. For nonnegative traffic and a loose \(\ell_1\) budget, CMS uses width proportional to \(1/\varepsilon\), preserves a valuable upper-estimate invariant, and is simple. Count Sketch needs width proportional to \(1/\varepsilon^2\) for the basic point bound, but \(\ell_2\) may be far smaller than \(\ell_1\) for a heavy-tailed residual, and signed updates do not invalidate it.
Both guarantees are probabilistic. Weak hashes, adversarial knowledge of seeds, correlated rows, integer overflow, or inconsistent key encoding break their premises. Merge tables only when width, depth, hashes, seeds, counter type, and sign convention match. Standard tables are linear and merge by counterwise addition; conservative-update CMS is not generally linear, so separately built conservative sketches cannot be blindly added and treated as an equivalent stream sketch.
One-Sided Bias versus Unbiased Noise
Let \(f_a=8,f_b=5,f_c=2\), and query \(a\) across three rows.
- CMS collision sets are \(\{b\},\{c\},\varnothing\). Row estimates are \(13,10,8\); the minimum is \(8\).
- Count-Sketch collision errors are \(+5,-2,0\). Row estimates are \(13,6,8\); the median is \(8\).
- The exact map independently confirms \(f_a=8\). Both happen to be exact for different reasons.
- Perturb \(f_c\) to \(-6\). Its CMS-like row becomes \(2\), so the minimum of \(13,2,8\) underestimates. Count Sketch remains unbiased under fresh valid hashes, although its variance changes.
Checkpoint: write collision error beside every row before aggregation. Expected conclusion: minimum follows from error sign; median follows from a majority of bounded absolute errors.
| Variant | Assumptions | Width and depth | Guarantee or role | Cost | Strength | Failure mode | Prefer when |
|---|---|---|---|---|---|---|---|
| Standard CMS | Nonnegative frequencies; pairwise buckets; independent rows | \(w=\lceil e/\varepsilon\rceil,d=\lceil\ln(1/\delta)\rceil\) | One-sided additive \(\varepsilon\lVert f\rVert_1\) | \(O(d)\) update/query | Compact upper estimate | Signed collision mass or adversarial hashes | Positive counts and upper-bound decisions |
| Conservative CMS | Usually insertion-only; common policy | Same shape; empirical error often smaller | Heuristic improvement | \(O(d)\) | Fewer needless increments | Loses simple linear merge behavior | Centralized pipeline without arbitrary merges |
| Count Sketch | Signed frequencies; unbiased signs; suitable independence | \(w=\Theta(1/\varepsilon^2),d=\Theta(\log(1/\delta))\) | Two-sided \(O(\varepsilon\lVert f_{-i}\rVert_2)\) | \(O(d)\) update/query | Turnstile support; heavy-tail friendly | Correlated signs, overflow | Signed deltas and l2-sensitive queries |
| Exact map | Any representable updates | One entry per distinct key | Exact oracle | Expected \(O(1)\) | Auditable truth | Memory grows with cardinality | Small domains and sampled validation |
| Misra-Gries | Positive updates | \(O(1/\varepsilon)\) labeled counters | Deterministic candidates | Usually \(O(1)\) amortized | No collision probability | Not signed point estimation | Frequent-item candidate discovery |
Choosing for Heavy Tails and Signed Updates
For teaching positive word counts, CMS makes the direction of error visible: collisions only add, and a minimum chooses the least polluted row. Pair it with an exact dictionary so learners can label collision mass.
For professional telemetry with additions and retractions, Count Sketch is preferable if coordinates may become negative. Compatible regional tables add counterwise, representing the sum of streams. In a heavy tail, its residual \(\ell_2\) scale may remain useful even when total absolute traffic is enormous. The deployment must version width, depth, seeds, hash algorithm, sign convention, key encoding, and counter width.
CMS can be preferable when a network guardrail wants an upper estimate of nonnegative request counts and false positives are safer than false negatives. Exact follow-up can verify alerts. Conservative update may reduce false positives centrally, but should be rejected if arbitrary linear merging is required.
An attacker who learns fixed hashes can manufacture colliding keys. A theorem over random hashes does not protect against adaptive inputs after bucket mappings are exposed. Keyed hashing, seed rotation, rate limiting, exact follow-up, and collision telemetry belong at the trust boundary. Systematic normalized bias, excessive empirical failures, correlated rows, counter saturation, or header mismatch are evidence to reject or resize the design.
flowchart TD
A[Define query and cost of error] --> B{Can a frequency be negative?}
B -->|yes| C[Evaluate Count Sketch]
B -->|no| D{Need one-sided upper estimate?}
D -->|yes| E[Evaluate CMS]
D -->|no| F[Compare l1 and l2 budgets]
F --> C
F --> E
C --> G[Choose dimensions hashes and counters]
E --> G
G --> H[Validate on exact sampled windows]
H --> I{Bias failures and memory acceptable?}
I -->|no| J[Reject resize or change method]
I -->|yes| K[Version contract and deploy]
K --> L[Monitor drift correlation and saturation]
L --> M{Assumptions hold?}
M -->|yes| L
M -->|no| J
classDef navy fill:#17365D,color:#fff,stroke:#17365D;
classDef teal fill:#147D84,color:#fff,stroke:#0D565B;
classDef purple fill:#6C3BAA,color:#fff,stroke:#472675;
classDef crimson fill:#C6284D,color:#fff,stroke:#861B35;
class A,B,D,F navy;
class C,E,G purple;
class H,K,L teal;
class I,J,M crimson;
Choosing for Heavy Tails and Signed Updates: Count-Min versus Count Sketch
Scenario: a commerce platform receives \(2\times10^8\) product-event updates per hour across 24 regions. Refunds generate negative deltas, some coordinates become negative, and the vector is heavy-tailed. The target is normalized absolute error below 2% of measured \(\ell_2\) residual for 99% of audited queries.
- Reject the standard CMS theorem because the stream is general turnstile; evaluate Count Sketch and keep an exact stratified sample.
- Select odd depth, benchmark width, use signed 64-bit counters, independent row seeds, keyed stable hashing, and versioned key encoding.
- Replay 30 windows. Measure \(|\widehat f_i-f_i|/\lVert f_{-i}\rVert_2\), signed bias, failure fraction, headroom, and row-error correlation for head and tail keys.
- Verify that adding regional tables equals sketching the concatenated stream, and reject every metadata mismatch.
- Stress crafted identifiers without revealing seeds to producers.
- Deploy only if the 99th percentile meets 2%, bias is centered, counters have safe headroom, and exact audits pass. Otherwise increase memory, improve hashing, or use exact counting for the affected tier.
Cross-Check Count-Min and Count Sketch
Mastery means reconstructing each estimator from its collision decomposition. First define the three stream models, collision noise, signed hashing, and conservative update. Then manually update two rows for four keys and label every collision. Derive CMS expected noise and identify where nonnegativity and row independence enter. Expand Count-Sketch variance and justify why cross terms disappear. Finally compare many deterministic simulation seeds with an exact oracle.
For debugging, reuse the same hash in every row, use an unsigned Count-Sketch counter, force overflow, and merge different seeds. Name the broken invariant in each case. For comparison, construct flat and heavy-tailed vectors with equal \(\ell_1\) norm, compute their residual \(\ell_2\) norms, and compare useful error scales. For extension, prove counterwise merge linearity and investigate inner-product estimation; contrast this with conservative CMS.
Completion is measurable: formulas name their probability space; bounds state \(\varepsilon,\delta,w,d\); experiments have exact oracles; merges verify metadata; and production recommendations name evidence that would reverse them. This bridges frequency estimation to heavy hitters, second moments, inner products, and turnstile algorithms.
Practice: Cross-Check Count-Min and Count Sketch
Use \(f=(12,7,3,-2)\) for keys \(a,b,c,d\), bucket maps \(h_1=(0,0,1,1)\), \(h_2=(1,0,1,0)\), and signs \(s_1=(+,-,+,-)\), \(s_2=(+,+,-,-)\). Add an independently designed third row for a median.
- Recall (2): classify the stream and explain why standard CMS one-sidedness is unavailable.
- Trace (4): build counters and query \(a,d\); show totals, sign correction, and collision noise.
- Proof (5): derive CMS expectation and Count-Sketch mean and variance. Hint: expand the squared signed sum.
- Verify (4): run 50 seeds and report bias, median absolute error, maximum error, and failure fraction.
- Debug (3): force one bucket and identical row hashes; explain why depth no longer amplifies confidence.
- Compare (3): test flat and heavy-tailed vectors with equal \(\ell_1\), then compare residual \(\ell_2\).
- Stretch (4): prove compatible table addition equals sketching summed vectors; explain why conservative update needs separate merge analysis.
Rubric: 22–25 professional judgment; 17–21 correct with minor proof gaps; 12–16 revisit assumptions; below 12 retrace collision decompositions. Include absent key, zero vector, one massive key, negative coordinate, width one, counter limit, and mismatched seed. Reflection: is false-positive overestimation or two-sided error costlier in your system?
Choose CMS when frequencies are nonnegative and a compact one-sided \(\ell_1\) upper estimate matches the decision cost; choose Count Sketch when signed updates or an \(\ell_2\)-scaled two-sided estimate matches the data. Never transfer minimum, median, conservative update, or mergeability across variants without rechecking the collision model, independence, and counter range.