Algorithm Search⌘K

Algorithmcore

Sparse vector technique

Also called AboveThreshold, SVT.

Compares a stream of low-sensitivity queries with a noisy threshold and reports only which one is first above it. The privacy cost is paid only for the queries above the threshold.

Time
O(k) worst
Space
O(1) extra
Where
c = the cutoff (the number of tops allowed); k = the number of queries asked
Origin
Cynthia Dwork, Moni Naor, Omer Reingold, Guy N. Rothblum, Salil Vadhan, 2009

The sparse vector technique answers a long stream of threshold questions about a private dataset: "is the answer to this query above TT?". It adds Laplace noise to the threshold once and to each query, and it stops at the first query whose noisy answer is above the noisy threshold. The surprise is that the queries below the threshold cost no privacy. The whole run is ε\varepsilon-differentially private, however many queries come before the first "yes". It is the base of the online query release algorithms, such as private multiplicative weights, and it is easy to get wrong: Lyu, Su and Li (2017) found that four of six published variants are not private.

In plain words

You want to know which of many questions has a large answer, for example which of thousands of product counts is above a level. To answer each one with noise would cost privacy for each question. Most of the answers are "no", and each "no" says little.

The technique moves the level a little at random, one time. It also moves each answer a little at random. Then it goes down the list and reports "no" until one noisy answer clears the noisy level. It reports "yes" for that one and stops. If you need more than one "yes", you start again with a new random level and pay again. You pay for each "yes", and the "no" answers are free.

The problem

The input is a dataset xx, a threshold TT, a privacy parameter ε>0\varepsilon > 0 and a stream of queries f1,f2,…f_1, f_2, \ldots, each a function from datasets to R\mathbb{R}. Each query has sensitivity at most Δ\Delta: ∣fi(x)−fi(x′)∣≤Δ|f_i(x) - f_i(x')| \le \Delta for all neighbors x∼x′x \sim x'. Two datasets are neighbors if one is the other with one record added or removed (add/remove), as in Dwork and Roth, who use histograms with ∥x−x′∥1≤1\|x - x'\|_1 \le 1. The proof uses only the sensitivity bound, so it holds for any neighbor relation under which each fif_i has sensitivity Δ\Delta. The analyst may choose fif_i after it sees the earlier outputs.

The output is a sequence a1,a2,…,aja_1, a_2, \ldots, a_j with ai∈{⊥,⊤}a_i \in \{\bot, \top\}: ⊥\bot for "below", and ⊤\top for "above". The goal is ε\varepsilon-DP for the whole sequence, and accuracy: each ⊤\top is for a query with fi(x)≥T−αf_i(x) \ge T - \alpha, and each ⊥\bot for a query with fi(x)≤T+αf_i(x) \le T + \alpha.

Lap(b)\mathrm{Lap}(b) is the Laplace distribution with density 12be−∣z∣/b\frac{1}{2b} e^{-|z|/b}. It has variance 2b22b^2, and P(∣Z∣>t)=e−t/bP(|Z| > t) = e^{-t/b}.

The algorithm

This is AboveThreshold, Algorithm 1 of Dwork and Roth, with a general sensitivity Δ\Delta (they use Δ=1\Delta = 1).

  1. ABOVE-THRESHOLD(x, f₁, f₂, ..., T, Δ, ε)
  2. 1T̂ ← T + Lap(2Δ/ε) ▷ one noisy threshold for the whole run
  3. 2for i ← 1, 2, ... do
  4. 3νᵢ ← Lap(4Δ/ε) ▷ fresh noise for each query
  5. 4if fᵢ(x) + νᵢ ≥ T̂ then
  6. 5output ⊤ and halt
  7. 6else output ⊥

Line L1 draws the threshold noise one time. Lines L3 and L4 compare a noisy answer with the noisy threshold. Line L5 halts at the first ⊤\top, and this is what keeps the cost at ε\varepsilon. The noisy values themselves are never output, only the comparison.

To allow cc tops, run AboveThreshold again after each ⊤\top, with a fresh noisy threshold. With ε/c\varepsilon/c per run, basic composition gives ε\varepsilon-DP in total. This is Sparse, Algorithm 2 of Dwork and Roth, with noise Lap(σ)\mathrm{Lap}(\sigma) on the threshold and Lap(2σ)\mathrm{Lap}(2\sigma) on each query, σ=2cΔ/ε\sigma = 2c\Delta/\varepsilon. With advanced composition, σ=32cln⁡(1/δ) Δ/ε\sigma = \sqrt{32 c \ln(1/\delta)}\,\Delta/\varepsilon gives (ε,δ)(\varepsilon, \delta)-DP.

Example

Take ε=1\varepsilon = 1, Δ=1\Delta = 1 and T=10T = 10, so the threshold noise is Lap(2)\mathrm{Lap}(2) and the query noise is Lap(4)\mathrm{Lap}(4). The query answers are f(x)=(3,8,6,11,14,5)f(x) = (3, 8, 6, 11, 14, 5). The run of the code with random.Random(16) draws T^=9.35\hat T = 9.35 in line L1, and the noise values below.

step fi(x)f_i(x) νi\nu_i fi(x)+νif_i(x) + \nu_i compare with T^=9.35\hat T = 9.35 output
L1 T^=9.35\hat T = 9.35
i=1i = 1 3 −0.16-0.16 2.84 below ⊥\bot
i=2i = 2 8 −0.73-0.73 7.27 below ⊥\bot
i=3i = 3 6 −0.45-0.45 5.55 below ⊥\bot
i=4i = 4 11 −0.80-0.80 10.20 above ⊤\top, halt
i=5i = 5 14 not asked
i=6i = 6 5 not asked

The output is (⊥,⊥,⊥,⊤)(\bot, \bot, \bot, \top). Query 4 is above TT and it is reported. Query 5 is also above TT, but the run halted. To find it too, use Sparse with c=2c = 2. Theorem 3.24 with k=6k = 6 and β=0.1\beta = 0.1 gives α=8(ln⁡6+ln⁡20)/1=38.3\alpha = 8(\ln 6 + \ln 20)/1 = 38.3. So the guarantee at this ε\varepsilon is weak for answers of size 10: the method needs large counts or a larger ε\varepsilon.

Correctness

Privacy (Dwork-Roth Theorem 3.23, a theorem). For adaptively chosen queries of sensitivity Δ\Delta, AboveThreshold is (ε,0)(\varepsilon, 0)-DP.

The key step: fix x∼x′x \sim x' and an output that halts at query kk. Fix the noise ν1,…,νk−1\nu_1, \ldots, \nu_{k-1}, which the two runs share. Let g(x)=max⁡i<k(fi(x)+νi)g(x) = \max_{i<k} (f_i(x) + \nu_i). The output is (⊥k−1,⊤)(\bot^{k-1}, \top) exactly when T^>g(x)\hat T > g(x) and fk(x)+νk≥T^f_k(x) + \nu_k \ge \hat T. Shift the threshold noise by at most Δ\Delta and the query noise νk\nu_k by at most 2Δ2\Delta: this maps the good event on xx into the good event on x′x'. The densities change by at most eε/2e^{\varepsilon/2} each, because the scales are 2Δ/ε2\Delta/\varepsilon and 4Δ/ε4\Delta/\varepsilon. The full proof is in proofs/correctness.md.

Accuracy (Dwork-Roth Theorem 3.24, a theorem). Let α=8Δ(ln⁡k+ln⁡(2/β))/ε\alpha = 8\Delta(\ln k + \ln(2/\beta))/\varepsilon. With probability at least 1−β1 - \beta, ∣T^−T∣≤α/2|\hat T - T| \le \alpha/2 and ∣νi∣≤α/2|\nu_i| \le \alpha/2 for all i≤ki \le k. On this event each ⊤\top has fi(x)≥T−αf_i(x) \ge T - \alpha and each ⊥\bot has fi(x)<T+αf_i(x) < T + \alpha. The theorem adds the condition that no query before the kk-th has fi(x)≥T−αf_i(x) \ge T - \alpha, so that the run reaches query kk.

Proof: AboveThreshold is epsilon-DP and (alpha, beta)-accuratefull

We use the pseudocode of the page. The queries f1,f2,…f_1, f_2, \ldots have sensitivity at most Δ\Delta for the neighbor relation in use: ∣fi(x)−fi(x′)∣≤Δ|f_i(x) - f_i(x')| \le \Delta for all neighbors x∼x′x \sim x'. The threshold noise has scale b1=2Δ/εb_1 = 2\Delta/\varepsilon and the query noise has scale b2=4Δ/εb_2 = 4\Delta/\varepsilon. We write p1p_1 for the density of T^\hat T (Laplace with center TT and scale b1b_1) and p2p_2 for the density of Lap(b2)\mathrm{Lap}(b_2). For a Laplace density pp with scale bb and any shift ss, p(z−s)≤e∣s∣/bp(z)p(z - s) \le e^{|s|/b} p(z), by the triangle inequality ∣z∣≤∣z−s∣+∣s∣|z| \le |z - s| + |s|.

Claim 1 (privacy). For any neighbors x∼x′x \sim x' and any output sequence aa, P[A(x)=a]≤eεP[A(x′)=a]P[\mathcal{A}(x) = a] \le e^{\varepsilon} P[\mathcal{A}(x') = a], also when each query is chosen as a function of the earlier outputs.

