TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Heavy Hitters in Turnstile Streams

Heavy Hitters in Turnstile Streams

Misra-Gries and Space-Saving find heavy hitters deterministically, but only in insertion-only streams. With deletions, an item that was heavy and then lost most of its occurrences must disappear from the answer, and an item that rose late must appear, and no counter-based summary can track that. Linear sketches can: count-min and Count-Sketch estimate any frequency at any time. What they lack is a way to find the heavy items without querying all nn of them. This lesson adds that piece, the dyadic hierarchy, and with it answers range and quantile queries in turnstile streams as well.

The problem

In the strict turnstile model (f≥0f \ge 0 at query time) with ∥f∥1=∑ifi\lVert f \rVert_1 = \sum_i f_i, report every item with fx≥ϕ∥f∥1f_x \ge \phi \lVert f \rVert_1 and no item with fx<(ϕ−ε)∥f∥1f_x < (\phi - \varepsilon)\lVert f \rVert_1, with probability 1−δ1 - \delta. Note that ∥f∥1\lVert f \rVert_1 is easy here: in the strict turnstile model it is the sum of all updates, one counter.

A single count-min sketch answers "is xx heavy?" for a given xx, but there are nn candidates. Querying all of them takes Θ(n)\Theta(n) time, and a union bound over nn queries forces d=Θ(log⁡(n/δ))d = \Theta(\log(n/\delta)) rows. With insertions only, the arriving item is the natural candidate; with deletions, an item can become heavy by other items being deleted, at a moment when it does not arrive at all.

The dyadic hierarchy

Let n=2Ln = 2^L. A dyadic interval at level ℓ\ell is a block [p 2ℓ,(p+1)2ℓ−1][p\,2^\ell, (p+1)2^\ell - 1], the set of items whose binary representation starts with the prefix p=x≫ℓp = x \gg \ell. Level 0 holds the single items, level LL the whole universe, and every dyadic interval at level ℓ≥1\ell \ge 1 is the disjoint union of two children at level ℓ−1\ell - 1.

Keep one count-min sketch per level, where level ℓ\ell treats the prefix x≫ℓx \gg \ell as its item. An update (x,Δ)(x, \Delta) goes to all L+1L + 1 sketches. The frequency of a dyadic interval is the sum of the frequencies of its items, and in the strict turnstile model it is at least the frequency of any item inside it. So:

  • if xx is heavy, every dyadic interval containing xx is heavy;
  • at each level, at most 1/ϕ1/\phi disjoint intervals can be heavy, since their frequencies add up to at most ∥f∥1\lVert f \rVert_1.

Heavy hitters are found by descending from the root, expanding only the intervals whose estimate passes the threshold:

text
Dyadic heavy-hitter search (Cormode and Muthukrishnan, 2005)
1  frontier ← {the root interval}
2  for ℓ ← L down to 1:
3      next ← {}
4      for each interval I in frontier, for each child J of I:
5          if estimate_{ℓ−1}(J) ≥ φ · ||f||_1: add J to next
6      frontier ← next
7  report frontier (single items at level 0)

Since estimates never fall below the truth, no heavy item is lost. Each level keeps at most about 1/(ϕ−ε)1/(\phi - \varepsilon) intervals (true heavy ones plus a few false positives, which a count-min with ε∥f∥1\varepsilon \lVert f \rVert_1 error admits only if their true count exceeds (ϕ−ε)∥f∥1(\phi - \varepsilon) \lVert f \rVert_1), so the search makes O(Lϕ)O(\frac{L}{\phi}) point queries instead of nn, and a union bound over those queries needs only d=O(log⁡Lϕδ)d = O(\log \frac{L}{\phi \delta}) rows per sketch.

Theorem (Cormode and Muthukrishnan, 2005). In the strict turnstile model, ε\varepsilon-approximate ϕ\phi-heavy hitters can be maintained with O(1εlog⁡nlog⁡log⁡nϕδ)O(\frac{1}{\varepsilon} \log n \log \frac{\log n}{\phi\delta}) counters, update time O(log⁡nlog⁡log⁡nϕδ)O(\log n \log \frac{\log n}{\phi \delta}) and query time O(1ϕlog⁡nlog⁡log⁡nϕδ)O(\frac{1}{\phi}\log n \log \frac{\log n}{\phi \delta}), succeeding with probability 1−δ1 - \delta.

