Sub topic 11
Conservative update to reduce overcounting
This chapter assumes you have the CountMinSketch class from the earlier chapters. It has a d by w table of counters, one hash per row, add increments one cell per row, and estimate takes the row minimum. You should also know why the estimate is never below the true count. The chapter changes how add works so the table collects fewer inflated counters. It does not change what estimate does.
Where the overcounting comes from
A standard update adds count to one cell in every row. Rows are independent, so a cell shared by two items receives both items' increments. That sharing is a collision, and collisions are the only source of error.
The standard update does more work than the estimate needs. estimate returns only the smallest of the item's d cells. Suppose one of those cells is already inflated by a heavy neighbour. Adding to it makes it larger, but it will not become the minimum, so the increment has no effect on this item's estimate. It does raise the cell for every other item that shares it, and the extra count stays in the table permanently.
Conservative update, also called conservative counting, avoids those wasted increments. It is a local rule that needs no extra memory and no change to the table layout.
The rule
To add count occurrences of an item:
- Find the item's
dcells, one per row. - Compute
current, the minimum of those cells. This is whatestimatewould return right now. - Compute
target = current + count. This is the smallest value the new estimate can have. - Raise each of the item's cells to
targetif it is lower. Leave any cell that is already at or abovetargetunchanged.
In symbols, each cell becomes max(cell, target).
The cells that actually set the estimate, the smallest ones, get the increment. Cells that were inflated by collisions are left alone as long as they already exceed the target.
A worked example
Take d = 2. An item x maps to one cell in each row. Its true count is 5. The cell in row 0 holds 5, so it has no collisions. The cell in row 1 holds 9, because a heavy item shares it. Now x arrives once more.
| Update rule | Row 0 cell | Row 1 cell | Estimate after |
|---|---|---|---|
| Before the update | 5 | 9 | 5 |
| Standard | 6 | 10 | 6 |
| Conservative | 6 | 9 | 6 |
Both rules give the correct estimate of 6. The standard rule also pushed row 1 from 9 to 10, and that extra 1 now sits in the cell shared with the heavy item. Any other item that maps to that cell and relies on it will see a larger value. The conservative rule computed target = 5 + 1 = 6, saw that 9 already exceeds 6, and did nothing to that cell.
Why it never undercounts
The one-sided error guarantee must survive the change. It does, by an invariant. After every update, for every item y ever seen, each of y's cells holds at least the true count of y.
- Items that were not updated. Their cells can only stay the same or go up, since
max(cell, target)never lowers a cell. The invariant still holds. - The item
xbeing updated. Before the update, all ofx's cells are at leastf(x), its true count. Socurrent >= f(x), andtarget = current + count >= f(x) + count, which is the new true count. Every cell ofxis now at leasttarget, so the invariant holds.
Since the estimate is the minimum of cells that are all at least the true count, the estimate is at least the true count.
Conservative update also never exceeds the standard rule. If you run both on the same stream with the same hash parameters, every cell in the conservative table is at most the corresponding cell in the standard table. Each conservative step raises a cell by no more than the standard step would, so by induction the inequality holds throughout. Therefore:
true count <= conservative estimate <= standard estimateThe (ε, δ) guarantee from the earlier chapter still applies, because the conservative estimate is never worse than the standard one. It is a safe drop-in change. The guarantee does not get tighter. The improvement is empirical, and its size depends on the data.
Code
The class below is the sketch from the earlier chapters with add_conservative added as a method. It uses integer items so that hash() gives the same values on every run.
import math
import random
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 add_conservative(self, item, count=1):
cols = list(self._cols(item))
current = min(self.table[r][c] for r, c in enumerate(cols))
target = current + count
for r, c in enumerate(cols):
self.table[r][c] = max(self.table[r][c], target)
self.total += count
def estimate(self, item):
return min(row[col] for row, col in zip(self.table, self._cols(item)))
# A skewed stream: item 0 is very common, item 999 is rare.
rng = random.Random(42)
items = list(range(1000))
weights = [1 / (rank + 1) for rank in items]
stream = rng.choices(items, weights=weights, k=20000)
truth = {}
for item in stream:
truth[item] = truth.get(item, 0) + 1
standard = CountMinSketch(epsilon=0.05, delta=0.05, seed=1)
conservative = CountMinSketch(epsilon=0.05, delta=0.05, seed=1)
for item in stream:
standard.add(item)
conservative.add_conservative(item)
err_std = err_con = 0
for item, true_count in truth.items():
e_std = standard.estimate(item)
e_con = conservative.estimate(item)
assert true_count <= e_con <= e_std
err_std += e_std - true_count
err_con += e_con - true_count
print("table:", standard.w, "columns,", standard.d, "rows")
print("total overcount, standard: ", err_std)
print("total overcount, conservative:", err_con)The table is deliberately small, 55 columns for 1000 distinct items, so collisions are frequent. The assertion true_count <= e_con <= e_std checks both properties from the previous section for every item. The exact totals depend on the stream, but the conservative total is never larger than the standard one, and on skewed data it is usually clearly smaller.
What it costs and what it breaks
Conservative update reads the item's cells before writing them, so each update does two passes over d cells instead of one. The asymptotic cost is still O(d) per update, but it is a little slower in practice. In a concurrent setting the read-then-write is not atomic. Two threads updating overlapping cells can both read the same minimum and produce a smaller table than a serial run would. That table can then undercount. Use a lock, or shard the sketch per thread and merge afterwards.
Two other consequences follow from the rule:
- The table depends on arrival order. The standard update is commutative: any ordering of the same stream gives the same table. Conservative update is not, because
currentdepends on what came before. Two runs over a shuffled stream can give different tables, though both stay between the true counts and the standard estimates. - Merging is weaker. You can still merge two conservative sketches by adding tables cell by cell, as in the merging chapter. The result is a valid upper bound on the combined counts, and it is no larger than merging two standard sketches. It is not identical to one conservative sketch that saw both streams. The merged table carries each side's collisions, and the cross-stream information that conservative update would have used was never available.
When to use it
Use conservative update when your stream only increases counts and you want tighter estimates for the same memory. Typical cases are heavy-hitter tracking, where the heap compares estimates and benefits from less noise, and network or log analysis with skewed data. The gain is largest when a few items are very frequent and many are rare, because that is when rare items share cells with heavy ones.
Stay with the standard update when you need deletions, when you need the table to be independent of order, or when exact reproducibility across reorderings matters.
Exercise
A sketch has d = 3 rows. An item x has cells holding 12, 40, and 25 before an update. Its true count before the update is 12. A new occurrence of x arrives with count 1. What are the three cells after a standard update and after a conservative update, and what does estimate(x) return in each case?
Show answer
Standard: the cells become 13, 41, and 26, and the estimate is 13. Conservative: current = min(12, 40, 25) = 12, so target = 13. The cells become max(12, 13) = 13, max(40, 13) = 40, and max(25, 13) = 25. The estimate is 13. Both estimates are correct, but the conservative update leaves the cells at 40 and 25 unchanged, so items that share those cells are not inflated.
Exercise
Explain in two or three sentences why conservative update still never returns an estimate below the true count, even though it skips some increments.
Show answer
The skipped increments are only for cells that are already at least as large as the new target, which is the old minimum plus the count. The old minimum was at least the item's old true count, so the target is at least the new true count. After the update, every cell of the item is at least the target, and every other item's cells can only stay the same or increase. So every cell of every item stays at least that item's true count, and the minimum of those cells does too.
Exercise
You run a standard sketch and a conservative sketch with identical dimensions and hash parameters over the same stream. For some item, the conservative estimate is larger than the standard estimate. What can you conclude?
Show answer
There is a bug in the setup or the code. Each conservative cell is at most the corresponding standard cell, so the conservative estimate can never exceed the standard one. Check that both sketches use the same seed and dimensions, that the same stream went into each, and that no update used a negative count.