Algorithmintro
Laplace mechanism
Also called Laplace noise mechanism.
Adds Laplace noise with scale equal to the l1 sensitivity over epsilon to a numeric query, which gives epsilon-differential privacy.
- Time
- O(k) worst
- Space
- O(k) extra
- Where
- k = the number of coordinates of the query
- Model
- Real RAM
- Properties
- randomizedrandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Cynthia Dwork, Frank McSherry, Kobbi Nissim, Adam Smith, 2006
The Laplace mechanism answers a numeric query about a private dataset with noise from the Laplace distribution added to each coordinate. The scale of the noise is the global sensitivity divided by , and then the output is -differentially private. The error of each coordinate is about and does not grow with the size of the dataset. It is the first mechanism of differential privacy, and the geometric mechanism and the Gaussian mechanism are its discrete and its versions.
In plain words
You want to publish a count, such as the number of people in a table who have a disease. One person can change that count by at most one. So you add random noise that is often of size about one, and sometimes larger. Then the published number looks almost the same whether or not a given person is in the table.
The noise comes from a fixed bell-like shape with a sharp peak at zero and two tails that fall at a steady rate. A smaller privacy budget gives wider noise. A query that one person can change more also gets wider noise. The noise does not depend on how many people are in the table, so a large table gives an accurate answer.
The problem
The input is a dataset of records from a universe , a query that maps datasets to , a number , and a privacy parameter . Here
where means that and are neighbors. The page uses add/remove neighbors unless it says otherwise: is with one record added or removed. Under replace neighbors, where one record changes and stays fixed, the same query can have a larger sensitivity. A histogram has under add/remove and under replace.
The output is a random vector . The map from to the distribution of must be -differentially private, and must be close to .
The Laplace distribution with scale has the density and the distribution function
Its mean is 0, its variance is , its mean absolute value is , and for .
The algorithm
LAPLACE-MECHANISM(x, f, Delta, epsilon) ▷ Delta >= the l1 sensitivity of f- 1
b <- Delta / epsilon - 2
v <- f(x) ▷ v = (v_1, ..., v_k) - 3
for i <- 1 to k do - 4
draw u uniform in (-1/2, 1/2) ▷ draw again if u = -1/2 - 5
z <- -b sgn(u) ln(1 - 2|u|) ▷ the inverse of F_b at u + 1/2 - 6
y_i <- v_i + z - 7
return y = (y_1, ..., y_k)
Line L1 sets the scale. Line L2 computes the true answer, and this is the only line that reads the data. Lines L4 and L5 draw one sample of by inverse transform sampling: if is uniform, then has the distribution function . Line L6 adds an independent sample to each coordinate. The output of line L7 is the only thing that is published. The noise of line L4 is never published, and it is never used again.
The code on this site uses floats and a seeded pseudorandom generator, 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; Canonne, Kamath and Steinke 2020). The discrete Gaussian mechanism page shows the exact samplers.
Example
The universe is and the dataset is , with . The query is the histogram , with under add/remove neighbors. With , line L1 gives . Assume that line L4 draws , and .
| step | (line L5) | (line L6) | |||
|---|---|---|---|---|---|
| L1, L2 | , | ||||
| L3 to L6 | 1 | 2 | 0.3 | 2.916291 | |
| L3 to L6 | 2 | 1 | 0.776856 | ||
| L3 to L6 | 3 | 3 | 0.45 | 5.302585 | |
| L7 |
The accuracy theorem below says that, with probability at least , each of the errors is at most . Here the largest error is 2.302585.
A second check: with and , the scale is , the variance of the noise is 8, and .
Correctness
Theorem (Dwork, McSherry, Nissim and Smith 2006; Dwork-Roth Theorem 3.6). If under a neighbor relation, then LAPLACE-MECHANISM is -differentially private under that relation.
The key step is a bound on the ratio of the output densities. For neighbors and every output , the triangle inequality gives
The integral of this bound over a set of outputs gives the definition. The full proof, with the proof that lines L4 and L5 sample and the proof of the accuracy bound, is in the correctness proof of this page.
Theorem (accuracy, Dwork-Roth Theorem 3.8). For , with probability at least , . The proof is a union bound over the tails .
Proof: The Laplace mechanism samples the right noise, is epsilon-DP, and is accuratefull
We work in the real RAM. Fix a neighbor relation , a query with values in , a number , and . Let (line L1). We write for the density of and for its distribution function.
Lemma 1 (the sampler). If is uniform on , then of line L5 has the distribution .
Proof. Let , which is uniform on . We show that . If , then and . This is negative, and . If , then and , and . ( gives with either sign.) is continuous and strictly increasing, so for every .
So, by Lemma 1 and because each pass of line L3 draws a fresh , the output of line L7 is with and independent . Its density at is
Theorem 1 (privacy). For all and every measurable set , , where is LAPLACE-MECHANISM with the parameters above.
Proof. Fix and . For each , the triangle inequality gives . So
The last step uses . Both densities are positive everywhere, so for all . The integral over gives
The relation is symmetric, so the same holds with and swapped.
Theorem 2 (accuracy). For , .
Proof. For , . Take , so that . The union bound over the coordinates gives . Since , this is the claim.
Termination. The loop of line L3 runs times. Line L4 draws again only on the event , which has probability 0 in the real RAM, so each pass ends with probability 1.
Lemma 1, Theorem 1 and Theorem 2 together show that the output has the stated distribution, is -differentially private under the relation for which , and has error at most in every coordinate with probability at least .
Complexity
The model is the real RAM: a uniform real number in , a logarithm and an addition each cost one step. The cost is counted per query, after the one evaluation of in line L2.
- Time. The loop of line L3 runs times. Each pass draws one uniform number and does arithmetic. The event of line L4 has probability 0 in this model. So the time is in the worst case.
- Space. The output has numbers, and the loop keeps other numbers. So the extra space is .
On real machines with 53-bit floats, line L4 draws again with probability , so the expected number of draws is still .
Properties
- Pure privacy. The output is -DP. The bound is tight: when has one nonzero coordinate equal to , the ratio of the densities is exactly on a half-line of outputs. The tests check this on a grid (a measurement on the test data: the largest log ratio is 0.5 for ).
- Unbiased. , and each coordinate has variance and mean absolute error .
- No dependence on . The error is the same for 10 records and for records. The relative error of a count of size is about .
- Closed under post-processing. Rounding, clamping or any other map of that does not read keeps -DP, by the post-processing theorem.
- Composition. Two runs on the same data with and are -DP together, by the sequential composition theorem.
Variants and improvements
- Integer outputs. The geometric mechanism adds the discrete analog of Laplace noise to an integer query. It needs no floats.
- The version. The Gaussian mechanism calibrates to and gives -DP. For counts that one record can all change by one, and , so the Gaussian error is much smaller for large .
- Snapping. Mironov (2012) rounds and clamps the float output so that the low-order bits no longer depend on the data. This gives a slightly larger , which his paper bounds.
- Data-dependent noise. Smooth sensitivity and propose-test-release add less noise when the dataset is far from the worst case, such as for a median.
- Selection. To publish only the index of the largest of counts, report noisy max adds Laplace noise and releases only the index.
- Release of a model. Output perturbation adds Laplace or Gaussian noise to the parameters of a trained model, with the sensitivity of the training map.
When to use it
Use the Laplace mechanism for a small number of numeric queries with a low sensitivity, when you need pure -DP: counts, histograms, and sums or means of values that are clipped to a known range. If the answer is an integer and you want integer output with exact sampling, use the geometric mechanism. If you answer many queries, or the sensitivity is much smaller than the sensitivity, and a small is acceptable, the Gaussian mechanism adds less noise. If you need the best item of a set and not a number, use the exponential mechanism or report noisy max.
Pitfalls
- The sensitivity of the wrong neighbor relation. A histogram has under add/remove and 2 under replace. Line L1 with is only -DP under replace. The tests measure a log ratio of 1.0 for there. Under replace, line L1 must use , and then .
- The scale of one coordinate. For queries that one record can each change by 1, line L1 with gives only -DP. Line L1 must use the sensitivity of the whole vector, .
- Local sensitivity. Line L1 with the change of at the actual , in place of the maximum over all neighbor pairs, is not private, because the scale itself then depends on the data. Use the global , or the methods of smooth sensitivity.
- Float noise. Lines L4 and L5 on floats with a non-cryptographic generator are fine for study, but not for a release (Mironov 2012). Use an exact sampler from a cryptographic source, or the snapping mechanism.
- Fresh noise for a repeated query. Each call of the mechanism draws fresh noise in line L4 and costs again. The average of answers to one query has times the cost. Store and reuse a published answer.
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
laplace_mechanism.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/laplace-mechanism/. The authors are listed in prov/ZJZCN9.jsonl.
"""The Laplace mechanism of Dwork, McSherry, Nissim and Smith (2006).
The code uses random.Random so that the tests are reproducible, 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 the float version leaks through its low-order bits (Mironov 2012).
"""
from __future__ import annotations
import math
import random
from typing import Callable, Sequence, TypeVar
D = TypeVar("D")
def laplace_scale(sensitivity: float, epsilon: float) -> float:
"""The noise scale b = sensitivity / epsilon. Precondition: both are positive."""
if sensitivity <= 0 or epsilon <= 0:
raise ValueError("sensitivity and epsilon must be positive")
return sensitivity / epsilon
def laplace_from_uniform(u: float, b: float) -> float:
"""The Lap(b) quantile at u + 1/2, for u in the open interval (-1/2, 1/2).
This is the inverse of the CDF F(z) = e^(z/b)/2 for z < 0 and
1 - e^(-z/b)/2 for z >= 0. Cost: O(1).
"""
if not -0.5 < u < 0.5:
raise ValueError("u must be in (-1/2, 1/2)")
s = (u > 0) - (u < 0)
return -b * s * math.log(1.0 - 2.0 * abs(u))
def laplace_mechanism(
x: D,
f: Callable[[D], Sequence[float]],
sensitivity: float,
epsilon: float,
rng: random.Random,
) -> list[float]:
"""Release f(x) plus independent Lap(sensitivity / epsilon) noise on each coordinate.
Precondition: sensitivity is at least the l1 sensitivity of f under the
neighbor relation that the caller uses, and epsilon > 0. Then the output
is epsilon-differentially private for that relation.
Cost: one evaluation of f, then O(k) time and k uniform draws for k coordinates.
"""
b = laplace_scale(sensitivity, epsilon) # @line L1
v = list(f(x)) # @line L2
y: list[float] = []
for vi in v: # @line L3
u = rng.random() - 0.5 # @line L4
while u == -0.5: # the open interval excludes -1/2
u = rng.random() - 0.5
z = laplace_from_uniform(u, b) # @line L5
y.append(vi + z) # @line L6
return y # @line L7
def laplace_log_density(y: Sequence[float], center: Sequence[float], b: float) -> float:
"""The log density at y of center plus k independent Lap(b) coordinates. Cost: O(k)."""
return sum(-math.log(2.0 * b) - abs(yi - ci) / b for yi, ci in zip(y, center))
def laplace_tail(t: float, b: float) -> float:
"""P(|Z| > t) = e^(-t/b) for Z ~ Lap(b) and t >= 0."""
return math.exp(-t / b)
def laplace_error_bound(k: int, b: float, beta: float) -> float:
"""The bound b ln(k / beta) on the largest error over k coordinates.
With probability at least 1 - beta, every coordinate of the noise is at
most this value in absolute value (a union bound over the k tails).
"""
return b * math.log(k / beta)
test_laplace_mechanism.py 229 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/laplace-mechanism/. The authors are listed in prov/ZJZCN9.jsonl.
import itertools
import math
import random
from collections import Counter
from fractions import Fraction
import dpkit
from laplace_mechanism import (
laplace_error_bound,
laplace_from_uniform,
laplace_log_density,
laplace_mechanism,
laplace_scale,
laplace_tail,
)
UNIVERSE = (0, 1, 2)
def histogram(x):
return [sum(1 for r in x if r == v) for v in UNIVERSE]
def all_datasets(max_n):
for n in range(max_n + 1):
for x in itertools.combinations_with_replacement(UNIVERSE, n):
yield x
# ---------------------------------------------------------------- dpkit self-test
def test_dpkit_neighbors_match_multiset_distance():
rng = random.Random(11)
for _ in range(500):
n = rng.randint(0, 4)
x = tuple(rng.choice(UNIVERSE) for _ in range(n))
cx = Counter(x)
got = {tuple(sorted(y)) for y in dpkit.neighbors_add_remove(x, UNIVERSE)}
assert len(got) == len(dpkit.neighbors_add_remove(x, UNIVERSE))
want = set()
for m in range(n - 1, n + 2):
for y in itertools.combinations_with_replacement(UNIVERSE, max(m, 0)):
if m < 0:
continue
cy = Counter(y)
diff = sum(abs(cx[v] - cy[v]) for v in UNIVERSE)
if diff == 1:
want.add(tuple(sorted(y)))
assert got == want
got_r = {tuple(sorted(y)) for y in dpkit.neighbors_replace(x, UNIVERSE)}
want_r = set()
for y in itertools.combinations_with_replacement(UNIVERSE, n):
cy = Counter(y)
if sum(abs(cx[v] - cy[v]) for v in UNIVERSE) == 2:
want_r.add(tuple(sorted(y)))
assert got_r == want_r
def _rr_pmf(x):
# randomized response with e^epsilon = 3 on a dataset of one bit
v = x[0]
return {v: Fraction(3, 4), 1 - v: Fraction(1, 4)}
def test_dpkit_randomized_response_is_exactly_ln3_dp():
pairs = [((0,), (1,))]
assert dpkit.max_privacy_loss(_rr_pmf((0,)), _rr_pmf((1,))) == math.log(3)
assert dpkit.is_pure_dp(_rr_pmf, pairs, math.log(3))
assert not dpkit.is_pure_dp(_rr_pmf, pairs, math.log(3) - 0.01)
assert dpkit.is_approx_dp(_rr_pmf, pairs, math.log(3), 0.0)
assert not dpkit.is_approx_dp(_rr_pmf, pairs, 0.0, 0.49)
loss = dpkit.privacy_loss(_rr_pmf((0,)), _rr_pmf((1,)))
assert math.isclose(loss[0], math.log(3)) and math.isclose(loss[1], -math.log(3))
def test_dpkit_hockey_stick():
p = {0: Fraction(3, 4), 1: Fraction(1, 4)}
q = {0: Fraction(1, 4), 1: Fraction(3, 4)}
assert dpkit.hockey_stick(p, p, 0.0) == 0.0
assert dpkit.hockey_stick(p, p, 1.0) == 0.0
assert math.isclose(dpkit.hockey_stick(p, q, 0.0), 0.5) # total variation distance
assert dpkit.hockey_stick(p, q, math.log(3)) <= 1e-15
assert math.isclose(dpkit.hockey_stick(p, q, math.log(2)), 0.75 - 2 * 0.25)
assert math.isclose(dpkit.hockey_stick({0: 1.0}, {1: 1.0}, 5.0), 1.0)
assert dpkit.max_privacy_loss({0: 1.0}, {1: 1.0}) == math.inf
assert dpkit.max_privacy_loss({}, {1: 1.0}) == -math.inf
def test_dpkit_renyi_of_bernoulli():
p = {0: Fraction(3, 4), 1: Fraction(1, 4)}
q = {0: Fraction(1, 4), 1: Fraction(3, 4)}
# order 2: ln(sum p^2 / q) = ln(9/4 + 1/12) = ln(7/3)
assert math.isclose(dpkit.renyi_divergence(p, q, 2.0), math.log(7 / 3))
rng = random.Random(12)
for _ in range(500):
a, b = rng.uniform(0.01, 0.99), rng.uniform(0.01, 0.99)
alpha = rng.uniform(1.1, 8.0)
closed = math.log(a**alpha * b ** (1 - alpha) + (1 - a) ** alpha * (1 - b) ** (1 - alpha)) / (alpha - 1)
got = dpkit.renyi_divergence({1: a, 0: 1 - a}, {1: b, 0: 1 - b}, alpha)
assert math.isclose(got, closed, rel_tol=1e-9, abs_tol=1e-12)
# near alpha = 1 it tends to the KL divergence, which is ln(3)/2 here
assert abs(dpkit.renyi_divergence(p, q, 1.0 + 1e-7) - math.log(3) / 2) < 1e-6
assert dpkit.renyi_divergence({0: 1.0}, {1: 1.0}, 2.0) == math.inf
def test_dpkit_empirical_and_margin():
assert dpkit.empirical_pmf([]) == {}
assert dpkit.empirical_pmf([1, 1, 2, 3]) == {1: 0.5, 2: 0.25, 3: 0.25}
assert math.isclose(dpkit.hoeffding_margin(2000, 0.01), math.sqrt(math.log(200) / 4000))
assert dpkit.log_ratio_grid(lambda z: -abs(z), lambda z: -abs(z - 1), [-3, 0, 0.5, 4]) == 1.0
# ---------------------------------------------------------------- the Laplace mechanism
def test_check_values():
b = laplace_scale(1.0, 0.5)
assert b == 2.0
assert math.isclose(2 * b * b, 8.0)
assert math.isclose(laplace_tail(2 * math.log(10), b), 0.1)
assert abs(2 * math.log(10) - 4.6052) < 5e-5
def test_quantile_against_cdf():
rng = random.Random(21)
def cdf(z, b):
return 0.5 * math.exp(z / b) if z < 0 else 1 - 0.5 * math.exp(-z / b)
assert laplace_from_uniform(0.0, 3.0) == 0.0
for _ in range(500):
b = rng.uniform(0.1, 10)
u = rng.uniform(-0.499, 0.499)
z = laplace_from_uniform(u, b)
assert math.isclose(cdf(z, b), u + 0.5, rel_tol=1e-9, abs_tol=1e-12)
def _grid_check(relation, sensitivity, epsilon, n_max):
b = laplace_scale(sensitivity, epsilon)
grid = [(-2.0 + 0.5 * i, -2.0 + 0.5 * j, -2.0 + 0.5 * k) for i in range(0, 15, 2) for j in range(0, 15, 3) for k in range(0, 15, 3)]
worst = 0.0
for x in all_datasets(n_max):
for y in relation(x, UNIVERSE):
fx, fy = histogram(x), histogram(y)
w = dpkit.log_ratio_grid(
lambda z: laplace_log_density(z, fx, b),
lambda z: laplace_log_density(z, fy, b),
grid,
)
worst = max(worst, w)
return worst
def test_privacy_on_a_grid_add_remove():
# a histogram has l1 sensitivity 1 under add/remove
worst = _grid_check(dpkit.neighbors_add_remove, 1.0, 0.5, 3)
assert worst <= 0.5 + 1e-9
assert worst >= 0.5 - 1e-9 # the bound is attained
def test_privacy_on_a_grid_replace():
# under replace the sensitivity is 2; calibrating with 1 gives only 2 epsilon
assert _grid_check(dpkit.neighbors_replace, 1.0, 0.5, 3) >= 1.0 - 1e-9
assert _grid_check(dpkit.neighbors_replace, 2.0, 0.5, 3) <= 0.5 + 1e-9
def test_random_pairs_log_ratio():
rng = random.Random(22)
for _ in range(500):
eps = rng.uniform(0.05, 3.0)
b = laplace_scale(1.0, eps)
x = tuple(rng.choice(UNIVERSE) for _ in range(rng.randint(0, 5)))
ys = dpkit.neighbors_add_remove(x, UNIVERSE)
y = rng.choice(ys)
z = [rng.uniform(-6, 10) for _ in UNIVERSE]
loss = laplace_log_density(z, histogram(x), b) - laplace_log_density(z, histogram(y), b)
assert abs(loss) <= eps + 1e-9
def test_sampler_monte_carlo():
rng = random.Random(23)
n = 2000
zs = [laplace_mechanism((), lambda x: [0.0], 1.0, 0.5, rng)[0] for _ in range(n)]
m = dpkit.hoeffding_margin(n, 1e-3)
tail = sum(1 for z in zs if abs(z) > 2 * math.log(10)) / n
assert abs(tail - 0.1) <= m
for t in (-3.0, -1.0, 0.0, 1.0, 3.0):
cdf = 0.5 * math.exp(t / 2) if t < 0 else 1 - 0.5 * math.exp(-t / 2)
assert abs(sum(1 for z in zs if z <= t) / n - cdf) <= m
var = sum(z * z for z in zs) / n
assert abs(var - 8.0) < 2.0
def test_accuracy_bound():
rng = random.Random(24)
x = (0, 0, 1, 2, 2, 2)
fx = histogram(x)
b = laplace_scale(1.0, 1.0)
beta = 0.1
bound = laplace_error_bound(3, b, beta)
n = 2000
bad = 0
for _ in range(n):
y = laplace_mechanism(x, histogram, 1.0, 1.0, rng)
if max(abs(a - c) for a, c in zip(y, fx)) > bound:
bad += 1
assert bad / n <= beta + dpkit.hoeffding_margin(n, 1e-3)
def test_edges():
rng = random.Random(25)
assert laplace_mechanism((), lambda x: [], 1.0, 1.0, rng) == []
for bad in ((0.0, 1.0), (1.0, 0.0), (-1.0, 1.0)):
try:
laplace_scale(*bad)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
try:
laplace_from_uniform(-0.5, 1.0)
except ValueError:
pass
else:
raise AssertionError("expected ValueError")
History
Dwork, McSherry, Nissim and Smith (TCC 2006) defined the sensitivity of a query and proved that Laplace noise scaled to it gives what is now called -differential privacy. The same paper gives the privacy definition in its first form. Dwork and Roth (2014) give the mechanism in the form of this page, with the accuracy bound for coordinates. Mironov (2012) showed that the textbook float implementation is not private, and Canonne, Kamath and Steinke (2020) gave exact samplers for the discrete versions.
References
- Cynthia Dwork, Frank McSherry, Kobbi Nissim and Adam Smith, Calibrating noise to sensitivity in private data analysis, TCC 2006, LNCS 3876, pages 265 to 284, the definition of sensitivity and the mechanism that adds Laplace noise scaled to it
- 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.3, Definition 3.1 (l1 sensitivity), Definition 3.2 (the Laplace distribution), Definition 3.3 (the Laplace mechanism), Theorem 3.6 (privacy), Fact 3.7 (the tail) and Theorem 3.8 (accuracy)
- Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, pages 650 to 661, why floating-point Laplace noise is not private, and the snapping mechanism
- Clement L. Canonne, Gautam Kamath and Thomas Steinke, The discrete Gaussian for differential privacy, NeurIPS 2020, exact samplers for discrete Laplace and discrete Gaussian noise
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 ZJZCN9 Edit this page History Report an error Markdown