Structures

A sketch that is allowed to be under

Count-Min's estimate is never below the truth, and it pays for that with an error proportional to the whole stream. Give every key a sign and take a median instead, and the same table is 2.7 times more accurate on the keys anybody asks about — and wrong in both directions.

A Count-Min sketch is a table of counters, dd rows by ww columns, with one hash per row. Every arrival adds one to a cell in each row; a query takes the minimum of its dd cells. Because every cell is a sum of non-negative counts, the estimate is never below the truth — an unconditional property with no probability attached, and the reason six essays of this field lean on it.

Change one thing. Give every row a second hash, sjs_j, which returns ±1\pm 1; on arrival of key xx add sj(x)s_j(x) rather than 11 to cell hj(x)h_j(x) of row jj; on query, take sj(x)s_j(x) times the cell, and report the median over rows rather than the minimum.

That is Count-Sketch, and this essay is what the change costs and what it buys.

Signed error on 200 keys, in the cash register modelEach mark is one key's estimate minus its exact count, so a mark left of the line is an estimate BELOW the truth. The stream is 60,000 updates over 2,048 keys, insertions only, Zipf s = 1.1. Count-Min 4×64 holds 8,192 bits and came back under on 0 of 200 keys, worst under 0 and worst over 630; Count-Sketch 4×64 holds 8,192 bits and came back under on 120 of 200 keys, worst under -873 and worst over 2,569. Count-Min's one-sidedness is a consequence of every cell being a sum of non-negative counts; it survives deletions exactly as long as no count goes below zero, which is a condition on the stream that the structure cannot check and its bound never mentions.Count-Min 4×64exact0 under200 overrms 303Count-Sketch 4×64-2,774-1,38701,3872,774120 under80 overrms 256cash register · insertions only, Zipf s = 1.1 · counts exact8,192 bits each
Fig. 1 Both tables, both 8,192 bits, on the same 60,000-item stream, queried on the same 200 keys. Every mark is one key’s estimate minus its true count. Count-Min’s marks are all on one side of the line, which is its theorem. Count-Sketch’s are on both, and they are closer to it.

What the sign does

In a Count-Min cell, every key that hashes there contributes its own count, positively. The cell holds fxf_x plus a pile of other keys’ counts, so the error is one-sided and its size is the mass of the colliding keys — on average (F1fx)/w(F_1 - f_x)/w, and the minimum over dd rows picks the luckiest of dd such piles.

In a Count-Sketch cell, each colliding key contributes ±fy\pm f_y with the sign its own hash drew. Multiplying back by sj(x)s_j(x) at query time leaves fxf_x plus a signed sum of other keys’ counts, and that sum has mean zero. The estimate is unbiased: too high as often as too low, by an amount whose size is the standard deviation of a signed sum rather than the total of an unsigned one.

That is the same cancellation the tug-of-war estimator runs on, applied one cell at a time. Count-Sketch is a table of tug-of-war registers with a hash deciding which register each key lands in, and the family relationship is exact rather than an analogy: the sum of the squares of a Count-Sketch row is itself an estimate of F2F_2.

The error changes currency

The two error bounds are in different units and that is the whole story.

Count-Min’s additive error is proportional to f1\lVert f \rVert_1, the sum of all the counts — the length of the stream. Count-Sketch’s is proportional to f2\lVert f \rVert_2, the square root of the sum of the squares. On this essay’s stream those are 60,000 and 12,409: the second is 4.84 times smaller than the first, and on a more skewed stream the gap is wider still.

The reason a signed sum is smaller than an unsigned one is that random signs make errors add in quadrature rather than linearly. A thousand keys of count ten sum to 10,000 with plus signs and to about 101000=31610\sqrt{1000} = 316 with random ones.

A 4×32 Count-Min table after 60,000 itemsEach cell is a counter and each row has its own hash, so a key lands in exactly one cell per row — the four ringed cells are where key 0 went. The darker a cell, the larger its count. Key 0 truly occurred 10,202 times; its four cells hold 11,025, 11,280, 11,200, 11,473, and the estimate is the smallest of them, 11,025. Every cell is the key's count plus whatever else collided there, so every cell is an overestimate and the minimum is the least bad one. The whole table is 4,096 bits against 92,184 for an exact counter.hash rowh1h2h3h4h1 → cell 30: 11,025h2 → cell 29: 11,280h3 → cell 19: 11,200h4 → cell 4: 11,473key 0 occurred 10,202 times · the minimum of the four is 11,025 · over by 823the additive bound at this width is e/w × N = 5,0974×32 counters · 4,096 bits · Zipf s = 1.1exact would take 92,184 bits
Fig. 2 The Count-Min table for the same stream, with a queried key’s four cells ringed. Every cell is a sum of counts and none of them can be below the truth — the minimum of four over-estimates is the best of them and is still an over-estimate.