The program inserts 23 400 items into a universe of 2162^{16} (four planted heavy items among random noise), then deletes 12 000 of them again, and searches for the items above 5%5\% of what remains.

python · try it yourself
import random
from collections import Counter

P = (1 << 61) - 1
class CountMin:
    def __init__(self, w, d, rng):
        self.w = w
        self.ab = [(rng.randrange(1, P), rng.randrange(P)) for _ in range(d)]
        self.C = [[0] * w for _ in range(d)]
    def add(self, x, c):
        for row, (a, b) in zip(self.C, self.ab):
            row[((a * x + b) % P) % self.w] += c
    def estimate(self, x):
        return min(row[((a * x + b) % P) % self.w] for row, (a, b) in zip(self.C, self.ab))

class DyadicCountMin:
    """One count-min per level; level l counts the prefixes x >> l (dyadic intervals of length 2^l)."""
    def __init__(self, bits, w, d, rng):
        self.bits = bits
        self.levels = [CountMin(w, d, rng) for _ in range(bits + 1)]
        self.total = 0                                    # ||f||_1 = sum of updates (strict turnstile)
    def update(self, x, delta):
        self.total += delta
        for l, cm in enumerate(self.levels):
            cm.add(x >> l, delta)
    def heavy_hitters(self, phi):
        thr, queries = phi * self.total, 0
        frontier = [0]                                    # the root interval: prefix 0 at the top level
        for l in range(self.bits, 0, -1):
            nxt = []
            for p in frontier:
                for child in (2 * p, 2 * p + 1):
                    queries += 1
                    if self.levels[l - 1].estimate(child) >= thr:
                        nxt.append(child)
            frontier = nxt
        return frontier, queries

rng = random.Random(2003)
bits = 16
sk = DyadicCountMin(bits, 64, 3, rng)
exact = Counter()
inserted = []
heavy = {1234: 2000, 40000: 1600, 65000: 1200, 777: 600}
for x, c in heavy.items():
    inserted += [x] * c
inserted += [rng.randrange(1 << bits) for _ in range(18000)]
rng.shuffle(inserted)
for x in inserted:
    sk.update(x, +1); exact[x] += 1
for x in inserted[:12000]:                                # delete two thirds of the stream again
    sk.update(x, -1); exact[x] -= 1
L1 = sum(exact.values())
phi = 0.05
found, q = sk.heavy_hitters(phi)
print(f"{len(inserted)} insertions, 12000 deletions; ||f||_1 = {L1}, threshold phi*||f||_1 = {phi * L1:.0f}")
print(f"found {found} with {q} point queries (instead of {1 << bits})")
print("true heavy hitters:", sorted(x for x in exact if exact[x] >= phi * L1), "with counts", {x: exact[x] for x in found})
print("item 777, inserted 600 times:", exact[777], "left after the deletions")
23400 insertions, 12000 deletions; ||f||_1 = 11400, threshold phi*||f||_1 = 570
found [1234, 40000, 65000] with 104 point queries (instead of 65536)
true heavy hitters: [1234, 40000, 65000] with counts {1234: 925, 40000: 837, 65000: 587}
item 777, inserted 600 times: 303 left after the deletions

The search used about a hundred point queries instead of 65 536. Item 777 was planted too, but most of its copies were deleted and it now holds less than the threshold: a summary that only grows (like Misra-Gries) could not have dropped it.

In C++

The same hierarchy with one flat array per level; the search keeps a frontier of prefixes.

cpp · try it yourself
#include <cstdint>
#include <cstdio>
#include <random>
#include <vector>

