Algorithmcore
Exponential mechanism
Also called McSherry-Talwar mechanism.
Picks an output with probability proportional to e^(epsilon times its utility over twice the sensitivity); the factor 2 can be dropped when the utility is monotone in the data.
- Time
- O(m q) worst
- Space
- O(m) extra
- Where
- m = the number of candidates; q = the cost of one evaluation of the utility
- Model
- Real RAM
- Properties
- randomizedrandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Frank McSherry, Kunal Talwar, 2007
The exponential mechanism selects one item from a set of candidates, such as a price, a threshold or a model, so that good items are likely and the choice is -differentially private. Each candidate has a utility that depends on the dataset , and the mechanism outputs with probability proportional to , where is the sensitivity of . When the utility is monotone in the data, the factor 2 can be dropped. It is the general tool for private selection when adding noise to the output makes no sense, and McSherry and Talwar (2007) introduced it to design auctions.
In plain words
You want to choose the most popular of several options from votes, but you must not let the choice reveal any one vote. So you choose at random, and you give each option a weight that grows exponentially with its number of votes. One vote changes the count of an option by at most one, so it changes each weight by at most a fixed factor. Then the probability of each choice changes very little when one voter leaves.
The best option is the most likely choice. An option that is far behind is exponentially unlikely, so the chosen option is almost always close to the best. The price for privacy is a small loss of utility that grows only with the logarithm of the number of options.
The problem
The input is a dataset , a finite list of candidates that does not depend on , a utility function , a number and a privacy parameter . The sensitivity of is
and the mechanism needs . The page uses add/remove neighbors unless it says otherwise. The utility is monotone under a neighbor relation if, for every pair , either for all or for all . A count of votes for each option is monotone under add/remove, because a new record never lowers a count. It is not monotone under replace, where one count rises and another count falls.
The output is one candidate . The map from to the distribution of must be -DP, and must be close to with high probability. The output distribution is
The algorithm
EXPONENTIAL-MECHANISM(x, R, u, Delta, epsilon, monotone) ▷ R = (r_1, ..., r_m), Delta >= the sensitivity of u- 1
c <- 1 if monotone else 2 - 2
s_r <- epsilon u(x, r) / (c Delta) for each r in R - 3
M <- the largest s_r - 4
w_r <- exp(s_r - M) for each r in R - 5
W <- the sum of all w_r - 6
draw U uniform in [0, 1); t <- U W - 7
for r <- r_1 to r_m do - 8
t <- t - w_r - 9
if t < 0 then return r - 10
return r_m ▷ reached only by float rounding
Line L1 picks the factor of the exponent. Line L2 computes the scores, and this is the only line that reads the data. Lines L3 and L4 subtract the largest score before the exponential. This divides every weight by the same number , so the distribution does not change, but no weight overflows and the largest weight is 1. Lines L5 to L9 sample one candidate with probability by inverse transform sampling on the list: the candidate whose interval of length holds the point is returned. In exact arithmetic the loop always returns, and line L10 only guards against rounding. Only the output is published; the scores and the weights are never published.
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, for the same reasons as the Laplace mechanism (Mironov 2012).
Example
The candidates are and the dataset is the list of votes . The utility is the number of votes for , so the counts are and under both neighbor relations. Take and the general version, so . Assume that line L6 draws .
| step | value |
|---|---|
| L1 | |
| L2 | |
| L3 | |
| L4 | |
| L5 | |
| L6 | |
| L7 to L9, | , not negative |
| L7 to L9, | , so return |
The output distribution is . Counts are monotone under add/remove, so the version with is also -DP there, and it gives , which puts more weight on the best option.
A larger example shows the utility bound. With counts , and , the distribution is . The utility theorem below with says that the output has utility at most with probability at most . The actual probability of that event, the output or , is .
Correctness
Theorem (privacy; McSherry and Talwar 2007; Dwork-Roth Theorem 3.10). If , then EXPONENTIAL-MECHANISM with is -DP under the neighbor relation that defines .
The key step splits the ratio of the probabilities into the ratio of the weights and the ratio of the normalizers. For and every ,
Theorem (monotone utility). If and is monotone under the neighbor relation, then the version with is -DP. Dwork and Roth define monotone functions and use them for the noisy arg-max in Section 3.4, but they do not state this theorem for the exponential mechanism, so the proof is here. Take with for all . In the ratio for , the first factor is at most 1 and the second at most . In the ratio for the other order, the first factor is at most and the second at most 1. In both orders the product is at most .
Theorem (utility; Dwork-Roth Theorem 3.11 and Corollary 3.12). For every and , the output satisfies
The proof: each bad candidate has weight at most , there are at most of them, and the normalizer is at least the weight of a best candidate. Dwork and Roth state it for with in place of , where is the set of best candidates.
The proofs in full, with the proof that lines L3 to L10 sample the right distribution, are in the correctness proof of this page.
Proof: The exponential mechanism samples the right distribution, is epsilon-DP, and has high utilityfull
We work in the real RAM. Fix a neighbor relation , a finite list of candidates with , a utility , a number with , and . Let be the value of line L1. For a dataset write
Lemma 1 (the sampler). In exact arithmetic, EXPONENTIAL-MECHANISM returns with probability , and line L10 is reached with probability 0.
Proof. Lines L2 to L4 give , and line L5 gives . So ; the shift by does not change the ratios. Every , and with equality for a candidate with the largest score, so no weight overflows. Let , with and . After the -th pass of line L8, . So the loop returns at the first with , which is the with . Since is uniform on , is uniform on , and this event has probability . Since , some returns, and line L10 is never reached.
Theorem 1 (privacy with ). If , then for all and every set , .
Proof. Fix . For every , , so . Hence for every , and the sum over gives . So
The sum over of gives the claim, and Lemma 1 says that is the output distribution. The relation is symmetric, so the claim also holds with and swapped.
Theorem 2 (privacy with for a monotone utility). Assume that for every pair , either for all , or for all . If , then for all and every , .
Proof. Fix . By symmetry of the relation we may name the pair so that for all , and we must prove the bound in both orders. With , for every . Summing the exponentials over gives . Then
The sum over gives the claim in both orders.
The hypothesis is needed. Under replace neighbors, the count of one candidate rises by 1 and the count of another falls by 1, so the counts are not monotone. Take , the count, , and , with the replace neighbors and . The scores are and , so and . The log ratio is , so the version with is not -DP under replace. Both factors of the ratio move against here: its own score falls, and the normalizer grows.
Theorem 3 (utility). For every and , let and . Then .
Proof. Let . For , . There are at most candidates in , so . A candidate with gives . By Lemma 1, .
If the set of best candidates has more than one element, the bound on improves by the factor , and the same proof gives in place of , which is Dwork-Roth Theorem 3.11.
Lemma 2 (the Gumbel max trick). Let be independent standard Gumbel variables, with . Then has the distribution .
Proof. Write . The index wins when for all ; ties have probability 0. Given , this has probability , with . The density of is , so
with the substitution , which turns the integral into .
Complexity
The model is the real RAM: an exponential, a uniform real number and an addition each cost one step. One evaluation of costs steps.
- Time. Line L2 evaluates once for each of the candidates, in time. Lines L3 to L5 and the loop of lines L7 to L9 each take time. So the time is in the worst case.
- Space. The scores and the weights take numbers. A version that computes each score twice, once for and and once in the loop, needs only extra space and time.
When is very large, as in SmallDB, where the candidates are all small databases, the running time is the main cost. The privacy and the utility do not depend on how the sampler works.
Properties
- Pure privacy. The output is -DP. The tests compute the exact output distribution on every dataset of at most 4 votes over 3 options, with . The largest log ratio is 0.433 under add/remove and 0.775 under replace for , and 0.977 under add/remove for (a measurement on the test data). So for counts under add/remove, the factor 2 wastes about half of the budget.
- Utility that grows like . The loss is with high probability, and it does not depend on the size of the dataset. A utility that grows with , such as a count, gives a relative loss that goes to 0.
- Any output set. The candidates can be numbers, strings, graphs or models. McSherry and Talwar allow an infinite set with a base measure , with a density proportional to with respect to .
- It contains the Laplace mechanism. On with and , the output density is proportional to . This utility is not monotone, so and the noise is , twice the scale of the Laplace mechanism.
- Closed under post-processing. Any map of the output that does not read keeps -DP, by the post-processing theorem.
Variants and improvements
- Gumbel noise. Add an independent standard Gumbel sample to each score and output the index of the largest. This samples exactly the distribution of the exponential mechanism, by the Gumbel max trick (Dwork-Roth Remark 3.1). It needs no normalizer and works in one pass over a stream of candidates. The tests check it against the exact distribution.
- Laplace or exponential noise. Report noisy max adds Laplace noise to each count and reports the index of the largest. Report one-sided noisy arg-max adds one-sided exponential noise with parameter for a monotone utility and otherwise (Dwork-Roth Theorem 3.13). Both have guarantees similar to the exponential mechanism, but give different distributions.
- Query release. MWEM uses the exponential mechanism to pick the query with the largest error in each round, and SmallDB uses it to pick a small synthetic database. See private query release.
- Private median and quantiles. With over a finite grid of values , the output is an approximate median. This utility has sensitivity at most 1 under both neighbor relations, and it is not monotone.
When to use it
Use the exponential mechanism to choose one item from a discrete set: the best of several options, a price, a split of a decision tree, a parameter from a grid. The output space has no useful metric, or noise on the output would destroy it. When the utility is a count and you only need the index of the best item, report noisy max is a simple alternative with the same kind of guarantee. When the answer is a number and you want to add noise, use the Laplace or the Gaussian mechanism. The candidate set must be fixed before the data are read.
Pitfalls
- The monotone flag under the wrong relation. Counts are monotone under add/remove but not under replace. The version with has a largest log ratio of 1.866 under replace in the tests, for , so it is only about -DP there. Use only after you check that every pair of neighbors moves all utilities in the same direction.
- A candidate set that depends on the data. If is built from the values in , such as the set of values that occur, then the presence of a candidate leaks a record. Fix in advance, for example as a grid.
- The sensitivity of one candidate. must bound the change of for every at the same time, and over all pairs of neighbors. A bound at the actual is local sensitivity and is not private.
- Overflow. Without lines L3 and L4, overflows for scores above about 709 in 64-bit floats. The tests run it with utilities up to .
- Float sampling. Lines L6 to L9 on floats with a non-cryptographic generator are fine for study, but a release needs an exact 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
exponential_mechanism.py 90 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/exponential-mechanism/. The authors are listed in prov/T51N2F.jsonl.
"""The exponential mechanism of McSherry and Talwar.
It picks a candidate r with probability proportional to
exp(epsilon u(x, r) / (c Delta)), where Delta is the sensitivity of the
utility u and c = 2 in general. When u is monotone in the data (one step to a
neighbor moves every utility in the same direction), c = 1 is enough.
The scores are shifted by their maximum before exp, so large utilities do
not overflow. Floats and random.Random are used so that the tests are
reproducible; a deployment needs a cryptographic source of randomness and an
exact sampler.
"""
from __future__ import annotations
import math
import random
from typing import Callable, Hashable, Sequence, TypeVar
X = TypeVar("X")
R = TypeVar("R", bound=Hashable)
def _scores(x: X, candidates: Sequence[R], u: Callable[[X, R], float], sensitivity: float, epsilon: float, monotone: bool) -> list[float]:
if not candidates:
raise ValueError("need at least one candidate")
if sensitivity <= 0 or epsilon <= 0:
raise ValueError("need sensitivity > 0 and epsilon > 0")
c = 1.0 if monotone else 2.0
return [epsilon * u(x, r) / (c * sensitivity) for r in candidates]
def exponential_mechanism(
x: X,
candidates: Sequence[R],
u: Callable[[X, R], float],
sensitivity: float,
epsilon: float,
rng: random.Random,
monotone: bool = False,
) -> R:
"""Sample r with probability proportional to exp(epsilon u(x, r) / (c Delta)).
Precondition: a nonempty candidate list, Delta >= the sensitivity of u in
the data for every r, and epsilon > 0. Use monotone=True only if u is
monotone in the data under the chosen neighbor relation.
Cost: O(|R|) evaluations of u and O(|R|) other operations.
"""
if not candidates:
raise ValueError("need at least one candidate")
if sensitivity <= 0 or epsilon <= 0:
raise ValueError("need sensitivity > 0 and epsilon > 0")
c = 1.0 if monotone else 2.0 # @line L1
s = [epsilon * u(x, r) / (c * sensitivity) for r in candidates] # @line L2
m = max(s) # @line L3
w = [math.exp(si - m) for si in s] # @line L4
total = sum(w) # @line L5
t = rng.random() * total # @line L6
for r, wr in zip(candidates, w): # @line L7
t -= wr # @line L8
if t < 0: # @line L9
return r
return candidates[-1] # @line L10
def exponential_pmf(
x: X,
candidates: Sequence[R],
u: Callable[[X, R], float],
sensitivity: float,
epsilon: float,
monotone: bool = False,
) -> dict[R, float]:
"""The output pmf of exponential_mechanism, in floats. Cost: O(|R|)."""
s = _scores(x, candidates, u, sensitivity, epsilon, monotone)
m = max(s)
w = [math.exp(si - m) for si in s]
total = sum(w)
out: dict[R, float] = {}
for r, wr in zip(candidates, w):
out[r] = out.get(r, 0.0) + wr / total
return out
def utility_threshold(opt: float, sensitivity: float, epsilon: float, n_candidates: int, t: float, monotone: bool = False) -> float:
"""OPT - (c Delta / epsilon)(ln |R| + t); the output falls below it with probability at most e^(-t)."""
c = 1.0 if monotone else 2.0
return opt - c * sensitivity / epsilon * (math.log(n_candidates) + t)
test_exponential_mechanism.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/exponential-mechanism/. The authors are listed in prov/T51N2F.jsonl.
import itertools
import math
import random
import pytest
import dpkit
from exponential_mechanism import exponential_mechanism, exponential_pmf, utility_threshold
UNIVERSE = (0, 1, 2)
CANDIDATES = (0, 1, 2)
def count(x, r):
"""Utility of candidate r: the number of records equal to r. Sensitivity 1."""
return sum(1 for v in x if v == r)
def all_datasets(max_n):
for n in range(max_n + 1):
for x in itertools.combinations_with_replacement(UNIVERSE, n):
yield x
def worst_loss(mech, pairs):
best = 0.0
for x, y in pairs:
p, q = mech(x), mech(y)
best = max(best, dpkit.max_privacy_loss(p, q), dpkit.max_privacy_loss(q, p))
return best
ADD_REMOVE = [(x, y) for x in all_datasets(4) for y in dpkit.neighbors_add_remove(x, UNIVERSE)]
REPLACE = [(x, y) for x in all_datasets(4) for y in dpkit.neighbors_replace(x, UNIVERSE)]
def oracle_pmf(x, eps, c):
"""Direct normalization without the max shift."""
w = {r: math.exp(eps * count(x, r) / c) for r in CANDIDATES}
total = sum(w.values())
return {r: v / total for r, v in w.items()}
def test_pmf_matches_direct_normalization():
rng = random.Random(12)
for _ in range(500):
n = rng.randint(0, 8)
x = tuple(rng.choice(UNIVERSE) for _ in range(n))
eps = rng.uniform(0.05, 3.0)
for monotone, c in ((False, 2.0), (True, 1.0)):
got = exponential_pmf(x, CANDIDATES, count, 1.0, eps, monotone)
want = oracle_pmf(x, eps, c)
for r in CANDIDATES:
assert abs(got[r] - want[r]) < 1e-12
def test_general_version_is_epsilon_dp_under_both_relations():
eps = 1.0
mech = lambda x: exponential_pmf(x, CANDIDATES, count, 1.0, eps)
assert dpkit.is_pure_dp(mech, REPLACE, eps)
assert dpkit.is_pure_dp(mech, ADD_REMOVE, eps)
# Counts are monotone under add/remove, so the factor 2 wastes half the budget there.
assert worst_loss(mech, ADD_REMOVE) <= eps / 2 + 1e-12
def test_monotone_version_is_epsilon_dp_under_add_remove():
eps = 1.0
mech = lambda x: exponential_pmf(x, CANDIDATES, count, 1.0, eps, monotone=True)
assert dpkit.is_pure_dp(mech, ADD_REMOVE, eps)
assert worst_loss(mech, ADD_REMOVE) > 0.9 * eps
def test_monotone_flag_breaks_under_replace():
# Under replace one count rises and another falls, so the utility is not monotone.
eps = 1.0
mech = lambda x: exponential_pmf(x, CANDIDATES, count, 1.0, eps, monotone=True)
assert not dpkit.is_pure_dp(mech, REPLACE, eps)
assert worst_loss(mech, REPLACE) <= 2 * eps + 1e-12
def test_utility_bound_holds_exactly():
rng = random.Random(13)
for _ in range(500):
m = rng.randint(1, 12)
cands = tuple(range(m))
n = rng.randint(0, 30)
x = tuple(rng.randrange(m) for _ in range(n))
eps = rng.uniform(0.1, 2.0)
t = rng.uniform(0.0, 4.0)
monotone = rng.random() < 0.5
pmf = exponential_pmf(x, cands, count, 1.0, eps, monotone)
opt = max(count(x, r) for r in cands)
thr = utility_threshold(opt, 1.0, eps, m, t, monotone)
bad = sum(p for r, p in pmf.items() if count(x, r) <= thr)
assert bad <= math.exp(-t) + 1e-12
def test_sampler_matches_pmf():
rng = random.Random(14)
n = 2000
x = (0, 0, 0, 1, 1, 2)
t = dpkit.hoeffding_margin(n, 1e-6 / 3)
for eps in (0.5, 2.0):
pmf = exponential_pmf(x, CANDIDATES, count, 1.0, eps)
emp = dpkit.empirical_pmf(exponential_mechanism(x, CANDIDATES, count, 1.0, eps, rng) for _ in range(n))
for r in CANDIDATES:
assert abs(emp.get(r, 0.0) - pmf[r]) <= t
def test_gumbel_argmax_gives_the_same_distribution():
# Adding Gumbel noise to the scores and taking the argmax samples the same pmf.
rng = random.Random(15)
n = 2000
x = (0, 1, 1, 2, 2, 2)
eps = 1.0
pmf = exponential_pmf(x, CANDIDATES, count, 1.0, eps)
picks = []
for _ in range(n):
noisy = [eps * count(x, r) / 2 - math.log(-math.log(1.0 - rng.random())) for r in CANDIDATES]
picks.append(max(CANDIDATES, key=lambda r: noisy[r]))
emp = dpkit.empirical_pmf(picks)
t = dpkit.hoeffding_margin(n, 1e-6 / 3)
for r in CANDIDATES:
assert abs(emp.get(r, 0.0) - pmf[r]) <= t
def test_large_utilities_do_not_overflow():
rng = random.Random(16)
big = lambda x, r: 1e6 * r
pmf = exponential_pmf(None, (0, 1, 2), big, 1.0, 1.0)
assert pmf[2] == pytest.approx(1.0)
assert exponential_mechanism(None, (0, 1, 2), big, 1.0, 1.0, rng) == 2
def test_edge_cases():
rng = random.Random(0)
with pytest.raises(ValueError):
exponential_mechanism((), (), count, 1.0, 1.0, rng)
with pytest.raises(ValueError):
exponential_mechanism((), (0,), count, 1.0, 0.0, rng)
with pytest.raises(ValueError):
exponential_pmf((), (0,), count, 0.0, 1.0)
assert exponential_mechanism((), ("only",), lambda x, r: 0.0, 1.0, 1.0, rng) == "only"
# Equal utilities give the uniform distribution.
pmf = exponential_pmf((), CANDIDATES, count, 1.0, 1.0)
assert all(abs(p - 1 / 3) < 1e-15 for p in pmf.values())
History
McSherry and Talwar (FOCS 2007) defined the exponential mechanism with a base measure on the output set and proved its privacy and utility bounds. They used it to build auctions in which no bidder gains much by lying, because no single bid changes the outcome distribution much, and so tied differential privacy to mechanism design. Dwork and Roth (2014) give the finite form of this page, the utility bound with , and the remark that Gumbel noise samples the same distribution. The mechanism is the selection step of many later algorithms, such as MWEM and SmallDB.
References
- Frank McSherry and Kunal Talwar, Mechanism design via differential privacy, FOCS 2007, pages 94 to 103, the definition of the exponential mechanism with a base measure, its privacy theorem and its utility bound
- 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.4, Definition 3.4 (the mechanism), Theorem 3.10 (privacy), Theorem 3.11 and Corollary 3.12 (utility), the definition of a monotonic function, Theorem 3.13 (report one-sided noisy arg-max) and Remark 3.1 (the Gumbel max trick)
- Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, pages 650 to 661, why a float sampler is not enough for a release
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 T51N2F Edit this page History Report an error Markdown