Measured, at equal bits

Eight seeds each, d=4d = 4, w=64w = 64, 8,192 bits apiece, over 60,000 items on 2,004 distinct keys.

Count-Min Count-Sketch
mean absolute error, top 20 keys 300.4 111.5
mean absolute error, all keys 325.3 180.9
mean absolute error, keys occurring once or twice 314.9 156.0
share of queries below the truth 0.0% 48.7%
worst single error 1,971 6,001

The signed sketch is 2.69 times more accurate on the keys anybody asks about, at identical state, and it is worse in exactly one respect: its tail. The largest error over sixteen thousand queries was 6,001 against Count-Min’s 1,971, because a median of four can be dragged by two unlucky rows while a minimum of four is protected by one lucky one.

This is the same shape as the result the previous phase found for Misra-Gries — the structure with the reputation for sophistication is not automatically the accurate one, and the comparison has to be made at equal bits on the question both are built for. Here the sophisticated one does win, and it wins by changing which norm the error is measured against rather than by being cleverer with the same one.

Where the two bounds actually bite

Both structures come with a published guarantee and both guarantees are far above what happens.

Count-Min’s is εf1\varepsilon \lVert f \rVert_1 with ε=e/w\varepsilon = e/w, holding with probability 1ed1 - e^{-d}. At w=64w = 64 and d=4d = 4 that is an error of at most 2,548 with probability 98.2%. The measured mean absolute error is 325 and the worst of sixteen thousand queries is 1,971 — inside the bound, at an eighth of it typically, and with no breach at all where 1.8% were permitted. That is the same loose-and-correct bound the previous phase measured, and it is loose for the same reason: the bound is about the worst arrangement of colliding mass and the arrangement at hand is not the worst.

Count-Sketch’s is stated against f2\lVert f \rVert_2, and which f2\lVert f \rVert_2 matters enormously. The whole vector gives 12,409, so a per-row standard deviation of 12,409/64=1,55112{,}409/\sqrt{64} = 1{,}551; but the norm is dominated by a handful of keys, and a query only suffers from a heavy key when that key lands in the same column, which happens one time in ww.

norm used value per-row spread
the whole vector 12,409 1,551
after the heaviest key 7,064 883
after the ten heaviest 2,258 282
after the fifty heaviest 883 110

The measured mean absolute error is 181, which sits between the fourth row and the third. That is the right reading: a typical query collides with none of the head, so its error is governed by the residual after the head has been removed, and the head only appears in the rare rows where it lands on top of the query. The bound quotes the first row of that table and the behaviour lives in the last two, and the gap between them is not a defect in the bound — it is the difference between a statement about every query and a statement about most of them.

More rows is worse, at a fixed budget

A second measurement, and it is the one most likely to change what somebody does.

Holding the bits fixed at about 8,160 and dividing them between rows and columns:

rows dd columns ww Count-Min error Count-Sketch error
3 85 214.6 85.0
5 51 381.0 128.8
7 37 567.6 129.0
9 28 792.6 167.1

Both structures get worse as rows are added. The reason is arithmetic: the error in a cell falls like 1/w1/w for Count-Min and 1/w1/\sqrt{w} for Count-Sketch, and adding rows at a fixed budget shrinks ww proportionally. Depth buys a failure probability — the chance that every row is unlucky — and width buys accuracy, and at a fixed number of bits the two are in direct competition.

The published advice is usually d=ln(1/δ)d = \lceil \ln(1/\delta) \rceil, which for a one-in-fifty failure probability is four. That is the right rule when δ\delta is what matters. When the mean error is what matters, three rows and a wide table beat nine rows and a narrow one by a factor of three and a half on this stream.

What is actually lost

The one-sidedness is not a decoration and losing it costs three specific things.

An estimate stops being a bound. “This key occurred at most 4,300 times” is a sentence a Count-Min sketch can say and a Count-Sketch cannot. Anywhere the answer feeds a decision that must not under-count — a rate limiter, a quota, an admission control — the one-sided structure is answering the question that was asked and the two-sided one is not.

