Sparse Recovery and l0-Sampling
Reservoir sampling draws a uniform sample from an insertion-only stream, but a deletion can remove the sampled item and there is no way back. In a turnstile stream the natural question is: pick a uniformly random element of the support at the end, however many items were inserted and deleted on the way. An -sampler does this with a linear sketch of polylogarithmic size. It looks like a curiosity, but it is the engine of the dynamic graph algorithms in the next lesson, and its building block, sparse recovery, is a small piece of compressed sensing.
1-sparse and -sparse recovery
The first lesson of the course built a 1-sparse detector: three linear counters , and a fingerprint . If has exactly one non-zero entry, and , and the fingerprint test passes; if has two or more, the test fails except with probability about . There the fingerprint was for a random (a polynomial evaluation, analysed with Schwartz-Zippel); here is a random-looking hash, which is faster and in practice just as good.
To recover a vector with at most non-zero entries, hash the items into buckets with a few independent hash functions (rows), and put a 1-sparse detector in each bucket. A bucket that receives exactly one support element reveals it. Peeling then subtracts every recovered item from all its buckets, which may turn other buckets into 1-sparse ones, and repeats. With 3 rows of buckets the peeling succeeds with high probability (this is the analysis of invertible Bloom lookup tables and of 3-uniform hypergraph cores, Goodrich and Mitzenmacher, 2011; stated here). If has more than non-zero entries, peeling gets stuck and the structure reports failure rather than a wrong answer.
The program sketches a turnstile stream with 10 000 updates of "noise" (each inserted and later deleted) plus a planted sparse vector, with .
import random
P = (1 << 61) - 1
MASK = (1 << 64) - 1
def mix64(x):
x = (x + 0x9E3779B97F4A7C15) & MASK
x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
return x ^ (x >> 31)
class SparseRecovery:
"""rows x buckets of 1-sparse detectors (s0, s1, s2); recovers any k-sparse vector by peeling."""
def __init__(self, k, rows, rng):
self.w = 2 * k
self.salts = [rng.getrandbits(64) for _ in range(rows)]
self.fp = rng.getrandbits(64)
self.T = [[[0, 0, 0] for _ in range(self.w)] for _ in range(rows)]
def _r(self, i):
return mix64(i ^ self.fp) % P
def update(self, i, d):
r = self._r(i)
for salt, row in zip(self.salts, self.T):
c = row[mix64(i ^ salt) % self.w]
c[0] += d; c[1] += d * i; c[2] = (c[2] + d * r) % P
def recover(self):
found = {}
progress = True
while progress:
progress = False
for row in self.T:
for c in row:
s0, s1, s2 = c
if s0 != 0 and s1 % s0 == 0 and s2 == s0 * self._r(s1 // s0) % P:
i = s1 // s0
found[i] = found.get(i, 0) + s0
self.update(i, -s0) # peel it off everywhere
progress = True
ok = all(c[0] == 0 and c[1] == 0 and c[2] == 0 for row in self.T for c in row)
return found if ok else None # None: the vector was not k-sparse (or bad luck)
rng = random.Random(4)
n, k = 1 << 20, 25
for support in [25, 60]:
f = {}
ups = []
for _ in range(5000): # churn: many items inserted and deleted again
i = rng.randrange(n); d = rng.randint(1, 9)
ups += [(i, d), (i, -d)]
for i in rng.sample(range(n), support):
d = rng.choice([-3, -1, 2, 7]); f[i] = d; ups.append((i, d))
rng.shuffle(ups)
sr = SparseRecovery(k, 3, rng)
for i, d in ups:
sr.update(i, d)
got = sr.recover()
print(f"support {support}, sketch for k = {k} ({3 * 2 * k} cells of 3 numbers), {len(ups)} updates: "
+ ("recovered exactly: " + str(got == f) if got is not None else "reports 'not k-sparse'"))support 25, sketch for k = 25 (150 cells of 3 numbers), 10025 updates: recovered exactly: True
support 60, sketch for k = 25 (150 cells of 3 numbers), 10060 updates: reports 'not k-sparse'
The sketch has 150 cells, independent of the 10 000 updates and of the universe of a million items, and it recovered the 25 survivors exactly. Given 60 survivors it correctly refused. The space for -sparse recovery is words (to handle the failure probability, ), which is optimal up to the logarithm: the output itself needs bits.
-sampling
To sample from a support of unknown size , which may be anywhere between 1 and , subsample the universe at every scale. Level keeps the items whose hash has at least trailing zero bits, a random subset of density , and runs a 1-sparse detector on the restriction of to it. At the level with , the expected number of surviving support items is about 1, so with constant probability exactly one survives, and the detector returns it. By symmetry, the returned item is (close to) uniform over the support.
ℓ0-sampler (after Frahling, Indyk and Sohler, 2008; Jowhari, Saglam and Tardos, 2011)
1 for j = 0 .. log2 n: D_j ← 1-sparse detector
2 update (i, Δ): for j = 0 .. tz(h(i)): D_j.update(i, Δ) (tz = trailing zeros)
3 query: return the item of the first D_j that is exactly 1-sparse (or fail)Theorem (Jowhari, Sağlam and Tardos, 2011; stated). There is an -sampler for the general turnstile model that uses bits, fails with probability at most , and otherwise returns each support element with probability . Kapralov, Nelson, Pachocki, Wang, Woodruff and Yahyazadeh (2017) showed that this space is optimal up to constant factors. The version above, with one 1-sparse detector per level and an idealized hash, succeeds with a constant probability; replacing the 1-sparse detectors by -sparse recovery with pushes the success probability to , since then some level holds between 1 and survivors.
The program builds a turnstile stream whose final support has 30 items (600 items inserted, 570 of them deleted again) and runs 300 independent samplers.
import random
from collections import Counter
P = (1 << 61) - 1
MASK = (1 << 64) - 1
def mix64(x):
x = (x + 0x9E3779B97F4A7C15) & MASK
x = ((x ^ (x >> 30)) * 0xBF58476D1CE4E5B9) & MASK
x = ((x ^ (x >> 27)) * 0x94D049BB133111EB) & MASK
return x ^ (x >> 31)
class OneSparse:
"""s0 = sum f_i, s1 = sum i f_i, s2 = sum f_i r(i) mod P with a random-looking r: a fingerprint."""
def __init__(self, salt):
self.salt, self.s0, self.s1, self.s2 = salt, 0, 0, 0
def r(self, i):
return mix64(i ^ self.salt) % P
def update(self, i, d):
self.s0 += d
self.s1 += d * i
self.s2 = (self.s2 + d * self.r(i)) % P
def recover(self): # (i, f_i) if the vector is 1-sparse, else None
if self.s0 == 0 or self.s1 % self.s0:
return None
i = self.s1 // self.s0
if i >= 0 and self.s2 == self.s0 * self.r(i) % P:
return i, self.s0
return None
class L0Sampler:
"""Level j sees the items whose hash has at least j trailing zeros (probability 2^-j)."""
def __init__(self, levels, rng):
self.salt = rng.getrandbits(64)
self.levels = [OneSparse(rng.getrandbits(64)) for _ in range(levels)]
def update(self, i, d):
h = mix64(i ^ self.salt)
j = 0
while j < len(self.levels):
self.levels[j].update(i, d)
if h >> j & 1:
break
j += 1
def sample(self):
for lev in self.levels: # the first level with exactly one survivor
r = lev.recover()
if r:
return r
return None
rng = random.Random(2011)
n = 1 << 16
# turnstile stream: 600 items inserted, 570 of them deleted again; 30 survive with various counts
items = rng.sample(range(n), 600)
ups = [(i, rng.randint(1, 5)) for i in items]
survivors = set(items[:30])
ups += [(i, -c) for i, c in ups if i not in survivors]
rng.shuffle(ups)
counts, fails = Counter(), 0
for run in range(300):
s = L0Sampler(17, random.Random(run))
for i, d in ups:
s.update(i, d)
r = s.sample()
if r is None:
fails += 1
else:
assert r[0] in survivors
counts[r[0]] += 1
print(f"{len(ups)} updates, support size {len(survivors)} at the end; 300 independent samplers")
print(f"failed: {fails}; every sample was a surviving item; distinct items sampled: {len(counts)}")
print(f"times each survivor was sampled: min {min(counts.get(i, 0) for i in survivors)}, "
f"max {max(counts.values())}, mean {(300 - fails) / 30:.1f}")1170 updates, support size 30 at the end; 300 independent samplers
failed: 93; every sample was a surviving item; distinct items sampled: 30
times each survivor was sampled: min 2, max 13, mean 6.9
About two thirds of the samplers succeeded, every success returned a genuine survivor, and all 30 survivors were sampled with frequencies consistent with uniformity (about 7 each, with the usual Poisson scatter). The failures are runs where no level held exactly one survivor; independent copies make the failure probability as small as needed.
In C++
The same sampler for a universe of items, with 128-bit sums for . Twenty thousand items are inserted and all but 10 are deleted; 1000 independent samplers are run.
#include <bit>
#include <cstdint>
#include <cstdio>
#include <map>
#include <optional>
#include <random>
#include <utility>
#include <vector>
std::uint64_t mix64(std::uint64_t x) {
x += 0x9E3779B97F4A7C15ULL;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ULL;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBULL;
return x ^ (x >> 31);
}
constexpr std::uint64_t P = (1ULL << 61) - 1;
struct OneSparse { // s0 = sum f_i, s1 = sum i f_i, s2 = fingerprint
std::int64_t s0 = 0;
__int128 s1 = 0;
std::uint64_t s2 = 0;
void update(std::uint64_t i, std::int64_t d, std::uint64_t r) {
s0 += d; s1 += (__int128)d * i;
s2 = (std::uint64_t)(((__int128)s2 + (__int128)d * r % (__int128)P + P) % P);
}
};
class L0Sampler {
std::uint64_t salt, fsalt;
std::vector<OneSparse> level;
std::uint64_t r(std::uint64_t i) const { return mix64(i ^ fsalt) % P; }
public:
L0Sampler(int levels, std::mt19937_64& rng) : salt(rng()), fsalt(rng()), level(levels) {}
void update(std::uint64_t i, std::int64_t d) {
int top = std::countr_zero(mix64(i ^ salt) | (1ULL << 63)); // item lives in levels 0..top
for (int j = 0; j <= top && j < (int)level.size(); ++j) level[j].update(i, d, r(i));
}
std::optional<std::pair<std::uint64_t, std::int64_t>> sample() const {
for (auto& L : level) {
if (L.s0 == 0 || L.s1 % L.s0 != 0) continue;
__int128 i = L.s1 / L.s0;
if (i < 0) continue;
std::uint64_t want = (std::uint64_t)(((__int128)L.s0 % (__int128)P + P) % P * r((std::uint64_t)i) % P);
if (L.s2 == want) return std::pair{(std::uint64_t)i, L.s0};
}
return std::nullopt;
}
};
int main() {
std::mt19937_64 rng(2011);
std::vector<std::pair<std::uint64_t, std::int64_t>> ups;
std::map<std::uint64_t, std::int64_t> f;
for (int t = 0; t < 20000; ++t) { // insert 20000 items, delete all but 10
std::uint64_t i = rng() % (1ULL << 40);
std::int64_t d = 1 + rng() % 9;
ups.push_back({i, d});
if (t < 10) f[i] = d; else ups.push_back({i, -d});
}
int fails = 0, wrong = 0;
std::map<std::uint64_t, int> hits;
for (int run = 0; run < 1000; ++run) {
std::mt19937_64 seeds(run);
L0Sampler s(41, seeds);
for (auto [i, d] : ups) s.update(i, d);
auto got = s.sample();
if (!got) ++fails;
else if (!f.count(got->first) || f[got->first] != got->second) ++wrong;
else ++hits[got->first];
}
std::printf("1000 samplers: %d failed, %d wrong; hits per surviving item:", fails, wrong);
for (auto [i, c] : hits) std::printf(" %d", c);
std::printf("\n");
}1000 samplers: 260 failed, 0 wrong; hits per surviving item: 77 75 91 65 85 77 55 67 65 83
Again about a quarter of the single-detector samplers fail, none returns a wrong item, and the ten survivors are hit about equally often (each about 74 times out of 740 successes).
Why this matters
- Graph sketches. For each vertex, an -sampler over its incident edges, with signs chosen so that edges inside a set of vertices cancel when the vertices' sketches are added, samples an edge leaving the set. That is the AGM connectivity sketch, the subject of the next lesson.
- Distinct elements with deletions. Sampling from the support, and -sparse recovery when the support is small, give estimates of in the turnstile model, where HyperLogLog does not apply.
- Compressed sensing recovers approximately sparse vectors from few linear measurements; the combinatorial sketches here are its exactly-sparse, streaming-friendly cousins.
Test yourself
What does an -sampler return?
- The item with the largest
- A (nearly) uniformly random element of the support of the final vector, despite deletions
- A uniformly random position of the stream
- The number of non-zero entries
Why does the -sampler use levels with sampling rates ?
- To save time
- Because the support size is unknown; at the level where , exactly one support element survives with constant probability, and a 1-sparse detector can recover it
- To make the hash pairwise independent
- To store the support
What does -sparse recovery by peeling report when the vector has more than non-zero entries?
- A random subset of of them
- Failure: peeling gets stuck and the remaining cells are not all zero
- The largest entries
- A wrong vector without warning