TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Space as the Resource: Deterministic Limits and Approximate Counting

Space as the Resource: Deterministic Limits and Approximate Counting

Streaming algorithms are measured by the memory they keep. This lesson shows the two facts that shape the whole subject. First, even simple quantities cannot be computed exactly in small space, and a short counting argument proves it. Second, randomization plus approximation breaks the barrier, and the oldest streaming algorithm, Morris's approximate counter (1978), shows how: it counts to a million in about 5 bits.

Exact answers need a lot of memory

Consider F0F_0, the number of distinct items in an insertion-only stream over [n][n].

Theorem. Every deterministic one-pass algorithm that computes F0F_0 exactly uses at least nn bits of memory on some stream.

Proof. Feed the algorithm the elements of a set S⊆[n]S \subseteq [n] in increasing order, and call its memory state σ(S)\sigma(S). Suppose two different sets S≠TS \ne T give the same state. Pick ii in one but not the other, say i∈S∖Ti \in S \setminus T, and append ii to both streams. Because the states are equal and the algorithm is deterministic, the final answers are equal. But the stream S,iS, i has ∣S∣\lvert S \rvert distinct items and T,iT, i has ∣T∣+1\lvert T \rvert + 1, so the answers should differ unless ∣S∣=∣T∣+1\lvert S \rvert = \lvert T \rvert + 1. If that happens, compare instead the answers before appending anything: they are equal (same state) while ∣S∣≠∣T∣\lvert S \rvert \ne \lvert T \rvert. Either way the algorithm errs, so σ\sigma is injective on the 2n2^n subsets, and some state needs nn bits. □\square