class CountMin {
    static constexpr std::uint64_t P = (1ULL << 61) - 1;
    std::size_t w, d;
    std::vector<std::uint64_t> a, b;
    std::vector<std::int64_t> C;
    std::size_t cell(std::size_t r, std::uint64_t x) const {
        return (std::size_t)((std::uint64_t)(((unsigned __int128)a[r] * x + b[r]) % P) % w);
    }
public:
    CountMin(std::size_t w, std::size_t d, std::mt19937_64& rng) : w(w), d(d), C(w * d) {
        for (std::size_t r = 0; r < d; ++r) { a.push_back(1 + rng() % (P - 1)); b.push_back(rng() % P); }
    }
    void add(std::uint64_t x, std::int64_t c) { for (std::size_t r = 0; r < d; ++r) C[r * w + cell(r, x)] += c; }
    std::int64_t estimate(std::uint64_t x) const {
        std::int64_t best = INT64_MAX;
        for (std::size_t r = 0; r < d; ++r) best = std::min(best, C[r * w + cell(r, x)]);
        return best;
    }
};

int main() {
    const int L = 20;                                       // universe of 2^20 items
    std::mt19937_64 rng(2005), gen(9);
    std::vector<CountMin> level;
    for (int l = 0; l <= L; ++l) level.emplace_back(256, 4, rng);
    std::int64_t total = 0;
    auto update = [&](std::uint64_t x, std::int64_t delta) {
        total += delta;
        for (int l = 0; l <= L; ++l) level[l].add(x >> l, delta);
    };
    std::vector<std::uint64_t> noise;
    for (int t = 0; t < 300000; ++t) { noise.push_back(gen() % (1u << L)); update(noise.back(), +1); }
    for (int t = 0; t < 20000; ++t) update(123456, +1);       // heavy, then mostly deleted
    for (int t = 0; t < 18000; ++t) update(123456, -1);
    for (int t = 0; t < 15000; ++t) update(999999, +1);       // stays heavy
    for (int t = 0; t < 250000; ++t) update(noise[t], -1);  // most of the noise is deleted again
    const double phi = 0.1;
    std::vector<std::uint64_t> frontier{0};
    long queries = 0;
    for (int l = L; l >= 1; --l) {
        std::vector<std::uint64_t> next;
        for (auto p : frontier)
            for (auto c : {2 * p, 2 * p + 1})
                if (++queries, level[l - 1].estimate(c) >= phi * total) next.push_back(c);
        frontier = next;
    }
    std::printf("||f||_1 = %lld, threshold %.0f, %ld point queries\n", (long long)total, phi * total, queries);
    for (auto x : frontier)
        std::printf("heavy: %llu (estimate %lld)\n", (unsigned long long)x, (long long)level[0].estimate(x));
}
||f||_1 = 67000, threshold 6700, 50 point queries
heavy: 999999 (estimate 15180)

Range queries and quantiles

The same hierarchy answers range counts ∑i=lohifi\sum_{i=lo}^{hi} f_i: every interval [lo,hi][lo, hi] is the disjoint union of at most 2L2L maximal dyadic intervals, one or two per level, so the estimate is a sum of at most 2L2L point estimates and its error is at most 2Lε∥f∥12L \varepsilon \lVert f \rVert_1 (one-sided, with the union bound over the pieces). Setting ε′=ε/(2L)\varepsilon' = \varepsilon / (2L) restores error ε∥f∥1\varepsilon\lVert f \rVert_1 at a log⁡n\log n factor in space. A quantile query, "the smallest tt with ∑i≤tfi≥q∥f∥1\sum_{i \le t} f_i \ge q \lVert f \rVert_1", is then a binary search over range queries. The program sketches 20 000 values in [0,4095][0, 4095] (think of response times in milliseconds) and answers four range queries and the median.

python · try it yourself
import random

P = (1 << 61) - 1
class CountMin:
    def __init__(self, w, d, rng):
        self.w = w
        self.ab = [(rng.randrange(1, P), rng.randrange(P)) for _ in range(d)]
        self.C = [[0] * w for _ in range(d)]
    def add(self, x, c):
        for row, (a, b) in zip(self.C, self.ab):
            row[((a * x + b) % P) % self.w] += c
    def estimate(self, x):
        return min(row[((a * x + b) % P) % self.w] for row, (a, b) in zip(self.C, self.ab))

