Algorithmadvanced
Smooth sensitivity framework
Also called Nissim-Raskhodnikova-Smith smooth sensitivity.
Adds noise scaled to a smooth upper bound on the local sensitivity at the actual dataset. For the median this is often far less noise than the global sensitivity needs.
- Time
- O(n^2) worst
- Space
- O(n) extra
- Where
- n = the number of values
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kobbi Nissim, Sofya Raskhodnikova, Adam Smith, 2007
The smooth sensitivity framework adds noise that fits the actual dataset and not the worst case. The global sensitivity of the median of values in is , so the Laplace mechanism must add noise of scale , even when the data is dense near the median. The local sensitivity at is often tiny, but noise scaled to it leaks the data, because the scale itself then tells about . Nissim, Raskhodnikova and Smith fix this with the -smooth sensitivity : the largest local sensitivity near , with a discount that falls with the distance. Noise of scale from a suitable law is then private.
In plain words
You want to release the middle value of a list of numbers, and you must hide each number. The safe rule for any list adds noise as large as the whole range, because for some lists one change moves the middle value from one end to the other.
For most lists, one change moves the middle value only a little. But a list that is close to a risky list could still be a risk, so the method looks at the lists that are a few changes away. It takes the largest movement among them, made smaller the farther away the list is. This number changes only slowly from one list to the next. Noise of that size, from a law with heavy tails, hides each number.
The problem
A dataset is a list of values in , with odd and public. Two datasets are neighbors if one value is replaced by another (replace), so is fixed. The distance is the number of replacements from to . The median is with in sorted order. The local sensitivity is , and the global sensitivity is . The goal is an -DP estimate of whose error follows the local shape of .
Notation: has the density , the variance and . The standard Cauchy law has the density and .
The algorithm
Sort , and set for and for . Lines L1 to L3 are the closed form of NRS Proposition 3.4, and line L4 is the Cauchy release of NRS Corollary 2.4 with .
SMOOTH-MEDIAN(x₁ ≤ ... ≤ xₙ, Λ, ε)- 1
for k ← 0 to n do ▷ β = ε/6 and S = 0 at the start - 2
A_k ← max_{0 ≤ t ≤ k+1} (x_{m+t} − x_{m+t−k−1}) ▷ the largest local sensitivity within k changes - 3
S ← max(S, e^{−kβ} · A_k) ▷ the discount for the distance - 4
output x_m + (6S/ε) · Z, with Z standard Cauchy
Line L2 is . To move the median by a lot with changes, take a run of consecutive gaps that contains the median and move the values inside it out of it. The padding with 0 and covers runs that reach an end of the range. Line L3 takes the maximum over of the discounted value, which is . For the value is , so the loop can stop at . Line L4 adds noise of scale . For -DP, use and the noise in line L4.
Example
Take values , with and , so and the median is 50. Each gap is 1, so until a run reaches an end. From the code:
| 0 | 1 | 1.000 |
| 1 | 2 | 1.693 |
| 2 | 3 | 2.150 |
| 3 | 4 | 2.426 |
| 4 | 5 | 2.567 |
| 5 | 6 | 2.608 |
| 6 | 7 | 2.575 |
| 8 | 9 | 2.372 |
| 50 | 51 | 0.012 |
So , and line L4 adds Cauchy noise of scale 15.6. The median absolute error of Cauchy noise is its scale, 15.6. The Laplace mechanism with the global sensitivity 100 needs , with the median absolute error . The form with has , and noise, with the median absolute error 15.3 and light tails. These are exact values of the noise laws (a theorem), not a measurement.
Correctness
The closed form (NRS Proposition 3.4, a theorem). Lines L1 to L3 compute . One change moves the median by at most one position, so . Within changes the widest gap that can sit at the median spans consecutive gaps of , which is line L2. The test file checks lines L1 to L3 against the definition by brute force on every dataset of the grid for and .
A smooth bound (a theorem). , and for neighbors, by the triangle inequality for .
Privacy (NRS Lemma 2.3 and Corollary 2.4, a theorem). Between neighbors the center moves by at most , which is in units of the scale, and the scale changes by a factor at most . The Cauchy log density has slope at most 1, and a change of scale by changes it by at most . So the log density ratio is at most at every output. Laplace noise does not have this property for a change of scale at large , which is why it gives only -DP.
The proofs are in proofs/correctness.md. The Laplace case there is a sketch with the locator in NRS.
Proof: The smooth sensitivity of the median has a closed form, and noise scaled to it gives differential privacypartial
We use the pseudocode of the page. A dataset is a list of values in , with odd and . We sort it as and set for and for . Two datasets are neighbors if one value is replaced by another, and is the number of replacements that turn into . The median is . The local sensitivity is , and the -smooth sensitivity is (NRS Definition 2.2).
Claim 1 (local sensitivity). .
Proof. One replacement moves at most one value across the median, so the new median is one of . Replacing a value at or above position by 0 gives the median , and replacing a value at or below position by gives .
Claim 2 (the ball, NRS Proposition 3.4). Let . Then .
Proof. Upper bound. Let , so is with at most values removed and the same number added. Sort . By Claim 1, is or . Take (if there is nothing to prove). Let and , with the padding. The values of with indices lie strictly between and , and has no value there, so they were all removed: . At least values of are at most , and they are kept values of with index at most or added values, so . At least values of are at least , so in the same way , that is . The ranges and then meet, so pick in both and set . Since is sorted, , which is the term . The case is the same with in place of in the counts, and it gives and , so the ranges meet again.
Lower bound. Fix with . The real values with indices from to are at most . Replace them: put just enough of them at 0 so that exactly values of are at most , and put the rest at . Then and , with the padding, so . For , put the values with indices to at 0. Then and . The count works in each case because the gap holds at most real values. The test file checks this formula against the definition on every dataset with and .
Claim 3 (the closed form). , which is lines L1 to L3.
Proof. Group the in the definition by : . Since falls with , replacing "" by "" does not change the maximum, which gives . For , , so the terms with are not larger than the term . The test file checks the result against the definition by brute force on all datasets of the grid for and .
Claim 4 (a smooth bound). , and for neighbors .
Proof. The term gives the first part. For the second, by the triangle inequality, so for each .
Claim 5 (pure DP with Cauchy noise, NRS Lemma 2.3 and Corollary 2.4). Let have the density , let and let . The output of line L4 is -DP.
Proof. The output density is . For neighbors, write and . By Claim 4, , so , and . Go from to in two steps: first move the center from to with the scale , then change the scale from to with the center .
Shift: , so moving the center by scaled units changes the log density by at most .
Scaling: with the distance to the center in units of , the log ratio of the two densities is . The second term lies between and , so the scaling changes the log density by at most .
The total is at most , in both directions. NRS state this with : noise needs . The test file checks the log density ratio on a grid of outputs.
Claim 6 (approximate DP with Laplace noise, NRS Corollary 2.4). With and noise , the output is -DP.
Proof sketch. This is a sketch. The full proof is NRS Lemma 2.3 with the Laplace case of Corollary 2.4, in Section 2 of the paper. The shift costs at most , because has a log density with slope at most 1 and the shift is at most in scaled units. The scale ratio is with , and the scaling changes the log density at the scaled point by at most , which is about . With this is at most about unless is of order , an event of probability of order under . NRS make the constants exact. The test file checks the hockey-stick divergence at by numerical integration.
Cost. Sorting takes . Line L2 takes for each , so lines L1 to L3 take as written. NRS give an algorithm by a divide-and-conquer search for the best for each . Line L4 takes .
Complexity
In the real-RAM model, sorting takes , and lines L1 to L3 as written take time, because line L2 scans terms. The extra space is for the sorted copy. NRS give an algorithm for the median. Line L4 takes .
Properties
- Instance-based noise. The noise follows the gaps of near the median, not the worst case over all datasets.
- Pure DP with heavy tails. The Cauchy form is -DP, but its noise has no mean. A single release can be far off with a small probability.
- Approximate DP with light tails. The Laplace form has exponential tails and is -DP.
- A general framework. Any function with a computable smooth bound on its local sensitivity can use line L4. Computing exactly is hard for some functions, and any smooth upper bound on is also enough (NRS Definition 2.1).
Variants and improvements
- Other noise laws. NRS give a general condition for "admissible" noise. Bun and Steinke (NeurIPS 2019) give laws with lighter tails for pure DP and for concentrated DP.
- Subsample and aggregate. When no smooth bound is easy to compute, split the data, run the function on each part, and combine with a private median. See subsample and aggregate.
- Propose-test-release. Test privately that the dataset is far from any dataset with large local sensitivity, and only then add small noise. See propose-test-release.
- Other statistics. The same scheme works for the trimmed mean and for other order statistics, with a different formula in line L2.
When to use it
Use smooth sensitivity for a statistic whose global sensitivity is huge but whose local sensitivity is small on typical data, such as a median or a quantile of a large, dense sample. Use the Laplace mechanism when the global sensitivity is already small, such as for counts. Use the exponential mechanism over a grid of candidates for a quantile when a discrete output is fine.
Pitfalls
- Noise scaled to the local sensitivity. Replacing in line L4 by is not private, because the scale depends on the data. A dataset with releases its median with no noise, and a neighbor with large does not.
- Too large a . Line L1 needs for the Cauchy form and for the Laplace form. A larger gives a smaller but breaks the proof.
- Laplace noise with the pure DP claim. Line L4 with Laplace noise and is not -DP. Laplace noise needs .
- The padding. Line L2 must use below the data and above it. Without the padding, ignores the datasets whose median moves to an end of the range, and the bound is not smooth.
- Float noise. The code uses
random.Randomand float noise, for tests only. A deployment needs a cryptographic source of randomness and exact sampling (Mironov 2012; Canonne, Kamath and Steinke 2020).
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
smooth_sensitivity.py 116 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smooth-sensitivity/. The authors are listed in prov/0ZFFMP.jsonl.
"""The smooth sensitivity framework of Nissim, Raskhodnikova and Smith
(2007), for the median of values in a known range [0, lam].
Neighbors replace one value by another, so n is fixed. The local
sensitivity of the median at y is how far one change can move the median
of y. The beta-smooth sensitivity is S*(x) = max over k >= 0 of
exp(-k beta) A(k, x), where A(k, x) is the largest local sensitivity over
the datasets within k changes of x. Noise scaled to S*(x) gives privacy:
Cauchy noise for pure DP, and Laplace noise for (epsilon, delta)-DP.
The code uses random.Random so that the tests can be repeated, and float
noise. A real release needs a cryptographic source of randomness and exact
sampling (Mironov 2012; Canonne, Kamath and Steinke 2020).
"""
from __future__ import annotations
import math
import random
from typing import Sequence
def median(xs: Sequence[float]) -> float:
"""The median x_m of an odd number of values, m = (n + 1)/2 in 1-based order. Cost: O(n log n)."""
if len(xs) % 2 == 0 or not xs:
raise ValueError("n must be odd")
return sorted(xs)[len(xs) // 2]
def _padded(xs: Sequence[float], lam: float):
s = sorted(xs)
n = len(s)
def at(i: int) -> float: # 1-based, with x_i = 0 for i <= 0 and x_i = lam for i > n
if i <= 0:
return 0.0
if i > n:
return float(lam)
return float(s[i - 1])
return at, n
def ball_sensitivity(xs: Sequence[float], k: int, lam: float) -> float:
"""A(k, x) = max over t = 0..k+1 of x_{m+t} - x_{m+t-k-1}: the largest local sensitivity within k changes.
Precondition: n odd, values in [0, lam], k >= 0. Cost: O(n log n + k).
"""
at, n = _padded(xs, lam)
m = (n + 1) // 2
return max(at(m + t) - at(m + t - k - 1) for t in range(k + 2))
def smooth_sensitivity_median(xs: Sequence[float], beta: float, lam: float) -> float:
"""The beta-smooth sensitivity of the median (NRS Proposition 3.4).
S*(x) = max over k = 0..n of exp(-k beta) A(k, x). For k >= n, A(k, x) = lam.
Precondition: n odd, values in [0, lam], beta > 0. Cost: O(n^2) with this direct
formula; NRS give an O(n log n) algorithm.
"""
if beta <= 0:
raise ValueError("beta must be positive")
at, n = _padded(xs, lam)
m = (n + 1) // 2
best = 0.0
for k in range(n + 1): # @line L1
a_k = max(at(m + t) - at(m + t - k - 1) for t in range(k + 2)) # @line L2
best = max(best, math.exp(-k * beta) * a_k) # @line L3
return best
def cauchy_noise(rng: random.Random) -> float:
"""One draw of the standard Cauchy law, density 1/(pi (1 + z^2)), by the inverse CDF. Cost: O(1)."""
u = rng.random()
while u == 0.0:
u = rng.random()
return math.tan(math.pi * (u - 0.5))
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. Cost: O(1)."""
u = rng.random() - 0.5
while u == -0.5:
u = rng.random() - 0.5
s = (u > 0) - (u < 0)
return -b * s * math.log(1.0 - 2.0 * abs(u))
def private_median_cauchy(xs: Sequence[float], lam: float, epsilon: float, rng: random.Random) -> float:
"""An epsilon-DP median: x_m + (6 S*/epsilon) Z, with beta = epsilon/6 and Z standard Cauchy.
This is NRS Corollary 2.4 (1) with gamma = 2: noise 2(gamma + 1) S*/epsilon = 6 S*/epsilon,
which needs beta <= epsilon/(2(gamma + 1)) = epsilon/6.
Precondition: epsilon > 0, n odd, values in [0, lam]. Cost: O(n^2).
"""
if epsilon <= 0:
raise ValueError("epsilon must be positive")
beta = epsilon / 6.0
s = smooth_sensitivity_median(xs, beta, lam)
return median(xs) + (6.0 * s / epsilon) * cauchy_noise(rng) # @line L4
def private_median_laplace(
xs: Sequence[float], lam: float, epsilon: float, delta: float, rng: random.Random
) -> float:
"""An (epsilon, delta)-DP median: x_m + (2 S*/epsilon) Lap(1), with beta = epsilon/(2 ln(2/delta)).
This is NRS Corollary 2.4 (2). Precondition: epsilon > 0, 0 < delta < 1. Cost: O(n^2).
"""
if epsilon <= 0 or not 0 < delta < 1:
raise ValueError("need epsilon > 0 and 0 < delta < 1")
beta = epsilon / (2.0 * math.log(2.0 / delta))
s = smooth_sensitivity_median(xs, beta, lam)
return median(xs) + (2.0 * s / epsilon) * laplace_noise(1.0, rng)
test_smooth_sensitivity.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smooth-sensitivity/. The authors are listed in prov/0ZFFMP.jsonl.
import itertools
import math
import random
import dpkit
from smooth_sensitivity import (
ball_sensitivity,
cauchy_noise,
laplace_noise,
median,
private_median_cauchy,
private_median_laplace,
smooth_sensitivity_median,
)
def _local_sensitivity(xs, lam):
# Brute force: replace one value by 0 or lam (the extremes move the median the most).
med = median(xs)
best = 0.0
for i in range(len(xs)):
for v in (0, lam):
ys = list(xs)
ys[i] = v
best = max(best, abs(median(ys) - med))
return best
def _distance(a, b):
# Replace distance between two multisets of the same size.
ca, cb = {}, {}
for v in a:
ca[v] = ca.get(v, 0) + 1
for v in b:
cb[v] = cb.get(v, 0) + 1
return len(a) - sum(min(c, cb.get(v, 0)) for v, c in ca.items())
def _brute_smooth(xs, beta, lam, everything):
# Definition 2.2 of NRS: max over y of exp(-beta d(x, y)) LS(y), over all datasets on the grid.
return max(math.exp(-beta * _distance(xs, y)) * ls for y, ls in everything)
def _all_datasets(n, lam):
return [(y, _local_sensitivity(y, lam)) for y in itertools.combinations_with_replacement(range(lam + 1), n)]
def test_local_sensitivity_matches_brute_force() -> None:
rng = random.Random(1)
for _ in range(500):
n = rng.choice([1, 3, 5, 7])
lam = rng.randrange(1, 10)
xs = [rng.randrange(lam + 1) for _ in range(n)]
assert ball_sensitivity(xs, 0, lam) == _local_sensitivity(xs, lam)
def test_smooth_sensitivity_matches_definition() -> None:
# The closed form of NRS Proposition 3.4 against the definition, on every dataset of the grid.
grids = {(n, lam): _all_datasets(n, lam) for n in (1, 3, 5) for lam in (1, 2, 4)}
rng = random.Random(2)
count = 0
for (n, lam), everything in grids.items():
for xs, _ in everything:
beta = rng.choice([0.05, 0.3, 1.0, 2.5])
got = smooth_sensitivity_median(xs, beta, lam)
assert math.isclose(got, _brute_smooth(xs, beta, lam, everything), rel_tol=1e-12)
count += 1
assert count >= 100
def test_ball_sensitivity_matches_brute_force() -> None:
# A(k, x) is the largest local sensitivity over the datasets within distance k.
everything = _all_datasets(5, 3)
for xs, _ in everything:
for k in range(6):
brute = max(ls for y, ls in everything if _distance(xs, y) <= k)
assert ball_sensitivity(xs, k, 3) == brute
def test_smooth_bound_properties() -> None:
# S* >= LS, and S*(x) <= exp(beta) S*(y) for neighbors (Definition 2.1 of NRS).
rng = random.Random(3)
for _ in range(500):
n = rng.choice([3, 5, 9, 15])
lam = 20
beta = rng.choice([0.1, 0.5, 1.0])
xs = [rng.randrange(lam + 1) for _ in range(n)]
ys = list(xs)
ys[rng.randrange(n)] = rng.randrange(lam + 1)
sx = smooth_sensitivity_median(xs, beta, lam)
sy = smooth_sensitivity_median(ys, beta, lam)
assert sx >= _local_sensitivity(xs, lam) - 1e-12
assert sx <= math.exp(beta) * sy * (1 + 1e-12)
assert sy <= math.exp(beta) * sx * (1 + 1e-12)
def _cauchy_logpdf(xs, lam, epsilon):
s = 6.0 * smooth_sensitivity_median(xs, epsilon / 6.0, lam) / epsilon
c = median(xs)
return lambda z: -math.log(math.pi * s) - math.log1p(((z - c) / s) ** 2)
def test_cauchy_release_is_epsilon_dp_on_a_grid() -> None:
# Pure DP: the log density ratio of neighbors stays within epsilon at every output.
rng = random.Random(4)
grid = [i / 4 for i in range(-400, 481)]
worst = 0.0
for _ in range(150):
n, lam = rng.choice([3, 5, 7]), 10
epsilon = rng.choice([0.5, 1.0, 2.0])
xs = [rng.randrange(lam + 1) for _ in range(n)]
ys = list(xs)
ys[rng.randrange(n)] = rng.choice([0, lam, rng.randrange(lam + 1)])
loss = dpkit.log_ratio_grid(_cauchy_logpdf(xs, lam, epsilon), _cauchy_logpdf(ys, lam, epsilon), grid)
assert loss <= epsilon + 1e-9
worst = max(worst, loss / epsilon)
assert worst > 0.15 # the analysis has slack, but the loss is not trivial
def _laplace_pdf(xs, lam, epsilon, delta):
beta = epsilon / (2.0 * math.log(2.0 / delta))
b = 2.0 * smooth_sensitivity_median(xs, beta, lam) / epsilon
c = median(xs)
return lambda z: math.exp(-abs(z - c) / b) / (2 * b)
def test_laplace_release_is_approx_dp() -> None:
# (epsilon, delta)-DP: the hockey-stick integral, by a fine Riemann sum, is at most delta.
rng = random.Random(5)
h = 0.02
grid = [-60 + h * i for i in range(int(130 / h))]
for _ in range(25):
n, lam = 5, 10
epsilon, delta = rng.choice([0.5, 1.0]), 0.05
xs = [rng.randrange(lam + 1) for _ in range(n)]
ys = list(xs)
ys[rng.randrange(n)] = rng.choice([0, lam])
p, q = _laplace_pdf(xs, lam, epsilon, delta), _laplace_pdf(ys, lam, epsilon, delta)
for a, b in ((p, q), (q, p)):
mass = h * sum(max(0.0, a(z) - math.exp(epsilon) * b(z)) for z in grid)
assert mass <= delta + 1e-3
def test_example_values() -> None:
xs = list(range(101))
lam, epsilon = 100, 1.0
assert median(xs) == 50
assert _local_sensitivity(xs, lam) == 1
assert [ball_sensitivity(xs, k, lam) for k in range(6)] == [1, 2, 3, 4, 5, 6]
s = smooth_sensitivity_median(xs, epsilon / 6, lam)
assert math.isclose(s, 6 * math.exp(-5 / 6), rel_tol=1e-12)
assert 15.6 < 6 * s / epsilon < 15.7
def test_noise_samplers() -> None:
rng = random.Random(6)
n = 20000
cauchy = [abs(cauchy_noise(rng)) <= 1.0 for _ in range(n)]
lap = [abs(laplace_noise(2.0, rng)) > 3.0 for _ in range(n)]
margin = dpkit.hoeffding_margin(n, 1e-6)
assert abs(sum(cauchy) / n - 0.5) <= margin
assert abs(sum(lap) / n - math.exp(-1.5)) <= margin
def test_release_centers_on_the_median() -> None:
rng = random.Random(7)
xs = [3, 5, 5, 6, 9]
outs = [private_median_cauchy(xs, 10, 1.0, rng) for _ in range(4001)]
assert abs(sorted(outs)[2000] - 5) < 1.0
outs = [private_median_laplace(xs, 10, 1.0, 1e-3, rng) for _ in range(4001)]
assert abs(sorted(outs)[2000] - 5) < 1.0
def test_bad_parameters() -> None:
rng = random.Random(8)
for call in (
lambda: median([1, 2]),
lambda: smooth_sensitivity_median([1], 0.0, 1),
lambda: private_median_cauchy([1], 1, 0.0, rng),
lambda: private_median_laplace([1], 1, 1.0, 0.0, rng),
):
try:
call()
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
History
Dwork, McSherry, Nissim and Smith (2006) calibrated noise to the global sensitivity. Nissim, Raskhodnikova and Smith (STOC 2007) showed that the local sensitivity alone is not safe, and gave smooth sensitivity, its closed form for the median, its use for the cost of a minimum spanning tree, and the subsample and aggregate framework. Dwork and Lei (2009) gave the related propose-test-release framework. Bun and Steinke (2019) gave better noise laws for the framework.
References
- Kobbi Nissim, Sofya Raskhodnikova and Adam Smith, Smooth sensitivity and sampling in private data analysis, STOC 2007, Definition 2.1 (a smooth upper bound), Definition 2.2 (smooth sensitivity), Lemma 2.3 and Corollary 2.4 (Cauchy noise for epsilon-DP, Laplace noise for (epsilon, delta)-DP), Proposition 3.4 (the median)
- Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, the attack on floating-point noise and the snapping defense
- Clement Canonne, Gautam Kamath and Thomas Steinke, The discrete Gaussian for differential privacy, NeurIPS 2020, exact sampling of discrete noise
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 0ZFFMP Edit this page History Report an error Markdown