Filtering becomes probabilistic. A heavy-hitter routine built on Count-Min can discard a key the moment its estimate falls below the threshold, because the estimate is an upper bound and a key below it is genuinely below it. With Count-Sketch that discard is a coin flip near the boundary.

The composition changes. Count-Min estimates can be added, subtracted and compared with confidence about the direction of the resulting error; Count-Sketch estimates cannot, and a chain of them accumulates variance rather than a bias in a known direction.

Against that: 2.69 times the accuracy at equal bits, an unbiased answer that can be averaged over repetitions, a second question — F2F_2 — answered by the same table, and validity in a model where the other structure has no theorem at all. Which of those matters is a property of the application and not of the sketch.

Relative error of the second moment against bits of stateEach point is 16 independent runs of the tug-of-war estimator at one state size, against an exact F2 of 153,983,342 computed by a hash map the estimator never sees. The only difference between the series is where the ±1 signs come from: a polynomial of degree 4 (stated degree 4). The mean of the estimator is right as soon as two distinct keys' signs are independent; the variance is a statement about four at a time, which is what the separation between these lines is. Both axes are logarithmic. Model: cash register, one pass, no deletions.10,0000.1bits of state heldrelative error, rms over runsdegree 4F2 = 153,983,342 exactly · 16 runs per point · cash-register model5.7% at 16,384 bits
Fig. 3 The second question the same bits answer. A Count-Sketch of 5×1285 \times 128 cells estimates F2F_2 to 2.6% at 20,480 bits; the dedicated tug-of-war construction drawn here reaches 3.3% on the same budget. One table, two questions, and no separate structure for the second.

The rare key is hopeless either way

Both structures answer well about heavy keys and neither answers usefully about light ones, and the arithmetic makes that unavoidable rather than fixable.

This stream has 136 keys that occurred exactly once. Count-Min’s mean absolute error on the light keys is 314.9 and Count-Sketch’s is 156.0, so the answers are “about 315” and “about ±156” for a true answer of one. In relative terms those are 31,000% and 15,600% wrong, and halving a number like that changes nothing about what can be done with it.

The reason is structural. Both errors are a fraction of a norm of the whole vector, and neither norm knows anything about the key being queried. A structure whose error is a fixed number of counts is useful exactly for keys whose counts are much larger than that number, and the set of such keys is what “heavy hitter” means. Anybody wanting per-key accuracy for rare keys is asking for a structure whose state grows with the number of distinct keys, which is the exact counter table and costs 92,184 bits here.

This is worth saying plainly because the two structures’ relative merits are often argued about as though a better one would answer both. Neither does, the improvement measured above is real and is confined to keys where the answer was already usable, and the honest summary is that Count-Sketch moves the threshold at which a key becomes answerable down by a factor of about 2.7.

Why a median and not a mean

Averaging the dd rows would also be unbiased and would have lower variance than any single row. The median is used instead, and the reason is the tail rather than the centre.

A row’s error is a signed sum of colliding counts. Occasionally a heavy key collides with the queried key and that row’s error is enormous — not a small perturbation but a term of size fheavyf_{\text{heavy}}. An average includes that term with weight 1/d1/d; a median discards it entirely, provided fewer than half the rows are affected. Since a given heavy key collides with the query in each row independently with probability 1/w1/w, the chance that it lands on more than half the rows is astronomically small.

So the median is doing the same job it does in the median-of-means construction: converting a bound on a typical error into a bound on the failure probability, by requiring a majority of independent things to go wrong at once.

The general turnstile model is where the one-sidedness stops being free, and it is worth drawing because nothing about the structure changes: the same tables, the same bits, the same queries.

Signed error on 200 keys, in the general turnstile modelEach mark is one key's estimate minus its exact count, so a mark left of the line is an estimate BELOW the truth. The stream is 60,000 updates over 2,048 keys, insertions and deletions, counts may go negative. Count-Min 4×64 holds 8,192 bits and came back under on 184 of 200 keys, worst under -161 and worst over 13; Count-Sketch 4×64 holds 8,192 bits and came back under on 99 of 200 keys, worst under -54 and worst over 39. Count-Min's one-sidedness is a consequence of every cell being a sum of non-negative counts; it survives deletions exactly as long as no count goes below zero, which is a condition on the stream that the structure cannot check and its bound never mentions.Count-Min 4×64exact184 under16 overrms 42Count-Sketch 4×64-174-8708717499 under101 overrms 13general turnstile · insertions and deletions, counts may go negative · counts exact8,192 bits each
Fig. 4 Sixty thousand updates over 2,048 keys with insertions and deletions and counts allowed to go negative. Count-Min came back under the truth on 184 of 200 keys — worst under −161 against a worst over of 13 — while Count-Sketch was under on 99. The one-sidedness is a consequence of every cell being a sum of non-negative counts, and it survives deletions exactly as long as no count goes below zero: a condition on the stream that the structure cannot check and its bound never mentions.

