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 , the number of distinct items in an insertion-only stream over .
Theorem. Every deterministic one-pass algorithm that computes exactly uses at least bits of memory on some stream.
Proof. Feed the algorithm the elements of a set in increasing order, and call its memory state . Suppose two different sets give the same state. Pick in one but not the other, say , and append to both streams. Because the states are equal and the algorithm is deterministic, the final answers are equal. But the stream has distinct items and has , so the answers should differ unless . If that happens, compare instead the answers before appending anything: they are equal (same state) while . Either way the algorithm errs, so is injective on the subsets, and some state needs bits.
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 bits to compute exactly with probability ;
- even an approximate deterministic algorithm, one that outputs with always, needs bits (Alon, Matias and Szegedy, 1996).
So for both relaxations are needed at once: randomization and approximation. With both, bits suffice (HyperLogLog and the lessons before it).
Approximate counting
The simplest quantity of all is the stream length . Counting it exactly needs bits, and no deterministic algorithm can do better, since the counter must distinguish all values . Morris (1978) observed that if a relative error is acceptable, it suffices to store roughly , which takes only bits.
Morris counter
1 X ← 0
2 on each increment:
3 with probability 2^(-X): X ← X + 1
4 estimate: 2^X − 1Lemma. After increments, and . Hence the estimate is unbiased and .
Proof
Condition on . The next increment raises with probability , so
Taking expectations, , and with this gives . In the same way,
so , which sums to . Finally .
The program runs the counter 2000 times for each . Simulating a million increments one by one is slow in a browser, so it jumps: in state , the number of increments until next changes is geometric with success probability , and the program draws that waiting time directly. This is the same random process, sampled faster.
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 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 , so a single counter is a very rough estimate.
From a rough estimate to an -approximation
The standard recipe, used throughout the course, has two steps.
- Average independent copies (often called Morris+). The mean is still unbiased and its variance drops to , so by Chebyshev's inequality
which is at most for .
- Take the median of independent averages. Each average is within with probability at least ; the median fails only if at least half of them fail, which by a Chernoff bound has probability .
Together: counters of bits each. A sharper variant changes the base: increment with probability and estimate . With a single counter suffices, and the optimal space is bits (Nelson and Yu, 2022). The program measures how averaging shrinks the failure probability.
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 ), and the measured failure rate falls faster than once the average is close to normally distributed. The median step is what turns "probability " into "probability " at a logarithmic cost.
In C++
The counter increment by increment, as it would run in a real system: grows when the low bits of a random 64-bit word are all zero, which happens with probability exactly . Thirty-two counters each count the same increments.
#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 the standard deviation of the average is about of , so an error of several per cent is typical; other seeds give errors up to about , 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 exactly have different memory states after two different sets of items?
- Because and have different sizes
- Because appending an item that lies in exactly one of them (or appending nothing) leads to different correct answers from the same state
- Because hash values differ
- Because the stream is long
After increments, what is for a Morris counter?
How many bits does one Morris counter need to count to ?
- , since stays close to
In the average-then-median recipe, what does the median of averages achieve?
- It removes the bias
- It turns a constant success probability per average into , by a Chernoff bound on the number of failing averages
- It reduces the variance by a factor
- It is only needed for deterministic algorithms