Proof. The output has one of two forms: a=(⊥k−1,⊤)a = (\bot^{k-1}, \top) for some k≥1k \ge 1, or a=(⊥m)a = (\bot^m) when the stream ends after mm queries with no top. The set of outputs is countable, so a bound for each single output gives the bound for each set of outputs.

Adaptivity. The query fif_i may depend on a1,…,ai−1a_1, \ldots, a_{i-1}. On the event A(⋅)=(⊥k−1,⊤)\mathcal{A}(\cdot) = (\bot^{k-1}, \top), these earlier outputs are all ⊥\bot. So the queries f1,…,fkf_1, \ldots, f_k that are asked on this event are the same functions for xx and for x′x'. We fix them.

Case a=(⊥k−1,⊤)a = (\bot^{k-1}, \top). Fix the values ν1,…,νk−1\nu_1, \ldots, \nu_{k-1}. They have the same distribution in both runs and are independent of T^\hat T and νk\nu_k. Let g(x)=max⁡i<k(fi(x)+νi)g(x) = \max_{i<k} (f_i(x) + \nu_i), with g=−∞g = -\infty when k=1k = 1. The output is aa exactly when (T^,νk)(\hat T, \nu_k) lies in

A(x)={(t,v):t>g(x) and fk(x)+v≥t}.A(x) = \{(t, v) : t > g(x) \text{ and } f_k(x) + v \ge t\}.