Squeezing the table the other way makes the same point from the opposite end. A narrow table piles more keys into every cell, so the collision term grows and the sign is what decides whether it adds or cancels.

Signed error on 150 keys, in the cash register modelEach mark is one key's estimate minus its exact count, so a mark left of the line is an estimate BELOW the truth. The stream is 60,000 updates over 2,048 keys, insertions only, Zipf s = 1.1. Count-Min 4×16 holds 2,048 bits and came back under on 0 of 150 keys, worst under 0 and worst over 3,383; Count-Sketch 4×16 holds 2,048 bits and came back under on 70 of 150 keys, worst under -1,846 and worst over 3,260. Count-Min's one-sidedness is a consequence of every cell being a sum of non-negative counts; it survives deletions exactly as long as no count goes below zero, which is a condition on the stream that the structure cannot check and its bound never mentions.Count-Min 4×16exact0 under150 overrms 1,783Count-Sketch 4×16-3,654-1,82701,8273,65470 under80 overrms 815cash register · insertions only, Zipf s = 1.1 · counts exact2,048 bits each
Fig. 5 Sixteen columns rather than sixty-four — 2,048 bits, a quarter of the budget above, about 125 keys sharing every cell. Count-Min is under on none of the 150 keys and over by as much as 3,383; Count-Sketch is under on 70 of them, worst under −1,846 and worst over 3,260. The same collisions, signed, are a spread around the truth rather than a one-sided pile on top of it.

What the sign costs to compute

The signed sketch evaluates two hash functions per row rather than one — a position and a sign — so its work per arrival is double at the same shape. On the measurements above that is eight evaluations per item against four.

Two things make it less than it sounds. The sign needs only one bit, so it can be taken from a spare bit of a wider hash rather than from a second function; and the degree required is two rather than four, because the variance being bounded here is that of a sum over the keys in one column rather than over the whole stream. Implementations that take the sign from the high bit of the same multiply that produced the column are exactly as accurate on the streams measured here, and this file keeps them separate because a shared source is one more thing whose independence would have to be argued rather than assumed.

The comparison worth carrying is the one from the previous essay’s accounting: the plain tug-of-war construction shows every arrival to every register, at 640 evaluations an item for its largest setting. A Count-Sketch of the same 20,480 bits shows each arrival to five, and answers per-key questions the other cannot. That is what hashing to a column rather than broadcasting buys, and it is why the plain estimator is a teaching device and the table is what runs.

Signed error on 150 keys, in the cash register modelEach mark is one key's estimate minus its exact count, so a mark left of the line is an estimate BELOW the truth. The stream is 60,000 updates over 2,048 keys, insertions only, Zipf s = 1.1. Count-Min 3×128 holds 12,288 bits and came back under on 0 of 150 keys, worst under 0 and worst over 441; Count-Sketch 3×128 holds 12,288 bits and came back under on 104 of 150 keys, worst under -418 and worst over 2,994. Count-Min's one-sidedness is a consequence of every cell being a sum of non-negative counts; it survives deletions exactly as long as no count goes below zero, which is a condition on the stream that the structure cannot check and its bound never mentions.Count-Min 3×128exact0 under150 overrms 125Count-Sketch 3×128-3,234-1,61701,6173,234104 under46 overrms 260cash register · insertions only, Zipf s = 1.1 · counts exact12,288 bits each
Fig. 6 Three rows and 128 columns rather than four and 64 — half again the bits, arranged the way the sweep above says is better. Both structures improve and the gap between them holds.

A bias does not average out and a variance does

The unbiasedness is listed above as one item among four, and it has a consequence large enough to decide which structure a system should hold when the answers are going to be combined rather than read one at a time.

Ask both structures about two hundred keys and add the answers up. Count-Min is high by about 300 on each, in the same direction every time, so the total is high by about 60,000 — the biases add. Count-Sketch is off by about 180 on each with a sign that is as likely one way as the other, so the errors partly cancel and the total is off by about 1802002,500180\sqrt{200} \approx 2{,}500. A factor of twenty-four, on a quantity neither structure was asked about directly.