The argument is a fooling set: a family of prefixes that the algorithm must tell apart because some continuation separates every pair. It generalizes to other problems (the most frequent item's count, for example), and to randomized algorithms through communication complexity, in Space Lower Bounds from Communication Complexity. Two stronger statements are proved there or cited:

  • even a randomized algorithm needs Ω(n)\Omega(n) bits to compute F0F_0 exactly with probability 2/32/3;
  • even an approximate deterministic algorithm, one that outputs F^0\hat F_0 with ∣F^0−F0∣≤0.1F0\lvert \hat F_0 - F_0 \rvert \le 0.1 F_0 always, needs Ω(n)\Omega(n) bits (Alon, Matias and Szegedy, 1996).

So for F0F_0 both relaxations are needed at once: randomization and approximation. With both, O(ε−2+log⁡n)O(\varepsilon^{-2} + \log n) bits suffice (HyperLogLog and the lessons before it).

Approximate counting

The simplest quantity of all is the stream length mm. Counting it exactly needs ⌈log⁡2(m+1)⌉\lceil \log_2 (m+1) \rceil bits, and no deterministic algorithm can do better, since the counter must distinguish all values 0,…,m0, \ldots, m. Morris (1978) observed that if a relative error is acceptable, it suffices to store roughly log⁡2m\log_2 m, which takes only O(log⁡log⁡m)O(\log \log m) bits.

text
Morris counter
1  X ← 0
2  on each increment:
3      with probability 2^(-X): X ← X + 1
4  estimate: 2^X − 1

Lemma. After mm increments, E[2Xm]=m+1\mathbb{E}[2^{X_m}] = m + 1 and E[22Xm]=32m2+32m+1\mathbb{E}[2^{2X_m}] = \frac{3}{2}m^2 + \frac{3}{2}m + 1. Hence the estimate m^=2Xm−1\hat m = 2^{X_m} - 1 is unbiased and Var⁡[m^]=m(m−1)2\operatorname{Var}[\hat m] = \frac{m(m-1)}{2}.

Proof

Condition on Xm=jX_m = j. The next increment raises XX with probability 2−j2^{-j}, so

E[2Xm+1∣Xm=j]=2−j⋅2j+1+(1−2−j)⋅2j=2j+1.\mathbb{E}[2^{X_{m+1}} \mid X_m = j] = 2^{-j} \cdot 2^{j+1} + (1 - 2^{-j}) \cdot 2^j = 2^j + 1 .

Taking expectations, E[2Xm+1]=E[2Xm]+1\mathbb{E}[2^{X_{m+1}}] = \mathbb{E}[2^{X_m}] + 1, and with X0=0X_0 = 0 this gives m+1m + 1. In the same way,

E[22Xm+1∣Xm=j]=2−j⋅22j+2+(1−2−j)⋅22j=22j+3⋅2j,\mathbb{E}[2^{2X_{m+1}} \mid X_m = j] = 2^{-j} \cdot 2^{2j+2} + (1 - 2^{-j}) \cdot 2^{2j} = 2^{2j} + 3 \cdot 2^j ,

so E[22Xm+1]=E[22Xm]+3(m+1)\mathbb{E}[2^{2X_{m+1}}] = \mathbb{E}[2^{2X_m}] + 3(m + 1), which sums to 1+3∑t=1mt=1+32m(m+1)1 + 3\sum_{t=1}^{m} t = 1 + \frac{3}{2}m(m+1). Finally Var⁡[2Xm]=1+32m(m+1)−(m+1)2=m2−m2\operatorname{Var}[2^{X_m}] = 1 + \frac{3}{2}m(m+1) - (m+1)^2 = \frac{m^2 - m}{2}.

The program runs the counter 2000 times for each mm. Simulating a million increments one by one is slow in a browser, so it jumps: in state XX, the number of increments until XX next changes is geometric with success probability 2−X2^{-X}, and the program draws that waiting time directly. This is the same random process, sampled faster.

python · try it yourself
import math, random

def morris(m, rng):
    """Run a Morris counter on m increments; jump over the increments that leave X unchanged."""
    X, seen = 0, 0
    while True:
        p = 2.0 ** -X                       # each increment raises X with probability 2^-X
        u = 1.0 - rng.random()              # u in (0, 1]
        wait = 1 if p == 1.0 else int(math.log(u) / math.log1p(-p)) + 1   # geometric(p)
        if seen + wait > m:
            return X
        seen += wait
        X += 1

rng = random.Random(1978)
print("       m   mean of 2^X - 1   std (theory sqrt(m(m-1)/2))   largest X   bits for X")
for m in [10, 1000, 100000, 10**7]:
    est, xs = [], []
    for _ in range(2000):
        X = morris(m, rng)
        xs.append(X)
        est.append(2 ** X - 1)
    mean = sum(est) / len(est)
    std = (sum((e - mean) ** 2 for e in est) / len(est)) ** 0.5
    print(f"{m:8}   {mean:15.1f}   {std:11.1f} ({math.sqrt(m * (m - 1) / 2):11.1f})   {max(xs):9}   {max(xs).bit_length():10}")
       m   mean of 2^X - 1   std (theory sqrt(m(m-1)/2))   largest X   bits for X
      10               9.7           6.4 (        6.7)           6            3
    1000            1002.7         715.8 (      706.8)          13            4
  100000           97614.9       67523.6 (    70710.3)          19            5
10000000        10085203.0     7341086.2 (  7071067.5)          26            5

The means match mm and the spreads match the variance formula, and the counter for ten million increments never needed more than 5 bits. The price is visible too: the standard deviation is about 0.71 m0.71\,m, so a single counter is a very rough estimate.

From a rough estimate to an (ε,δ)(\varepsilon, \delta)-approximation

The standard recipe, used throughout the course, has two steps.

  1. Average kk independent copies (often called Morris+). The mean is still unbiased and its variance drops to m(m−1)2k<m22k\frac{m(m-1)}{2k} < \frac{m^2}{2k}, so by Chebyshev's inequality
Pr⁡[∣mˉ−m∣>εm]<m2/(2k)ε2m2=12kε2,\Pr\bigl[\lvert \bar m - m \rvert > \varepsilon m\bigr] < \frac{m^2/(2k)}{\varepsilon^2 m^2} = \frac{1}{2k\varepsilon^2} ,

which is at most 1/31/3 for k=⌈3/(2ε2)⌉k = \lceil 3/(2\varepsilon^2) \rceil.

  1. Take the median of t=O(log⁡(1/δ))t = O(\log(1/\delta)) independent averages. Each average is within εm\varepsilon m with probability at least 2/32/3; the median fails only if at least half of them fail, which by a Chernoff bound has probability e−Ω(t)≤δe^{-\Omega(t)} \le \delta.

Together: O(ε−2log⁡(1/δ))O(\varepsilon^{-2} \log(1/\delta)) counters of O(log⁡log⁡m)O(\log \log m) bits each. A sharper variant changes the base: increment with probability (1+a)−X(1 + a)^{-X} and estimate ((1+a)X−1)/a((1 + a)^X - 1)/a. With a≈2ε2δa \approx 2\varepsilon^2\delta a single counter suffices, and the optimal space is Θ(log⁡log⁡m+log⁡(1/ε)+log⁡log⁡(1/δ))\Theta(\log \log m + \log(1/\varepsilon) + \log\log(1/\delta)) bits (Nelson and Yu, 2022). The program measures how averaging shrinks the failure probability.

python · try it yourself
import math, random

def morris(m, rng):
    X, seen = 0, 0
    while True:
        p = 2.0 ** -X
        u = 1.0 - rng.random()
        wait = 1 if p == 1.0 else int(math.log(u) / math.log1p(-p)) + 1
        if seen + wait > m:
            return X
        seen += wait
        X += 1

rng = random.Random(5)
m, eps, trials = 10**6, 0.2, 400
print(f"m = {m}, target: within {eps:.0%} of m")
print("  k copies   Chebyshev bound on failure 1/(2k eps^2)   measured failure")
for k in [1, 8, 32, 128]:
    bad = 0
    for _ in range(trials):
        est = sum(2 ** morris(m, rng) - 1 for _ in range(k)) / k
        bad += abs(est - m) > eps * m
    print(f"  {k:8}   {min(1, 1 / (2 * k * eps * eps)):39.3f}   {bad / trials:16.3f}")
m = 1000000, target: within 20% of m
  k copies   Chebyshev bound on failure 1/(2k eps^2)   measured failure
         1                                     1.000              0.588
         8                                     1.000              0.400
        32                                     0.391              0.098
       128                                     0.098              0.003

Chebyshev's bound is valid but loose (it is vacuous for small kk), and the measured failure rate falls faster than 1/k1/k once the average is close to normally distributed. The median step is what turns "probability 2/32/3" into "probability 1−δ1 - \delta" at a logarithmic cost.

In C++

The counter increment by increment, as it would run in a real system: XX grows when the low XX bits of a random 64-bit word are all zero, which happens with probability exactly 2−X2^{-X}. Thirty-two counters each count the same 10610^6 increments.

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

struct Morris {
    std::uint8_t X = 0;                                   // one byte is plenty: X stays near log2(m)
    void increment(std::mt19937_64& rng) {
        std::uint64_t mask = X >= 64 ? ~0ULL : (1ULL << X) - 1;
        if ((rng() & mask) == 0) ++X;                     // probability 2^-X
    }
    double estimate() const { return double(1ULL << X) - 1; }
};

int main() {
    std::mt19937_64 rng(16);
    const int m = 1000000, k = 32;
    Morris c[k];
    for (int t = 0; t < m; ++t)
        for (auto& x : c) x.increment(rng);
    double sum = 0;
    int lo = 99, hi = 0;
    for (auto& x : c) {
        sum += x.estimate();
        lo = x.X < lo ? x.X : lo;
        hi = x.X > hi ? x.X : hi;
    }
    std::printf("%d increments, %d counters, X between %d and %d\n", m, k, lo, hi);
    std::printf("average estimate %.0f (relative error %+.1f%%)\n", sum / k, 100 * (sum / k / m - 1));
}
1000000 increments, 32 counters, X between 18 and 21
average estimate 925695 (relative error -7.4%)

With k=32k = 32 the standard deviation of the average is about 0.71/32≈12.5%0.71/\sqrt{32} \approx 12.5\% of mm, so an error of several per cent is typical; other seeds give errors up to about ±25%\pm 25\%, as Chebyshev's bound allows. The counters themselves never exceeded 21: a single byte each is plenty.

Test yourself

Why must a deterministic algorithm that computes F0F_0 exactly have different memory states after two different sets S≠TS \ne T of items?

  1. Because SS and TT have different sizes
  2. Because appending an item that lies in exactly one of them (or appending nothing) leads to different correct answers from the same state
  3. Because hash values differ
  4. Because the stream is long

After mm increments, what is E[2X]\mathbb{E}[2^{X}] for a Morris counter?

  1. mm
  2. m+1m + 1
  3. 2m2^m
  4. log⁡2m\log_2 m

How many bits does one Morris counter need to count to mm?

  1. O(log⁡m)O(\log m)
  2. O(log⁡log⁡m)O(\log \log m), since XX stays close to log⁡2m\log_2 m
  3. O(1)O(1)
  4. O(m)O(\sqrt{m})

In the average-then-median recipe, what does the median of O(log⁡(1/δ))O(\log(1/\delta)) averages achieve?

  1. It removes the bias
  2. It turns a constant success probability per average into 1−δ1 - \delta, by a Chernoff bound on the number of failing averages
  3. It reduces the variance by a factor 1/δ1/\delta
  4. It is only needed for deterministic algorithms