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
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
- 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 ?". 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 -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 , a threshold , a privacy parameter and a stream of queries , each a function from datasets to . Each query has sensitivity at most : for all neighbors . 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 . The proof uses only the sensitivity bound, so it holds for any neighbor relation under which each has sensitivity . The analyst may choose after it sees the earlier outputs.
The output is a sequence with : for "below", and for "above". The goal is -DP for the whole sequence, and accuracy: each is for a query with , and each for a query with .
is the Laplace distribution with density . It has variance , and .
The algorithm
This is AboveThreshold, Algorithm 1 of Dwork and Roth, with a general sensitivity (they use ).
ABOVE-THRESHOLD(x, f₁, f₂, ..., T, Δ, ε)- 1
T̂ ← T + Lap(2Δ/ε) ▷ one noisy threshold for the whole run - 2
for i ← 1, 2, ... do - 3
νᵢ ← Lap(4Δ/ε) ▷ fresh noise for each query - 4
if fᵢ(x) + νᵢ ≥ T̂ then - 5
output ⊤ and halt - 6
else 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 , and this is what keeps the cost at . The noisy values themselves are never output, only the comparison.
To allow tops, run AboveThreshold again after each , with a fresh noisy threshold. With per run, basic composition gives -DP in total. This is Sparse, Algorithm 2 of Dwork and Roth, with noise on the threshold and on each query, . With advanced composition, gives -DP.
Example
Take , and , so the threshold noise is and the query noise is . The query answers are . The run of the code with random.Random(16) draws in line L1, and the noise values below.
| step | compare with | output | |||
|---|---|---|---|---|---|
| L1 | |||||
| 3 | 2.84 | below | |||
| 8 | 7.27 | below | |||
| 6 | 5.55 | below | |||
| 11 | 10.20 | above | , halt | ||
| 14 | not asked | ||||
| 5 | not asked |
The output is . Query 4 is above and it is reported. Query 5 is also above , but the run halted. To find it too, use Sparse with . Theorem 3.24 with and gives . So the guarantee at this is weak for answers of size 10: the method needs large counts or a larger .
Correctness
Privacy (Dwork-Roth Theorem 3.23, a theorem). For adaptively chosen queries of sensitivity , AboveThreshold is -DP.
The key step: fix and an output that halts at query . Fix the noise , which the two runs share. Let . The output is exactly when and . Shift the threshold noise by at most and the query noise by at most : this maps the good event on into the good event on . The densities change by at most each, because the scales are and . The full proof is in proofs/correctness.md.
Accuracy (Dwork-Roth Theorem 3.24, a theorem). Let . With probability at least , and for all . On this event each has and each has . The theorem adds the condition that no query before the -th has , so that the run reaches query .
Proof: AboveThreshold is epsilon-DP and (alpha, beta)-accuratefull
We use the pseudocode of the page. The queries have sensitivity at most for the neighbor relation in use: for all neighbors . The threshold noise has scale and the query noise has scale . We write for the density of (Laplace with center and scale ) and for the density of . For a Laplace density with scale and any shift , , by the triangle inequality .
Claim 1 (privacy). For any neighbors and any output sequence , , also when each query is chosen as a function of the earlier outputs.
Proof. The output has one of two forms: for some , or when the stream ends after 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 may depend on . On the event , these earlier outputs are all . So the queries that are asked on this event are the same functions for and for . We fix them.
Case . Fix the values . They have the same distribution in both runs and are independent of and . Let , with when . The output is exactly when lies in
Each moves by at most , so the maximum moves by at most : . Let and . Then and . Define the translation . If , then , and
So . A translation has Jacobian 1, so
Here and . So the probability of on , for the fixed , is at most times the probability on for the same values. Take the expectation over on both sides.
Case . With for fixed , the output is exactly when . The shift maps this event on into the event on , and the density changes by at most . So the bound holds with .
Ties have probability 0, so the choice of in line L4 does not matter.
Claim 2 (accuracy). Let , and . With probability at least , over the first queries, every is for a query with and every is for a query with .
Proof. Let be the event that and for all . By for ,
By the union bound, . On , a at query means , and a means .
Dwork and Roth state Claim 2 as Theorem 3.24, with the extra condition that no query before the -th has . On that condition makes the run reach query , so the output has length .
Claim 3 (Sparse). Sparse with cutoff and is -DP.
Proof. With , each segment between two tops is a run of AboveThreshold with in place of : the threshold noise is and the query noise is . Each run is -DP by Claim 1, and its queries may depend on the outputs of the earlier runs. There are at most runs, so adaptive basic composition gives -DP.
Cost. Each query asked costs one evaluation of , one Laplace draw (line L3) and one comparison (line L4). With one more draw in line L1, queries cost draws and comparisons in the real-RAM model. The run stores only and the current noise, so the extra space is .
Complexity
In the real-RAM model with one Laplace draw at unit cost:
- Each query costs one evaluation , one draw and one comparison. For queries the time is plus the cost of the evaluations.
- The extra space is : the run keeps only .
- Sparse with cutoff draws at most thresholds, so it is still .
The privacy cost does not grow with . This is the point of the technique. With the Laplace mechanism on each query and sequential composition, the cost grows as .
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 stay inside. To publish a value for each , NumericSparse (Algorithm 3 of Dwork and Roth) spends a separate budget on a fresh Laplace answer.
- Pure DP. AboveThreshold and Sparse with are -DP. Sparse with advanced composition is -DP.
- Randomized. The output for one dataset is a random variable. Repeated runs on the same data each cost .
Variants and improvements
- Sparse with cutoff . Halt after tops, with a fresh threshold after each (Dwork-Roth Theorems 3.25 and 3.26). For the accuracy is .
- One threshold for tops. Lyu, Su and Li prove that the threshold need not be refreshed: noise on the threshold and on each query, with , is -DP. The noise on the threshold then scales with , not . Their analysis gives the split .
- Monotone queries. If all answers move in the same direction between neighbors, the query noise can be (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 () and not halting gives a mechanism that is not -DP for any . For counts of value 0 and of value 1, the data gives and the neighbor gives . The output needs , 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 . When one run allows tops, the query noise in line L3 must grow with : with in Sparse. Lyu, Su and Li show that the variant of Lee and Clifton, with query noise that does not scale with , is only -DP.
- No cutoff. Line L5 must halt, or Sparse must stop after tops. Without the cutoff, the variants of Stoddard et al. and of Chen et al. are not private for any finite (Lyu, Su and Li, Figure 2).
- Publishing the noisy answer. Outputting in line L5, in place of , is not private for any finite . 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.
# 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
- 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
- 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))
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag QVW2C4 Edit this page History Report an error Markdown