Algorithmcore
Gaussian mechanism
Also called Gaussian noise mechanism.
Adds Gaussian noise scaled to the l2 sensitivity, which gives (epsilon, delta)-differential privacy and composes well.
- Time
- O(k + T) worst
- Space
- O(k) extra
- Where
- T = the number of bisection steps of the analytic calibration; k = the number of coordinates of the query
- Model
- Real RAM
- Properties
- randomizedrandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Cynthia Dwork, Krishnaram Kenthapadi, Frank McSherry, Ilya Mironov, Moni Naor, 2006
The Gaussian mechanism answers a numeric query about a private dataset with independent normal noise added to each coordinate. The noise has standard deviation proportional to the sensitivity , and the output is -differentially private. It is never -DP with . Its strength is that it scales to the norm and not to the norm, so a vector of counts needs noise of size about per count in place of , and that its privacy loss is itself a normal random variable, so many runs compose in a simple closed form. It is the noise of DP-SGD.
In plain words
You want to publish many numbers about a table at once, for example 100 counts, and one person can change each count by at most one. The Laplace mechanism must protect the worst total change, which is 100, so it adds a lot of noise to each count. The Gaussian mechanism measures the change of the whole vector as a length, which is only . It adds bell-shaped noise of that scale to each count.
The price is a small . Bell-shaped noise has thin tails. On a rare output far out in a tail, the ratio between the probabilities under two neighboring tables can be very large. So the guarantee is "the ratio is at most , except on events of total probability about ". You choose much smaller than one over the number of people.
The problem
The input is a dataset of records from a universe , a query that maps datasets to , a number , and privacy parameters and . Here
and means that and are neighbors. The page uses add/remove neighbors (one record added or removed) unless it says otherwise. A histogram has under add/remove and under replace (one record changes, so one count falls and one rises). Note that under replace.
The output is a random vector . The map from to the distribution of must be -DP: for all neighbors and all sets .
The normal distribution has density . We write for the standard normal distribution function. The site has no page on the normal distribution, so this is its definition here.
The algorithm
There are two ways to choose . The classical bound of Dwork and Roth is a closed form, and it is proved only for . The analytic bound of Balle and Wang is the smallest that works, for every , and it is found by bisection on the function
which falls as grows.
GAUSSIAN-MECHANISM(x, f, Delta, epsilon, delta) ▷ Delta >= the l2 sensitivity of f- 1
sigma <- the smallest s with delta_Delta(s) <= delta ▷ analytic; classical: Delta sqrt(2 ln(1.25/delta)) / epsilon - 2
v <- f(x) ▷ v = (v_1, ..., v_k) - 3
for i <- 1 to k do - 4
draw z from N(0, sigma^2) - 5
y_i <- v_i + z - 6
return y = (y_1, ..., y_k)
Line L1 does not read the data. It depends only on , and , so it can run once and be reused for every query with the same parameters. The code doubles an upper end until is at most , then halves the bracket times, and returns the upper end of the final bracket, so the returned is never too small. Line L2 is the only line that reads the data. Line L4 draws a fresh normal sample for each coordinate, and the samples are never published or reused.
The code on this site uses floats and the seeded generator random.Random.gauss, so that the tests can repeat each run. A deployment needs a cryptographic source of randomness and an exact sampler, because float noise leaks through its low-order bits (Mironov 2012). The discrete Gaussian mechanism adds integer noise with an exact sampler (Canonne, Kamath and Steinke 2020).
Example
The universe is and the dataset is , so the histogram is with under add/remove neighbors. Take and . The classical bound does not apply, because it needs . Line L1 with the analytic bound gives . Assume that line L4 draws for the standard normal values .
| step | (line L4) | (line L5) | |||
|---|---|---|---|---|---|
| L1, L2 | , | ||||
| L3 to L5 | 1 | 2 | 0.5 | 1.865316 | 3.865316 |
| L3 to L5 | 2 | 1 | |||
| L3 to L5 | 3 | 3 | 0.1 | 0.373063 | 3.373063 |
| L6 |
A negative count is a normal output. Rounding and clamping it to is post-processing and keeps the guarantee.
The two calibrations for , :
| classical | analytic | ratio of the variances | |
|---|---|---|---|
| 0.1 | 48.448053 | 30.749566 | 0.403 |
| 0.5 | 9.689611 | 7.031827 | 0.527 |
| 0.9 | 5.383117 | 4.106624 | 0.582 |
| 1 | not proved | 3.730632 | |
| 2 | not proved | 1.993812 |
So the analytic bound removes 40 to 60 percent of the variance in this range. At the classical for , the exact is only , far below the target . Two more check values: with and , gives the exact and gives .
Correctness
Theorem (classical; Dwork-Roth Theorem 3.22, proved as Theorem A.1). Let and . If with and , then GAUSSIAN-MECHANISM is -DP. Dwork and Roth state it with a strict inequality for ; the proof of this page covers equality, which is what the code uses.
Theorem (analytic; Balle and Wang 2018, Theorem 8). For every and , adding noise to a query of sensitivity is -DP if and only if .
The key step is that the privacy loss is normal. For neighbors with and , the loss with has the distribution , because only the noise along the direction of matters. The tight for this pair is , with the loss under , and this is exactly . It grows with , so the worst pair has . The full proofs, with the proof of the classical bound from the normal tail, are in the correctness proof of this page.
Accuracy. Each coordinate has error , so . By a union bound, with probability at least all errors are at most . The total squared error has mean .
Proof: The Gaussian mechanism is (epsilon, delta)-DP under the analytic and the classical calibrationfull
We work in the real RAM, where line L4 draws an exact sample of . Fix a neighbor relation , a query with values in , a number , and . Write for the standard normal distribution function, , and for the standard normal density. The output of line L6 is with , because each pass of line L3 draws a fresh independent sample.
For and let
Lemma 1 (the privacy loss is normal). Fix with and , and let . Let and be the densities of and , and . If , then . If , then .
Proof. The normalizing constants of and are equal, so . For , we have , so
The scalar is a linear combination of independent normal coordinates, so it is . Hence is normal with mean and variance . For , and , which is .
Lemma 2 (the tight delta of one pair). For as in Lemma 1,
Proof. For any measurable , . This is largest for , because holds every point where the integrand is positive and no other point. So the supremum is . By Lemma 1,
With , and , which gives .
The same value comes out for the pair in the other order, because the pair has the same .
Lemma 3 (monotonicity). For fixed , the function is strictly increasing on . Hence grows with and falls with .
Proof. Let and . Then , so . The derivative is
Theorem 1 (analytic calibration; Balle and Wang 2018, Theorem 8). If , then is -DP. If some pair of neighbors has , the converse also holds.
Proof. For a pair with the two output distributions are equal. For a pair with , Lemma 2 and Lemma 3 give for every , which is the definition. Conversely, for a pair with , Lemma 2 gives a set with difference exactly , so -DP needs .
Lemma 4 (line L1 with the analytic bound). The bisection of line L1 stops and returns a with , within relative distance of the smallest such value.
Proof. As , : for both arguments of tend to , and for the value is . So the doubling loop stops with . As , the first argument tends to and the second to , so , and the halving loop stops with . Each bisection step keeps the invariant . By Lemma 3, the set is an interval , so at every step. The loop stops when , and it returns .
Theorem 2 (classical calibration; Dwork-Roth Theorem 3.22 and Theorem A.1). Let , , and . Then is -DP.
Proof. Fix a pair with and let . By Lemma 2 the worst difference is at most with . The map is decreasing, so , and . We show in two cases. Since and is increasing in , .
Case . Then , so and .
Case . Then , so . The tail bound for holds because . Also , so . Hence
In both cases every pair has difference at most for every set .
Dwork and Roth assume ; the proof above also covers equality, which is the value line L1 uses. The bound is far from tight: for , and , the exact at the classical is .
Theorem 3 (accuracy). For , with probability at least , .
Proof. Each error is . For , : for this follows from , and for smaller we have . So . With this is , and the union bound over the coordinates gives total failure probability at most .
Complexity
The model is the real RAM: a normal sample, an exponential, an evaluation of and an arithmetic step each cost one unit. The cost is counted per query, after the one evaluation of in line L2.
- Time. Line L1 with the classical bound is . With the analytic bound it is evaluations of , where is the number of bisection steps; the code stops when the bracket is below times its upper end, which is about 40 steps, plus a few doublings to find the bracket. The loop of line L3 runs times with work. So the time is in the worst case.
- Space. The output has numbers, and the rest is . So the extra space is .
Properties
- Approximate only. For no works: the log ratio of the two densities at is linear in , so it is unbounded. The tests measure it on a grid: 3.5 on and 30.5 on for .
- Tight. The analytic condition is necessary and sufficient. A below the analytic value fails for the worst pair, and the tests check that gives a above the target.
- scale. For counts that one record can each change by 1, while . So the noise per count grows like for the Gaussian mechanism and like for the Laplace mechanism, for a fixed and .
- Closed-form composition. For one pair of neighbors, the losses of independent runs add, and a sum of independent normal losses is the normal loss with . Dong, Roth and Su (2019) prove the same rule for adaptive runs: the composition is -GDP. In the language of other pages, the mechanism is -GDP with (Gaussian differential privacy), -zCDP with (zero-concentrated DP), and -RDP for every (Renyi DP). With and this is .
- Unbiased. and the covariance is , so the noise adds cleanly to other normal errors in a statistical analysis.
Variants and improvements
- Analytic calibration. Balle and Wang (2018) give the condition of line L1 and a stable way to solve it. This is the version the code uses by default.
- Discrete Gaussian. The discrete Gaussian mechanism adds integer noise with , with almost the same guarantees and an exact sampler.
- Correlated noise. Noise with a general covariance fits queries whose sensitivity set is an ellipsoid. The matrix mechanism is one way to design it.
- Denoising. Balle and Wang also post-process the output with estimators that know the noise distribution, which reduces the error in high dimension. This is post-processing and costs no privacy.
- Noisy gradients. DP-SGD clips each gradient to norm , so that the sum has , and adds Gaussian noise to the sum at each step. Its accounting uses the moments accountant or numerical privacy accounting.
When to use it
Use the Gaussian mechanism when you answer many numeric queries, or a vector query whose sensitivity is much smaller than its sensitivity, and a small is acceptable. It is also the right choice when the release is one step of an iterative algorithm, because its composition is exact in closed form. For one or a few low-dimensional queries with pure -DP, use the Laplace mechanism. For integer output, use the discrete Gaussian mechanism.
Pitfalls
- The classical formula for . Line L1 with is proved only for , and it fails for larger . With , and it gives , and the exact at this is , more than twice the target. Use the analytic calibration for any ; the code raises an error for the classical formula outside .
- in place of , or the reverse. Line L1 must use . Using is safe but wastes accuracy. Using in the Laplace mechanism is not safe.
- The wrong neighbor relation. A histogram has under add/remove and under replace. A calibration with under replace gives a larger than claimed.
- A large . The mechanism that publishes each record with probability is -DP, and it publishes about records. Choose much smaller than (Dwork-Roth Section 2.3).
- Float noise.
random.gausson floats is fine for study and not for a release (Mironov 2012). Use an exact discrete sampler from a cryptographic source.
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
gaussian_mechanism.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gaussian-mechanism/. The authors are listed in prov/B229GK.jsonl.
"""The Gaussian mechanism with the classical and the analytic calibration.
The mechanism adds independent N(0, sigma^2) noise to each coordinate of a
query with l2-sensitivity Delta. The classical calibration of Dwork and Roth
(Theorem 3.22) needs 0 < epsilon < 1. The analytic calibration of Balle and
Wang (2018) finds the smallest sigma with delta(epsilon) <= delta, using the
exact formula
delta(epsilon) = Phi(Delta / (2 s) - epsilon s / Delta)
- e^epsilon Phi(-Delta / (2 s) - epsilon s / Delta).
Floats and random.Random.gauss are used so that the tests are reproducible.
They are not a safe sampler: a deployment needs a cryptographic source of
randomness and an exact sampler such as the discrete Gaussian.
"""
from __future__ import annotations
import math
import random
from typing import Callable, Sequence, TypeVar
X = TypeVar("X")
def normal_cdf(t: float) -> float:
"""Phi(t), the standard normal CDF, from math.erfc. Cost: O(1)."""
return 0.5 * math.erfc(-t / math.sqrt(2.0))
def classical_sigma(sensitivity: float, epsilon: float, delta: float) -> float:
"""sigma = sqrt(2 ln(1.25 / delta)) Delta / epsilon (Dwork and Roth, Theorem 3.22).
Precondition: Delta > 0, 0 < epsilon < 1 and 0 < delta < 1. The bound is
proved only for epsilon < 1, so other values raise. Cost: O(1).
"""
if sensitivity <= 0 or not 0 < epsilon < 1 or not 0 < delta < 1:
raise ValueError("need Delta > 0, 0 < epsilon < 1 and 0 < delta < 1")
return math.sqrt(2.0 * math.log(1.25 / delta)) * sensitivity / epsilon
def analytic_delta(sensitivity: float, sigma: float, epsilon: float) -> float:
"""The exact smallest delta at epsilon for N(0, sigma^2) noise and l2-sensitivity Delta.
Precondition: Delta > 0, sigma > 0, epsilon >= 0. Cost: O(1).
"""
if sensitivity <= 0 or sigma <= 0 or epsilon < 0:
raise ValueError("need Delta > 0, sigma > 0 and epsilon >= 0")
a = sensitivity / (2.0 * sigma)
b = epsilon * sigma / sensitivity
return max(0.0, normal_cdf(a - b) - math.exp(epsilon) * normal_cdf(-a - b))
def analytic_sigma(sensitivity: float, epsilon: float, delta: float, rel_tol: float = 1e-12) -> float:
"""The smallest sigma with analytic_delta(Delta, sigma, epsilon) <= delta, by bisection.
delta(epsilon) falls as sigma grows, so bisection applies. The returned
sigma is the upper end of the final bracket, so it is never too small.
Precondition: Delta > 0, epsilon >= 0, 0 < delta < 1.
Cost: O(log(1 / rel_tol)) evaluations of analytic_delta.
"""
if sensitivity <= 0 or epsilon < 0 or not 0 < delta < 1:
raise ValueError("need Delta > 0, epsilon >= 0 and 0 < delta < 1")
lo, hi = sensitivity, sensitivity
while analytic_delta(sensitivity, hi, epsilon) > delta:
lo, hi = hi, 2.0 * hi
while analytic_delta(sensitivity, lo, epsilon) <= delta and lo > 1e-300:
hi, lo = lo, lo / 2.0
while hi - lo > rel_tol * hi:
mid = 0.5 * (lo + hi)
if analytic_delta(sensitivity, mid, epsilon) <= delta:
hi = mid
else:
lo = mid
return hi
def gaussian_mechanism(
x: X,
f: Callable[[X], Sequence[float]],
sensitivity: float,
epsilon: float,
delta: float,
rng: random.Random,
analytic: bool = True,
) -> list[float]:
"""Return f(x) + Z with Z_i independent N(0, sigma^2).
Precondition: f has l2-sensitivity at most Delta under the chosen neighbor
relation. With analytic=True the output is (epsilon, delta)-DP for any
epsilon >= 0; with analytic=False it needs 0 < epsilon < 1.
Cost: O(k) for k coordinates, plus O(log(1 / rel_tol)) for the calibration.
"""
if analytic:
sigma = analytic_sigma(sensitivity, epsilon, delta) # @line L1
else:
sigma = classical_sigma(sensitivity, epsilon, delta) # @line L1
v = list(f(x)) # @line L2
y: list[float] = []
for vi in v: # @line L3
z = rng.gauss(0.0, sigma) # @line L4
y.append(vi + z) # @line L5
return y # @line L6
def gaussian_log_density(y: float, center: float, sigma: float) -> float:
"""ln of the N(center, sigma^2) density at y."""
return -((y - center) ** 2) / (2.0 * sigma * sigma) - math.log(sigma * math.sqrt(2.0 * math.pi))
test_gaussian_mechanism.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/gaussian-mechanism/. The authors are listed in prov/B229GK.jsonl.
import math
import random
import pytest
import dpkit
from gaussian_mechanism import (
analytic_delta,
analytic_sigma,
classical_sigma,
gaussian_log_density,
gaussian_mechanism,
normal_cdf,
)
def simpson(g, a, b, n=1200):
h = (b - a) / n
s = g(a) + g(b)
for i in range(1, n):
s += (4 if i % 2 else 2) * g(a + i * h)
return s * h / 3
def hockey_stick_by_integration(sens, sigma, eps):
"""Oracle: integrate max(0, p - e^eps q) for p = N(0, s^2), q = N(Delta, s^2).
The integrand is positive exactly left of the point where the log ratio equals eps.
"""
p = lambda y: math.exp(gaussian_log_density(y, 0.0, sigma))
q = lambda y: math.exp(gaussian_log_density(y, sens, sigma))
cut = sens / 2 - eps * sigma * sigma / sens
g = lambda y: max(0.0, p(y) - math.exp(eps) * q(y))
return simpson(g, cut - 14 * sigma, cut)
def test_check_values():
assert abs(classical_sigma(1, 0.5, 1e-5) - 9.6896) < 5e-5
assert abs(analytic_delta(1, 1, 1) - 0.126937) < 5e-7
assert abs(analytic_delta(1, 2, 1) - 0.0068296) < 5e-8
# mu-GDP with mu = Delta / sigma = 1 gives the same delta at epsilon = 1.
assert analytic_delta(3, 3, 1) == pytest.approx(0.126937, abs=5e-7)
assert normal_cdf(0) == 0.5
def test_analytic_delta_matches_numeric_integration():
rng = random.Random(21)
for _ in range(500):
sens = rng.uniform(0.2, 3.0)
sigma = rng.uniform(0.3, 4.0) * sens
eps = rng.uniform(0.0, 3.0)
want = hockey_stick_by_integration(sens, sigma, eps)
assert abs(analytic_delta(sens, sigma, eps) - want) < 1e-8
def test_analytic_delta_falls_with_sigma():
for eps in (0.0, 0.5, 2.0):
prev = 1.0
for k in range(1, 60):
d = analytic_delta(1.0, 0.1 * k, eps)
assert d <= prev
prev = d
def test_analytic_sigma_is_tight_and_beats_classical():
rng = random.Random(4)
for _ in range(500):
eps = rng.uniform(0.01, 0.99)
delta = 10 ** rng.uniform(-9, -1)
sens = rng.uniform(0.5, 2.0)
s = analytic_sigma(sens, eps, delta)
assert analytic_delta(sens, s, eps) <= delta
assert analytic_delta(sens, s * (1 - 1e-6), eps) > delta
assert s <= classical_sigma(sens, eps, delta)
def test_classical_formula_fails_outside_its_range():
# A measurement: with epsilon = 10 the classical sigma gives a larger delta than asked.
s = math.sqrt(2 * math.log(1.25 / 1e-3)) / 10
assert analytic_delta(1, s, 10) > 1e-3
with pytest.raises(ValueError):
classical_sigma(1, 10, 1e-3)
def test_privacy_loss_is_gaussian_by_monte_carlo():
# L = ln p(Y) / q(Y) with Y ~ p is N(mu^2 / 2, mu^2), mu = Delta / sigma.
# delta(eps) = E[max(0, 1 - e^(eps - L))], a mean of [0, 1] values.
rng = random.Random(31)
n = 2000
for sens, sigma, eps in ((1.0, 1.0, 1.0), (1.0, 2.0, 0.5), (2.0, 1.5, 0.2)):
total = 0.0
for _ in range(n):
y = rng.gauss(0.0, sigma)
loss = gaussian_log_density(y, 0.0, sigma) - gaussian_log_density(y, sens, sigma)
total += max(0.0, 1 - math.exp(eps - loss))
assert abs(total / n - analytic_delta(sens, sigma, eps)) <= dpkit.hoeffding_margin(n, 1e-6)
def test_log_ratio_is_unbounded_so_no_pure_dp():
sigma = 1.0
px = lambda z: gaussian_log_density(z, 0.0, sigma)
py = lambda z: gaussian_log_density(z, 1.0, sigma)
narrow = dpkit.log_ratio_grid(px, py, [i / 10 for i in range(-30, 31)])
wide = dpkit.log_ratio_grid(px, py, [i / 10 for i in range(-300, 301)])
assert abs(narrow - 3.5) < 1e-9
assert abs(wide - 30.5) < 1e-9
def test_sampler_tail_and_coordinates():
rng = random.Random(55)
n = 2000
eps, delta = 1.0, 1e-5
sigma = analytic_sigma(1.0, eps, delta)
t = 1.5 * sigma
hits = 0
for _ in range(n):
y = gaussian_mechanism(None, lambda _: [0.0], 1.0, eps, delta, rng)
hits += abs(y[0]) > t
assert abs(hits / n - math.erfc(t / (sigma * math.sqrt(2)))) <= dpkit.hoeffding_margin(n, 1e-6)
out = gaussian_mechanism([1.0, 2.0, 3.0], lambda v: v, 1.0, 0.5, 1e-5, rng, analytic=False)
assert len(out) == 3
def test_edge_cases():
rng = random.Random(0)
with pytest.raises(ValueError):
classical_sigma(1, 0.5, 0)
with pytest.raises(ValueError):
analytic_sigma(1, 1, 1)
with pytest.raises(ValueError):
analytic_delta(0, 1, 1)
assert gaussian_mechanism(None, lambda _: [], 1.0, 1.0, 1e-5, rng) == []
# At epsilon = 0, sigma = Delta / (2 delta) is enough (Balle and Wang, Theorem 2).
assert analytic_delta(1, 1 / (2 * 0.01), 0) <= 0.01
History
Dwork, Kenthapadi, McSherry, Mironov and Naor (EUROCRYPT 2006) introduced the additive in the definition and used Gaussian noise, which is a sum of many small contributions in their distributed setting. Dwork and Roth (2014) give the classical bound for with its proof, and note that the bound is folklore. Balle and Wang (ICML 2018) showed that the classical bound is loose for small and does not extend to large , and gave the exact condition. Bun and Steinke (2016), Mironov (2017) and Dong, Roth and Su (2019) built the zCDP, RDP and GDP frameworks around the normal privacy loss of this mechanism.
References
- Cynthia Dwork, Krishnaram Kenthapadi, Frank McSherry, Ilya Mironov and Moni Naor, Our data, ourselves: privacy via distributed noise generation, EUROCRYPT 2006, LNCS 4004, pages 486 to 503, the relaxed definition with an additive delta and the use of Gaussian noise
- 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.5.3, Definition 3.8 (l2 sensitivity) and Theorem 3.22 (the classical bound, for epsilon in (0, 1)); Appendix A, Theorem A.1 (the same theorem with its proof)
- Borja Balle and Yu-Xiang Wang, Improving the Gaussian mechanism for differential privacy: analytical calibration and optimal denoising, ICML 2018, PMLR 80, Theorem 1 (the classical mechanism), Lemma 3 (the privacy loss is Gaussian), Theorem 5 (the exact condition for (epsilon, delta)-DP), Theorem 8 (the analytic Gaussian mechanism)
- Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, pages 650 to 661, why floating-point noise is not private
- Clement L. Canonne, Gautam Kamath and Thomas Steinke, The discrete Gaussian for differential privacy, NeurIPS 2020, the discrete Gaussian and its exact sampler
Where this leads
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 B229GK Edit this page History Report an error Markdown