def dyadic_cover(lo, hi):
    """Split [lo, hi] into maximal dyadic intervals; yields (level, prefix)."""
    while lo <= hi:
        l = 0
        while lo % (1 << (l + 1)) == 0 and lo + (1 << (l + 1)) - 1 <= hi:
            l += 1
        yield l, lo >> l
        lo += 1 << l

rng = random.Random(1)
bits = 12
levels = [CountMin(128, 3, rng) for _ in range(bits + 1)]
values = [int(1000 * sum(rng.random() for _ in range(4))) for _ in range(20000)]   # e.g. response times in ms
for v in values:
    for l, cm in enumerate(levels):
        cm.add(v >> l, 1)
print("range            exact   estimate   dyadic pieces")
for lo, hi in [(0, 999), (1500, 2500), (1234, 3210), (3000, 4095)]:
    pieces = list(dyadic_cover(lo, hi))
    est = sum(levels[l].estimate(p) for l, p in pieces)
    exact = sum(lo <= v <= hi for v in values)
    print(f"[{lo:4}, {hi:4}]   {exact:6}   {est:8}   {len(pieces):6}")
# a quantile from range queries: the smallest t with estimated count of [0, t] >= m/2 (binary search)
lo, hi = 0, (1 << bits) - 1
while lo < hi:
    mid = (lo + hi) // 2
    if sum(levels[l].estimate(p) for l, p in dyadic_cover(0, mid)) >= len(values) / 2:
        hi = mid
    else:
        lo = mid + 1
print(f"median estimate {lo}, exact median {sorted(values)[len(values) // 2]}")
range            exact   estimate   dyadic pieces
[   0,  999]      842        919        6
[1500, 2500]    11953      12325        8
[1234, 3210]    17771      18425       11
[3000, 4095]      844        911        3
median estimate 1996, exact median 2002

Every range estimate is above the truth, as count-min promises, by an amount that grows with the number of dyadic pieces. Deletions are handled for free, which is the reason to use this structure rather than an insertion-only quantile summary.

Other approaches

  • Group testing (Cormode and Muthukrishnan, 2005, "What's hot and what's not"): hash items into O(1/ϕ)O(1/\phi) buckets; in each bucket keep the total and, for each of the log⁡n\log n bit positions, the total of the items whose bit is 1. If one item holds more than half of its bucket's mass, its bits can be read off by majority, without any search. Repetition handles buckets with two heavy items.
  • ℓ2\ell_2-heavy hitters: replace count-min by Count-Sketch at each level. The search is the same, but the error is ε∥f∥2\varepsilon \lVert f \rVert_2; the space becomes O(ε−2log⁡2n)O(\varepsilon^{-2}\log^2 n) words for constant δ\delta. For insertion-only streams, O(ε−2log⁡(1/ε))O(\varepsilon^{-2}\log(1/\varepsilon)) words suffice (the BPTree of Braverman, Chestnut, Ivkin, Nelson, Wang and Woodruff, 2017).
  • Deterministic point queries and heavy hitters in turnstile streams are possible too, with more space: linear sketches built from explicit incoherent matrices give error ε∥f∥1\varepsilon\lVert f \rVert_1 with O(ε−2log⁡n)O(\varepsilon^{-2}\log n)-type space (see Nelson, Nguyen and Woodruff, 2012, for the bounds and their limits). The randomized sketches above are what is used in practice.

Test yourself

Why can Misra-Gries not be used when the stream has deletions?

  1. It uses too much space
  2. Its counters only track items it saw arriving; an item can become heavy because other items were deleted, without arriving, and a decremented counter cannot be restored
  3. It is randomized
  4. It needs to know nn

In the dyadic search, why are at most about 1/ϕ1/\phi intervals expanded per level?

  1. Because the hierarchy is binary
  2. Because the intervals of one level are disjoint, so at most 1/ϕ1/\phi of them can each hold ϕ∥f∥1\phi \lVert f \rVert_1 (plus a few false positives with count-min error)
  3. Because count-min has 1/ϕ1/\phi columns
  4. Because there are 1/ϕ1/\phi levels

Into how many dyadic intervals can an arbitrary range [lo,hi][lo, hi] of a universe of size 2L2^L be split?

  1. At most 2
  2. At most 2L2L
  3. At most L/2L/2
  4. Up to 2L2^L