Each fif_i moves by at most Δ\Delta, so the maximum gg moves by at most Δ\Delta: ∣g(x′)−g(x)∣≤Δ|g(x') - g(x)| \le \Delta. Let s1=g(x′)−g(x)s_1 = g(x') - g(x) and s2=s1+fk(x)−fk(x′)s_2 = s_1 + f_k(x) - f_k(x'). Then ∣s1∣≤Δ|s_1| \le \Delta and ∣s2∣≤2Δ|s_2| \le 2\Delta. Define the translation φ(t,v)=(t+s1,v+s2)\varphi(t, v) = (t + s_1, v + s_2). If (t,v)∈A(x)(t, v) \in A(x), then t+s1>g(x)+s1=g(x′)t + s_1 > g(x) + s_1 = g(x'), and

fk(x′)+v+s2=fk(x)+v+s1≥t+s1.f_k(x') + v + s_2 = f_k(x) + v + s_1 \ge t + s_1.

So φ(A(x))⊆A(x′)\varphi(A(x)) \subseteq A(x'). A translation has Jacobian 1, so

P[(T^,νk)∈A(x)]=∫φ(A(x))p1(t′−s1) p2(v′−s2) dt′ dv′≤e∣s1∣/b1e∣s2∣/b2∫A(x′)p1(t′) p2(v′) dt′ dv′.P[(\hat T, \nu_k) \in A(x)] = \int_{\varphi(A(x))} p_1(t' - s_1)\, p_2(v' - s_2)\, dt'\, dv' \le e^{|s_1|/b_1} e^{|s_2|/b_2} \int_{A(x')} p_1(t')\, p_2(v')\, dt'\, dv'.

Here ∣s1∣/b1≤Δε/(2Δ)=ε/2|s_1|/b_1 \le \Delta \varepsilon/(2\Delta) = \varepsilon/2 and ∣s2∣/b2≤2Δε/(4Δ)=ε/2|s_2|/b_2 \le 2\Delta \varepsilon/(4\Delta) = \varepsilon/2. So the probability of aa on xx, for the fixed ν1,…,νk−1\nu_1, \ldots, \nu_{k-1}, is at most eεe^{\varepsilon} times the probability on x′x' for the same values. Take the expectation over ν1,…,νk−1\nu_1, \ldots, \nu_{k-1} on both sides.

Case a=(⊥m)a = (\bot^m). With g(x)=max⁡i≤m(fi(x)+νi)g(x) = \max_{i \le m} (f_i(x) + \nu_i) for fixed ν1,…,νm\nu_1, \ldots, \nu_m, the output is aa exactly when T^>g(x)\hat T > g(x). The shift t↦t+s1t \mapsto t + s_1 maps this event on xx into the event on x′x', and the density changes by at most eε/2e^{\varepsilon/2}. So the bound holds with eε/2≤eεe^{\varepsilon/2} \le e^{\varepsilon}.

Ties fk(x)+νk=T^f_k(x) + \nu_k = \hat T have probability 0, so the choice of ≥\ge in line L4 does not matter. □\square

Claim 2 (accuracy). Let k≥1k \ge 1, 0<β<10 < \beta < 1 and α=8Δ(ln⁡k+ln⁡(2/β))/ε\alpha = 8\Delta(\ln k + \ln(2/\beta))/\varepsilon. With probability at least 1−β1 - \beta, over the first kk queries, every ⊤\top is for a query with fi(x)≥T−αf_i(x) \ge T - \alpha and every ⊥\bot is for a query with fi(x)<T+αf_i(x) < T + \alpha.

Proof. Let EE be the event that ∣T^−T∣≤α/2|\hat T - T| \le \alpha/2 and ∣νi∣≤α/2|\nu_i| \le \alpha/2 for all i≤ki \le k. By P(∣Z∣>t)=e−t/bP(|Z| > t) = e^{-t/b} for Z∼Lap(b)Z \sim \mathrm{Lap}(b),

P(∣T^−T∣>α/2)=e−αε/(4Δ),P(∣νi∣>α/2)=e−αε/(8Δ)=β2k.P(|\hat T - T| > \alpha/2) = e^{-\alpha \varepsilon/(4\Delta)}, \qquad P(|\nu_i| > \alpha/2) = e^{-\alpha\varepsilon/(8\Delta)} = \frac{\beta}{2k}.

By the union bound, P(Eˉ)≤(β/(2k))2+k⋅β/(2k)≤β/2+β/2=βP(\bar E) \le (\beta/(2k))^2 + k \cdot \beta/(2k) \le \beta/2 + \beta/2 = \beta. On EE, a ⊤\top at query ii means fi(x)≥T^−νi≥T−α/2−α/2=T−αf_i(x) \ge \hat T - \nu_i \ge T - \alpha/2 - \alpha/2 = T - \alpha, and a ⊥\bot means fi(x)<T^−νi≤T+αf_i(x) < \hat T - \nu_i \le T + \alpha. □\square

Dwork and Roth state Claim 2 as Theorem 3.24, with the extra condition that no query before the kk-th has fi(x)≥T−αf_i(x) \ge T - \alpha. On EE that condition makes the run reach query kk, so the output has length kk.

Claim 3 (Sparse). Sparse with cutoff cc and δ=0\delta = 0 is ε\varepsilon-DP.

Proof. With σ=2cΔ/ε\sigma = 2c\Delta/\varepsilon, each segment between two tops is a run of AboveThreshold with ε/c\varepsilon/c in place of ε\varepsilon: the threshold noise is Lap(2Δ/(ε/c))\mathrm{Lap}(2\Delta/(\varepsilon/c)) and the query noise is Lap(4Δ/(ε/c))\mathrm{Lap}(4\Delta/(\varepsilon/c)). Each run is (ε/c)(\varepsilon/c)-DP by Claim 1, and its queries may depend on the outputs of the earlier runs. There are at most cc runs, so adaptive basic composition gives ε\varepsilon-DP. □\square

Cost. Each query asked costs one evaluation of fif_i, one Laplace draw (line L3) and one comparison (line L4). With one more draw in line L1, kk queries cost O(k)O(k) draws and comparisons in the real-RAM model. The run stores only T^\hat T and the current noise, so the extra space is O(1)O(1).

Complexity

In the real-RAM model with one Laplace draw at unit cost:

  • Each query costs one evaluation fi(x)f_i(x), one draw and one comparison. For kk queries the time is O(k)O(k) plus the cost of the evaluations.
  • The extra space is O(1)O(1): the run keeps only T^\hat T.
  • Sparse with cutoff cc draws at most cc thresholds, so it is still O(k)O(k).

The privacy cost does not grow with kk. This is the point of the technique. With the Laplace mechanism on each query and sequential composition, the cost grows as kεk\varepsilon.

Properties

  • Online and adaptive. The queries may come one at a time, and each may depend on the earlier outputs.
  • Output only the comparison. The noisy answers fi(x)+νif_i(x) + \nu_i stay inside. To publish a value for each ⊤\top, NumericSparse (Algorithm 3 of Dwork and Roth) spends a separate budget on a fresh Laplace answer.
  • Pure DP. AboveThreshold and Sparse with δ=0\delta = 0 are ε\varepsilon-DP. Sparse with advanced composition is (ε,δ)(\varepsilon, \delta)-DP.
  • Randomized. The output for one dataset is a random variable. Repeated runs on the same data each cost ε\varepsilon.

Variants and improvements

  • Sparse with cutoff cc. Halt after cc tops, with a fresh threshold after each ⊤\top (Dwork-Roth Theorems 3.25 and 3.26). For δ=0\delta = 0 the accuracy is α=8cΔ(ln⁡k+ln⁡(2c/β))/ε\alpha = 8c\Delta(\ln k + \ln(2c/\beta))/\varepsilon.
  • One threshold for cc tops. Lyu, Su and Li prove that the threshold need not be refreshed: noise Lap(Δ/ε1)\mathrm{Lap}(\Delta/\varepsilon_1) on the threshold and Lap(2cΔ/ε2)\mathrm{Lap}(2c\Delta/\varepsilon_2) on each query, with ε1+ε2=ε\varepsilon_1 + \varepsilon_2 = \varepsilon, is ε\varepsilon-DP. The noise on the threshold then scales with Δ/ε1\Delta/\varepsilon_1, not cΔ/εc\Delta/\varepsilon. Their analysis gives the split ε1:ε2=1:(2c)2/3\varepsilon_1 : \varepsilon_2 = 1 : (2c)^{2/3}.
  • Monotone queries. If all answers move in the same direction between neighbors, the query noise can be Lap(cΔ/ε2)\mathrm{Lap}(c\Delta/\varepsilon_2) (Lyu, Su and Li).
  • NumericSparse. Also release a noisy value of each query above the threshold.
  • Private multiplicative weights. Hardt and Rothblum use the technique to find the queries on which a synthetic dataset is wrong, and update only there. See MWEM for the offline relative.

When to use it

Use the sparse vector technique when you expect few of many queries to be above a threshold, and the queries arrive online. Examples are finding the first large count, checking whether a public synthetic answer is still close to the true one, and the update test of online query release. If all queries are known in advance and you need the largest, use report noisy max or the exponential mechanism: Lyu, Su and Li show that in the non-interactive setting the exponential mechanism is more accurate. If most answers are above the threshold, the technique saves nothing.

Pitfalls

  • No noise on the queries. Dropping line L3 (νi=0\nu_i = 0) and not halting gives a mechanism that is not ε\varepsilon-DP for any ε\varepsilon. For counts f1f_1 of value 0 and f2f_2 of value 1, the data (0)(0) gives (1,0)(1, 0) and the neighbor (0,1)(0, 1) gives (1,1)(1, 1). The output (⊤,⊥)(\top, \bot) needs f1≥T^>f2f_1 \ge \hat T > f_2, which has probability 0 on the neighbor. The test file checks this. The variant of Stoddard, Chen and Machanavajjhala has this error (Lyu, Su and Li, Algorithm 5).
  • Query noise that does not scale with cc. When one run allows cc tops, the query noise in line L3 must grow with cc: Lap(2σ)\mathrm{Lap}(2\sigma) with σ=2cΔ/ε\sigma = 2c\Delta/\varepsilon in Sparse. Lyu, Su and Li show that the variant of Lee and Clifton, with query noise that does not scale with cc, is only 1+6c4ε\frac{1 + 6c}{4}\varepsilon-DP.
  • No cutoff. Line L5 must halt, or Sparse must stop after cc tops. Without the cutoff, the variants of Stoddard et al. and of Chen et al. are not private for any finite ε\varepsilon (Lyu, Su and Li, Figure 2).
  • Publishing the noisy answer. Outputting fi(x)+νif_i(x) + \nu_i in line L5, in place of ⊤\top, is not private for any finite ε\varepsilon. The variant in Roth's 2011 lecture notes does this (Lyu, Su and Li, Algorithm 3). Use a fresh Laplace answer, as NumericSparse does.
  • Float noise. The code uses float Laplace noise from random.Random, for tests only. A deployment needs a cryptographic source of randomness and exact sampling (Mironov 2012; Canonne, Kamath and Steinke 2020); see the discrete Gaussian mechanism.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

dpkit.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Checkers for differential privacy on small finite examples.

A dataset is a tuple of records from a finite universe. A pmf is a dict from
outputs to probabilities; the probabilities may be fractions.Fraction (exact)
or float. A mechanism pmf is a function from a dataset to the pmf of the
output of the mechanism on that dataset.

This module holds the neighbor relations, the privacy loss, the hockey-stick
and Renyi divergences, the pure and approximate DP checks over a list of
neighbor pairs, an empirical pmf, the Hoeffding margin for Monte Carlo
checks, and a grid check of a log density ratio. It holds no mechanism, no
noise sampler and no accountant: those belong to the pages that define them.

Natural logarithms are used throughout, as in the DP literature.
"""

from __future__ import annotations

import math
from fractions import Fraction
from typing import Callable, Hashable, Iterable, Mapping, Sequence, Union

Number = Union[int, float, Fraction]
Pmf = Mapping[Hashable, Number]
Dataset = tuple
Pair = tuple[Dataset, Dataset]


def neighbors_add_remove(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
    """All datasets at add/remove distance 1 from dataset.

    A neighbor removes one record, or appends one record from the universe.
    Datasets are treated as multisets: a removal keeps the order of the other
    records, and equal results are listed once. Cost: O(n (n + |universe|)).
    """
    x = tuple(dataset)
    out: list[Dataset] = []
    seen: set[Dataset] = set()
    for i in range(len(x)):
        y = x[:i] + x[i + 1:]
        key = tuple(sorted(y, key=repr))
        if key not in seen:
            seen.add(key)
            out.append(y)
    for v in universe:
        y = x + (v,)
        key = tuple(sorted(y, key=repr))
        if key not in seen:
            seen.add(key)
            out.append(y)
    return out


def neighbors_replace(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
    """All datasets of the same size that differ from dataset in one record.

    The record at index i is replaced by a different value of the universe.
    Equal multisets are listed once. Cost: O(n^2 |universe|).
    """
    x = tuple(dataset)
    values = list(universe)
    out: list[Dataset] = []
    seen: set[Dataset] = set()
    for i in range(len(x)):
        for v in values:
            if v == x[i]:
                continue
            y = x[:i] + (v,) + x[i + 1:]
            key = tuple(sorted(y, key=repr))
            if key not in seen:
                seen.add(key)
                out.append(y)
    return out


def _ratio(a: Number, b: Number) -> Number:
    if isinstance(a, (int, Fraction)) and isinstance(b, (int, Fraction)):
        return Fraction(a) / Fraction(b)
    return float(a) / float(b)


def privacy_loss(p: Pmf, q: Pmf) -> dict[Hashable, float]:
    """The privacy loss ln(p(y) / q(y)) at each output y with p(y) > 0 or q(y) > 0.

    The value is +inf where q(y) = 0 < p(y) and -inf where p(y) = 0 < q(y).
    Outputs with p(y) = q(y) = 0 are left out. Cost: O(|support|).
    """
    out: dict[Hashable, float] = {}
    for y in set(p) | set(q):
        a, b = p.get(y, 0), q.get(y, 0)
        if a == 0 and b == 0:
            continue
        if b == 0:
            out[y] = math.inf
        elif a == 0:
            out[y] = -math.inf
        else:
            out[y] = math.log(_ratio(a, b))
    return out


def max_privacy_loss(p: Pmf, q: Pmf) -> float:
    """The largest privacy loss ln(p(y) / q(y)) over the outputs y with p(y) > 0.

    Returns -inf when p has no output of positive probability. Cost: O(|support|).
    """
    best = -math.inf
    for y, v in privacy_loss(p, q).items():
        if p.get(y, 0) > 0 and v > best:
            best = v
    return best


def hockey_stick(p: Pmf, q: Pmf, epsilon: float) -> float:
    """The hockey-stick divergence: the sum over y of max(0, p(y) - e^epsilon q(y)).

    It is sup over sets S of P(S) - e^epsilon Q(S). Cost: O(|support|).
    """
    a = math.exp(epsilon)
    total = 0.0
    for y in set(p) | set(q):
        d = float(p.get(y, 0)) - a * float(q.get(y, 0))
        if d > 0:
            total += d
    return total


def is_pure_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, tol: float = 1e-12) -> bool:
    """True if max privacy loss <= epsilon + tol for both orders of every pair.

    Precondition: mech_pmf returns the exact output pmf of the mechanism.
    Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
    """
    for x, y in pairs:
        p, q = mech_pmf(x), mech_pmf(y)
        if max_privacy_loss(p, q) > epsilon + tol or max_privacy_loss(q, p) > epsilon + tol:
            return False
    return True


def is_approx_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, delta: float, tol: float = 1e-12) -> bool:
    """True if the hockey-stick divergence at e^epsilon is <= delta + tol for both orders of every pair.

    Precondition: mech_pmf returns the exact output pmf of the mechanism.
    Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
    """
    for x, y in pairs:
        p, q = mech_pmf(x), mech_pmf(y)
        if hockey_stick(p, q, epsilon) > delta + tol or hockey_stick(q, p, epsilon) > delta + tol:
            return False
    return True


def renyi_divergence(p: Pmf, q: Pmf, alpha: float) -> float:
    """The Renyi divergence of order alpha > 1: ln(sum_y p(y)^alpha q(y)^(1 - alpha)) / (alpha - 1).

    Returns +inf when q(y) = 0 < p(y) for some y. Cost: O(|support|).
    """
    if alpha <= 1:
        raise ValueError("alpha must be greater than 1")
    s = 0.0
    for y in set(p) | set(q):
        a, b = float(p.get(y, 0)), float(q.get(y, 0))
        if a == 0:
            continue
        if b == 0:
            return math.inf
        s += a * (a / b) ** (alpha - 1)
    return math.log(s) / (alpha - 1)


def empirical_pmf(samples: Iterable[Hashable]) -> dict[Hashable, float]:
    """The fraction of the samples equal to each value. Cost: O(number of samples)."""
    counts: dict[Hashable, int] = {}
    n = 0
    for s in samples:
        counts[s] = counts.get(s, 0) + 1
        n += 1
    if n == 0:
        return {}
    return {k: c / n for k, c in counts.items()}


def hoeffding_margin(n: int, beta: float) -> float:
    """The margin t = sqrt(ln(2 / beta) / (2 n)).

    For n independent samples of a [0, 1] variable, the empirical mean is
    within t of the true mean with probability at least 1 - beta (Hoeffding).
    """
    if n <= 0 or not 0 < beta < 1:
        raise ValueError("need n >= 1 and 0 < beta < 1")
    return math.sqrt(math.log(2 / beta) / (2 * n))


def log_ratio_grid(logpdf_x: Callable[[float], float], logpdf_y: Callable[[float], float], grid: Iterable[float]) -> float:
    """The largest |logpdf_x(z) - logpdf_y(z)| over the points z of the grid.

    Use it to check the log density ratio of a continuous mechanism on two
    neighbors. Cost: O(|grid|) calls of each function.
    """
    best = 0.0
    for z in grid:
        d = abs(logpdf_x(z) - logpdf_y(z))
        if d > best:
            best = d
    return best
sparse_vector_technique.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-vector-technique/. The authors are listed in prov/QVW2C4.jsonl.
"""The sparse vector technique: AboveThreshold and its cutoff form Sparse.

This follows Dwork and Roth (2014), Algorithms 1 and 2. A query is a
function from the dataset to a real number with sensitivity at most
`sensitivity` under the neighbor relation the caller uses (add/remove in the
tests). The queries may be chosen adaptively: `queries` may be a generator
that looks at the earlier outputs.

The code uses random.Random so that the tests can be repeated, and it adds
float noise. Both are fine for study and wrong for a deployment: a real
release needs a cryptographic source of randomness and an exact sampler,
because float noise leaks through its low-order bits (Mironov 2012;
Canonne, Kamath and Steinke 2020).
"""

from __future__ import annotations

import math
import random
from typing import Callable, Iterable, TypeVar

D = TypeVar("D")


def laplace_noise(b: float, rng: random.Random) -> float:
    """One draw of Lap(b), the density (1/(2b)) exp(-|z|/b), by the inverse CDF.

    Precondition: b > 0. Cost: one uniform draw and O(1) time.
    """
    u = rng.random() - 0.5
    while u == -0.5:  # the open interval (-1/2, 1/2) excludes -1/2
        u = rng.random() - 0.5
    s = (u > 0) - (u < 0)
    return -b * s * math.log(1.0 - 2.0 * abs(u))


def above_threshold(
    x: D,
    queries: Iterable[Callable[[D], float]],
    threshold: float,
    sensitivity: float,
    epsilon: float,
    rng: random.Random,
) -> list[bool]:
    """Run AboveThreshold and return its outputs: False for bottom, True for top.

    The run stops after the first True, or when the queries run out.
    Precondition: every query has sensitivity at most `sensitivity` > 0, and
    epsilon > 0. Then the output list is epsilon-DP (Dwork-Roth Theorem 3.23).
    Cost: one evaluation of each query asked, and one Laplace draw per query
    plus one for the threshold.
    """
    if sensitivity <= 0 or epsilon <= 0:
        raise ValueError("sensitivity and epsilon must be positive")
    t_hat = threshold + laplace_noise(2.0 * sensitivity / epsilon, rng)  # @line L1
    out: list[bool] = []
    for f in queries:  # @line L2
        nu = laplace_noise(4.0 * sensitivity / epsilon, rng)  # @line L3
        if f(x) + nu >= t_hat:  # @line L4
            out.append(True)  # @line L5
            return out
        out.append(False)  # @line L6
    return out


def sparse(
    x: D,
    queries: Iterable[Callable[[D], float]],
    threshold: float,
    cutoff: int,
    sensitivity: float,
    epsilon: float,
    rng: random.Random,
) -> list[bool]:
    """Sparse with cutoff c and delta = 0 (Dwork-Roth Algorithm 2).

    It is AboveThreshold run again after each top, with sigma = 2 c sensitivity / epsilon
    for the threshold noise and 2 sigma for the query noise, and a fresh
    noisy threshold after each top. It stops after `cutoff` tops. The output
    is epsilon-DP by basic composition of `cutoff` runs that are each
    (epsilon / cutoff)-DP. Cost: as above_threshold, per query.
    """
    if cutoff < 1:
        raise ValueError("cutoff must be at least 1")
    sigma = 2.0 * cutoff * sensitivity / epsilon
    t_hat = threshold + laplace_noise(sigma, rng)
    out: list[bool] = []
    count = 0
    for f in queries:
        nu = laplace_noise(2.0 * sigma, rng)
        if f(x) + nu >= t_hat:
            out.append(True)
            count += 1
            if count >= cutoff:
                return out
            t_hat = threshold + laplace_noise(sigma, rng)
        else:
            out.append(False)
    return out


def accuracy_alpha(k: int, beta: float, epsilon: float, sensitivity: float = 1.0) -> float:
    """The alpha of Dwork-Roth Theorem 3.24: 8 sensitivity (ln k + ln(2 / beta)) / epsilon.

    With probability at least 1 - beta, over a stream of k queries, no top
    has a value below T - alpha and no bottom has a value above T + alpha.
    """
    return 8.0 * sensitivity * (math.log(k) + math.log(2.0 / beta)) / epsilon
test_sparse_vector_technique.py 216 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/sparse-vector-technique/. The authors are listed in prov/QVW2C4.jsonl.

import itertools
import math
import random

import dpkit
from sparse_vector_technique import above_threshold, accuracy_alpha, laplace_noise, sparse

UNIVERSE = (0, 1, 2)


def _counting_queries() -> list:
    # Counting queries have sensitivity 1 under add/remove.
    return [
        lambda x: sum(1 for r in x if r == 0),
        lambda x: sum(1 for r in x if r <= 1),
        lambda x: sum(1 for r in x if r == 2),
        lambda x: len(x),
    ]


def _lap_cdf(z: float, b: float) -> float:
    return 0.5 * math.exp(z / b) if z < 0 else 1.0 - 0.5 * math.exp(-z / b)


def _lap_pdf(z: float, b: float) -> float:
    return math.exp(-abs(z) / b) / (2.0 * b)


def _simpson(g, lo: float, hi: float, n: int) -> float:
    if hi <= lo:
        return 0.0
    n += n % 2
    h = (hi - lo) / n
    s = g(lo) + g(hi)
    for j in range(1, n):
        s += (4 if j % 2 else 2) * g(lo + j * h)
    return s * h / 3.0


def exact_pmf(answers: tuple, threshold: float, epsilon: float) -> dict:
    """The exact pmf of the halting index of AboveThreshold, by numerical integration.

    Output k in 0..m-1 means a top at query k; output m means all bottoms.
    The integrand is smooth between the break points T and a_i, so Simpson's
    rule on each piece is accurate to about 1e-10 here.
    """
    bt, bq = 2.0 / epsilon, 4.0 / epsilon
    m = len(answers)
    lo, hi = threshold - 40 * bt, threshold + 40 * bt
    cuts = sorted({lo, hi, threshold, *[a for a in answers if lo < a < hi]})
    pmf = {}
    for k in range(m + 1):
        def g(t: float, k: int = k) -> float:
            v = _lap_pdf(t - threshold, bt)
            for i in range(min(k, m)):
                v *= _lap_cdf(t - answers[i], bq)  # P(a_i + nu_i < t)
            if k < m:
                v *= 1.0 - _lap_cdf(t - answers[k], bq)  # P(a_k + nu_k >= t)
            return v
        pmf[k] = sum(_simpson(g, a, b, max(40, int(40 * (b - a) / bt))) for a, b in zip(cuts, cuts[1:]))
    return pmf


def _all_datasets(max_n: int) -> list:
    out = []
    for n in range(max_n + 1):
        out.extend(itertools.combinations_with_replacement(UNIVERSE, n))
    return out


def test_laplace_noise_moments() -> None:
    rng = random.Random(1)
    b = 2.0
    zs = [laplace_noise(b, rng) for _ in range(2000)]
    # P(|Z| > 2 ln 10) = 0.1 for b = 2 (a check value of the area).
    frac = sum(1 for z in zs if abs(z) > 2 * math.log(10)) / len(zs)
    assert abs(frac - 0.1) <= dpkit.hoeffding_margin(len(zs), 1e-6)


def test_exact_pmf_is_a_pmf() -> None:
    pmf = exact_pmf((1, 3, 0), 2.0, 1.0)
    assert abs(sum(pmf.values()) - 1.0) < 1e-8
    assert all(p > 0 for p in pmf.values())


def test_above_threshold_is_epsilon_dp_on_all_pairs() -> None:
    epsilon, threshold = 1.0, 1.5
    qs = _counting_queries()
    cache: dict = {}

    def mech_pmf(x: tuple) -> dict:
        key = tuple(q(x) for q in qs)
        if key not in cache:
            cache[key] = exact_pmf(key, threshold, epsilon)
        return cache[key]

    pairs = [(x, y) for x in _all_datasets(2) for y in dpkit.neighbors_add_remove(x, UNIVERSE)]
    assert len(pairs) > 30
    assert dpkit.is_pure_dp(mech_pmf, pairs, epsilon, tol=1e-6)
    worst = max(dpkit.max_privacy_loss(mech_pmf(x), mech_pmf(y)) for x, y in pairs)
    assert 0.3 < worst <= epsilon + 1e-6  # the bound holds and the loss is not trivial


def test_variant_without_query_noise_is_not_private() -> None:
    # A variant that drops line L3 and does not halt after a top (Lyu, Su and Li
    # 2017 study such variants). On x = (0,) the answers are (1, 0) and on its
    # add/remove neighbor x' = (0, 1) they are (1, 1). The output (top, bottom)
    # needs a_1 >= T_hat > a_2, which has probability 0 on x', so no finite
    # epsilon holds. We compute both probabilities from the threshold noise alone.
    bt = 2.0

    def p_top_bottom(a1: float, a2: float, t: float = 0.5) -> float:
        if a1 <= a2:
            return 0.0
        return _lap_cdf(a1 - t, bt) - _lap_cdf(a2 - t, bt)

    p = {"tb": p_top_bottom(1, 0)}
    q = {"tb": p_top_bottom(1, 1)}
    assert p["tb"] > 0.1
    assert dpkit.max_privacy_loss(p, q) == math.inf


def _oracle(answers: list, threshold: float, epsilon: float, rng: random.Random) -> list:
    """An independent restatement: draw all noise first, then find the first index with a_i + nu_i >= T_hat."""
    t_hat = threshold + laplace_noise(2.0 / epsilon, rng)
    hits = []
    for i, a in enumerate(answers):
        nu = laplace_noise(4.0 / epsilon, rng)
        hits.append(a + nu >= t_hat)
        if hits[-1]:
            break
    return hits


def test_against_oracle_on_random_inputs() -> None:
    gen = random.Random(7)
    for trial in range(600):
        m = gen.randrange(0, 8)
        answers = [gen.randrange(-3, 12) for _ in range(m)]
        threshold = gen.uniform(0, 10)
        epsilon = gen.choice([0.25, 0.5, 1.0, 2.0])
        qs = [lambda x, a=a: a for a in answers]
        got = above_threshold(None, qs, threshold, 1.0, epsilon, random.Random(trial))
        want = _oracle(answers, threshold, epsilon, random.Random(trial))
        assert got == want
        assert got.count(True) <= 1
        assert not got or got[-1] or len(got) == m


def test_adaptive_queries_are_allowed() -> None:
    # The next query may depend on the earlier outputs; here it moves the bar.
    rng = random.Random(3)
    data = (0, 0, 1, 2, 2, 2)
    out: list = []

    def stream():
        for v in UNIVERSE:
            yield (lambda x, v=v: sum(1 for r in x if r == v))

    out = above_threshold(data, stream(), 2.5, 1.0, 50.0, rng)
    assert out == [False, False, True]  # with tiny noise the count 3 of value 2 is the first above 2.5


def test_empirical_halting_matches_exact_pmf() -> None:
    answers, threshold, epsilon = (0, 2, 1), 1.0, 1.0
    pmf = exact_pmf(answers, threshold, epsilon)
    rng = random.Random(11)
    n = 3000
    qs = [lambda x, a=a: a for a in answers]
    counts = [0] * (len(answers) + 1)
    for _ in range(n):
        out = above_threshold(None, qs, threshold, 1.0, epsilon, rng)
        counts[len(out) - 1 if out and out[-1] else len(answers)] += 1
    margin = dpkit.hoeffding_margin(n, 1e-6)
    for k, c in enumerate(counts):
        assert abs(c / n - pmf[k]) <= margin


def test_accuracy_theorem_3_24() -> None:
    k, beta, epsilon, threshold = 20, 0.1, 1.0, 100.0
    alpha = accuracy_alpha(k, beta, epsilon)
    rng = random.Random(5)
    answers = [threshold - alpha - 1] * (k - 1) + [threshold + alpha + 1]
    qs = [lambda x, a=a: a for a in answers]
    runs, bad = 1000, 0
    for _ in range(runs):
        out = above_threshold(None, qs, threshold, 1.0, epsilon, rng)
        wrong = any((o and a < threshold - alpha) or (not o and a > threshold + alpha) for o, a in zip(out, answers))
        bad += wrong
    assert bad / runs <= beta + dpkit.hoeffding_margin(runs, 1e-6)


def test_sparse_stops_after_cutoff() -> None:
    rng = random.Random(9)
    answers = [50, 0, 50, 50, 0, 50, 50]
    qs = [lambda x, a=a: a for a in answers]
    for _ in range(200):
        out = sparse(None, qs, 25.0, 2, 1.0, 20.0, rng)
        assert out.count(True) <= 2
        if out.count(True) == 2:
            assert out[-1]


def test_bad_parameters() -> None:
    rng = random.Random(0)
    for args in [(0.0, 1.0), (1.0, 0.0)]:
        try:
            above_threshold(None, [], 0.0, args[0], args[1], rng)
        except ValueError:
            pass
        else:
            raise AssertionError("expected ValueError")
    assert above_threshold(None, [], 0.0, 1.0, 1.0, rng) == []

History

Dwork, Naor, Reingold, Rothblum and Vadhan introduced the technique at STOC 2009, in their work on efficient private query release. Roth and Roughgarden (STOC 2010, the median mechanism) and Hardt and Rothblum (FOCS 2010, private multiplicative weights) refined it and used it to answer many queries online. The book of Dwork and Roth (2014) gave the AboveThreshold form used here. Lyu, Su and Li (PVLDB 2017) surveyed the published variants, showed that most of them are not private, and gave a corrected version with a better budget split.

References

  1. Cynthia Dwork and Aaron Roth, The Algorithmic Foundations of Differential Privacy, Foundations and Trends in Theoretical Computer Science 9(3-4), 2014, pages 211 to 407, Section 3.6, Algorithm 1 (AboveThreshold), Theorem 3.23 (privacy), Theorem 3.24 (accuracy), Algorithm 2 (Sparse) and Theorems 3.25 and 3.26, Algorithm 3 (NumericSparse) and Theorems 3.27 and 3.28
  2. Min Lyu, Dong Su and Ninghui Li, Understanding the sparse vector technique for differential privacy, Proceedings of the VLDB Endowment 10(6), 2017, pages 637 to 648, Section 3 and Figures 1 and 2 (six variants; Algorithms 3 to 6 are not epsilon-DP, and Algorithms 3, 5 and 6 are not private for any finite epsilon); equation (12) (the budget split epsilon1 to epsilon2 as 1 to (2c)^(2/3))
  3. Cynthia Dwork, Moni Naor, Omer Reingold, Guy N. Rothblum and Salil Vadhan, On the complexity of differentially private data release, efficient algorithms and hardness results, STOC 2009, pages 381 to 390, the first form of the sparse vector technique
  4. Moritz Hardt and Guy N. Rothblum, A multiplicative weights mechanism for privacy-preserving data analysis, FOCS 2010, pages 61 to 70, the use of the sparse vector technique to decide when to update the synthetic distribution
  5. Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, the attack on floating-point Laplace noise and the snapping defense

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example