TExcelTAD
Home › Streaming, Sketching & Sublinear Algorithms › Sparse Recovery and l0-Sampling

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 supp⁡(f)={i:fi≠0}\operatorname{supp}(f) = \{i : f_i \ne 0\} at the end, however many items were inserted and deleted on the way. An ℓ0\ell_0-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 kk-sparse recovery

The first lesson of the course built a 1-sparse detector: three linear counters s0=∑ifis_0 = \sum_i f_i, s1=∑iifis_1 = \sum_i i f_i and a fingerprint s2=∑ifir(i) mod ps_2 = \sum_i f_i r(i) \bmod p. If ff has exactly one non-zero entry, i=s1/s0i = s_1 / s_0 and fi=s0f_i = s_0, and the fingerprint test s2=s0 r(i)s_2 = s_0\, r(i) passes; if ff has two or more, the test fails except with probability about 1/p1/p. There the fingerprint was r(i)=zir(i) = z^i for a random zz (a polynomial evaluation, analysed with Schwartz-Zippel); here rr is a random-looking hash, which is faster and in practice just as good.

To recover a vector with at most kk non-zero entries, hash the items into 2k2k 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 2k2k 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 ff has more than kk 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 k=25k = 25.

python · try it yourself
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 kk-sparse recovery is O(klog⁡n)O(k \log n) words (to handle the failure probability, O(klog⁡(n/δ))O(k \log(n/\delta))), which is optimal up to the logarithm: the output itself needs klog⁡(n/k)k \log(n/k) bits.

ℓ0\ell_0-sampling

To sample from a support of unknown size ss, which may be anywhere between 1 and nn, subsample the universe at every scale. Level j=0,1,…,log⁡2nj = 0, 1, \ldots, \log_2 n keeps the items whose hash has at least jj trailing zero bits, a random subset of density 2−j2^{-j}, and runs a 1-sparse detector on the restriction of ff to it. At the level with 2j≈s2^j \approx s, 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.

text
ℓ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 ℓ0\ell_0-sampler for the general turnstile model that uses O(log⁡2nlog⁡1δ)O(\log^2 n \log \frac{1}{\delta}) bits, fails with probability at most δ\delta, and otherwise returns each support element with probability 1s±n−c\frac{1}{s} \pm n^{-c}. 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 kk-sparse recovery with k=O(log⁡1δ)k = O(\log \frac{1}{\delta}) pushes the success probability to 1−δ1 - \delta, since then some level holds between 1 and kk 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.

python · try it yourself
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 2402^{40} items, with 128-bit sums for s1s_1. Twenty thousand items are inserted and all but 10 are deleted; 1000 independent samplers are run.

cpp · try it yourself
#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 ℓ0\ell_0-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 kk-sparse recovery when the support is small, give estimates of F0F_0 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 ℓ0\ell_0-sampler return?

  1. The item with the largest ∣fi∣\lvert f_i \rvert
  2. A (nearly) uniformly random element of the support {i:fi≠0}\{i : f_i \ne 0\} of the final vector, despite deletions
  3. A uniformly random position of the stream
  4. The number of non-zero entries

Why does the ℓ0\ell_0-sampler use levels with sampling rates 2−j2^{-j}?

  1. To save time
  2. Because the support size ss is unknown; at the level where 2j≈s2^j \approx s, exactly one support element survives with constant probability, and a 1-sparse detector can recover it
  3. To make the hash pairwise independent
  4. To store the support

What does kk-sparse recovery by peeling report when the vector has more than kk non-zero entries?

  1. A random subset of kk of them
  2. Failure: peeling gets stuck and the remaining cells are not all zero
  3. The kk largest entries
  4. A wrong vector without warning