That matters because aggregates over many estimates are extremely common and rarely recognised as a different question. Summing the estimated counts of a group of keys; computing an entropy or a Gini coefficient from estimated frequencies; taking a weighted average; reporting what share of traffic a category accounts for — every one of those adds up many per-key answers, and every one of them turns a one-sided error into a systematic error that grows linearly in the number of terms.

The general rule is worth stating in that form. A bias survives averaging and a variance does not, so a structure whose error is one-sided is the right one for a single question with a direction attached and the wrong one for a sum. Count-Min’s over-estimate is a feature when the caller wants “at most”, and it is the whole of the error when the caller wants a total.

And it runs the other way for repetitions of the same query. Independent Count-Sketch tables over the same stream can be averaged, and their answers converge on the truth as 1/r1/\sqrt{r}; independent Count-Min tables averaged converge on the truth plus the bias, and no amount of repetition removes it. What Count-Min does with repetition is take a minimum, which sharpens the bound and does not remove the direction.

The repair that trades the property the last section is about

There is a change to Count-Min that recovers much of the accuracy gap, keeps the one-sidedness, and gives up the thing the next section says is the important one. Having all three facts together is what makes it a decision rather than an improvement.

Conservative updating. On an arrival, instead of incrementing all dd cells, compute their current minimum and increment only the cells that are at it. The estimate is still an upper bound — the minimum still contains the key’s own count plus a non-negative pile — and the piles grow more slowly, because a cell that is already large stops accumulating.

It is a real improvement and it is cheap: one extra pass over the same dd cells that were being touched anyway.

What it costs is linearity. The update rule now depends on the table’s current contents, so the state is no longer a function of the net frequency vector alone — two sequences of updates with the same sum produce different tables. And with linearity go all three of its consequences: the sketches cannot be merged by adding them, the structure has no meaning in a turnstile model where updates may be negative, and the table built on a stream is not the table built on its shuffle.

So the three-way choice is:

accurate on heavy keys one-sided linear
Count-Min worst yes yes
Count-Min, conservative better yes no
Count-Sketch best no yes

Each row gives up exactly one of the three, and there is no row that has all of them. That is the shape this collection keeps finding when a structure looks strictly better than another — the improvement is real and it is paid for on an axis the comparison was not measuring.

The property that survives every model

There is one thing both structures have that this essay has not used, and the next essay is entirely about it.

Both are linear. Their state is the sum of the updates applied to it, so the table after a sequence of updates is a function of the net frequency vector and of nothing else — not of the order, not of the number of updates, not of how much was inserted and then taken away. That is what makes them mergeable, and it is what makes them work when updates are allowed to be negative.

Count-Min’s one-sidedness does not survive that generalisation and its linearity does. Count-Sketch’s guarantee, which was never about a direction, survives intact. Which is a strange sort of advantage: the structure that promised less has less to lose.

Signed error on 200 keys, in the strict turnstile modelEach mark is one key's estimate minus its exact count, so a mark left of the line is an estimate BELOW the truth. The stream is 60,000 updates over 2,048 keys, insertions and deletions, no count below zero. Count-Min 4×64 holds 8,192 bits and came back under on 0 of 200 keys, worst under 0 and worst over 100; Count-Sketch 4×64 holds 8,192 bits and came back under on 108 of 200 keys, worst under -184 and worst over 1,754. Count-Min's one-sidedness is a consequence of every cell being a sum of non-negative counts; it survives deletions exactly as long as no count goes below zero, which is a condition on the stream that the structure cannot check and its bound never mentions.Count-Min 4×64exact0 under200 overrms 15Count-Sketch 4×64-1,894-94709471,894108 under92 overrms 179strict turnstile · insertions and deletions, no count below zero · counts exact8,192 bits each
Fig. 7 The same two structures on a stream with deletions that never take a count below zero. Count-Min is still never under — its theorem survives this model exactly — and Count-Sketch is still on both sides. Nothing visible has changed, which is the last moment at which that is true.

What this makes readable

Essays that name this one as a prerequisite.

Named alongside this one

Essays reaching for the same objects. Nobody chose these; they are what the concept index makes visible.

What links here

Every essay whose body links to this one.

The objects this essay names

Each one links to every other essay that touches it.

Additive errorCount-Min sketchCount-SketchEstimatorHeavy hitterLinear sketchMedian of meansOne-sided errorSecond frequency momentSketchState bitsTug-of-warUnbiased estimatorZipf distribution