Algorithm Search⌘K

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
Properties
randomizedrandomized
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 ε\varepsilon-differentially private. Each candidate rr has a utility u(x,r)u(x, r) that depends on the dataset xx, and the mechanism outputs rr with probability proportional to exp⁡(εu(x,r)/(2Δ))\exp(\varepsilon u(x, r) / (2\Delta)), where Δ\Delta is the sensitivity of uu. 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 xx, a finite list R=(r1,…,rm)R = (r_1, \ldots, r_m) of candidates that does not depend on xx, a utility function u(x,r)∈Ru(x, r) \in \mathbb R, a number Δ\Delta and a privacy parameter ε>0\varepsilon > 0. The sensitivity of uu is

Δu=max⁡r∈R max⁡x∼x′∣u(x,r)−u(x′,r)∣,\Delta u = \max_{r \in R}\ \max_{x \sim x'} |u(x, r) - u(x', r)|,

and the mechanism needs Δ≥Δu\Delta \ge \Delta u. The page uses add/remove neighbors unless it says otherwise. The utility is monotone under a neighbor relation if, for every pair x∼x′x \sim x', either u(x,r)≤u(x′,r)u(x, r) \le u(x', r) for all rr or u(x,r)≥u(x′,r)u(x, r) \ge u(x', r) for all rr. 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 r∈Rr \in R. The map from xx to the distribution of rr must be ε\varepsilon-DP, and u(x,r)u(x, r) must be close to OPT(x)=max⁡ru(x,r)\mathrm{OPT}(x) = \max_{r} u(x, r) with high probability. The output distribution is

Pr⁡[output r]=exp⁡(εu(x,r)/(cΔ))∑r′∈Rexp⁡(εu(x,r′)/(cΔ)),c=2 in general,c=1 for a monotone utility.\Pr[\text{output } r] = \frac{\exp(\varepsilon u(x, r)/(c\Delta))}{\sum_{r' \in R} \exp(\varepsilon u(x, r')/(c\Delta))}, \qquad c = 2 \text{ in general}, \quad c = 1 \text{ for a monotone utility}.

The algorithm

  1. EXPONENTIAL-MECHANISM(x, R, u, Delta, epsilon, monotone) ▷ R = (r_1, ..., r_m), Delta >= the sensitivity of u
  2. 1c <- 1 if monotone else 2
  3. 2s_r <- epsilon u(x, r) / (c Delta) for each r in R
  4. 3M <- the largest s_r
  5. 4w_r <- exp(s_r - M) for each r in R
  6. 5W <- the sum of all w_r
  7. 6draw U uniform in [0, 1); t <- U W
  8. 7for r <- r_1 to r_m do
  9. 8t <- t - w_r
  10. 9if t < 0 then return r
  11. 10return 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 eMe^M, 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 wr/Ww_r / W by inverse transform sampling on the list: the candidate whose interval of length wrw_r holds the point UWU W 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 R=(A,B,C)R = (A, B, C) and the dataset is the list of votes x=(A,A,A,B,B,C)x = (A, A, A, B, B, C). The utility u(x,r)u(x, r) is the number of votes for rr, so the counts are (3,2,1)(3, 2, 1) and Δu=1\Delta u = 1 under both neighbor relations. Take ε=1\varepsilon = 1 and the general version, so c=2c = 2. Assume that line L6 draws U=0.62U = 0.62.

step value
L1 c=2c = 2
L2 s=(1.5,1,0.5)s = (1.5, 1, 0.5)
L3 M=1.5M = 1.5
L4 w=(1,e−0.5,e−1)=(1,0.606531,0.367879)w = (1, e^{-0.5}, e^{-1}) = (1, 0.606531, 0.367879)
L5 W=1.974410W = 1.974410
L6 t=0.62×1.974410=1.224134t = 0.62 \times 1.974410 = 1.224134
L7 to L9, r=Ar = A t=1.224134−1=0.224134t = 1.224134 - 1 = 0.224134, not negative
L7 to L9, r=Br = B t=0.224134−0.606531=−0.382397t = 0.224134 - 0.606531 = -0.382397, so return BB

The output distribution is (0.506480,0.307196,0.186324)(0.506480, 0.307196, 0.186324). Counts are monotone under add/remove, so the version with c=1c = 1 is also 11-DP there, and it gives (0.665241,0.244728,0.090031)(0.665241, 0.244728, 0.090031), which puts more weight on the best option.

A larger example shows the utility bound. With counts (30,20,10)(30, 20, 10), ε=1\varepsilon = 1 and c=2c = 2, the distribution is (0.993262,0.006693,0.000045)(0.993262, 0.006693, 0.000045). The utility theorem below with t=3t = 3 says that the output has utility at most 30−2(ln⁡3+3)=21.80277530 - 2(\ln 3 + 3) = 21.802775 with probability at most e−3=0.049787e^{-3} = 0.049787. The actual probability of that event, the output BB or CC, is 0.0067380.006738.

Correctness

Theorem (privacy; McSherry and Talwar 2007; Dwork-Roth Theorem 3.10). If Δ≥Δu\Delta \ge \Delta u, then EXPONENTIAL-MECHANISM with c=2c = 2 is ε\varepsilon-DP under the neighbor relation that defines Δu\Delta u.

The key step splits the ratio of the probabilities into the ratio of the weights and the ratio of the normalizers. For x∼x′x \sim x' and every rr,

Pr⁡[M(x)=r]Pr⁡[M(x′)=r]=exp⁡(ε(u(x,r)−u(x′,r))2Δ)⋅∑r′exp⁡(εu(x′,r′)/(2Δ))∑r′exp⁡(εu(x,r′)/(2Δ))≤eε/2⋅eε/2.\frac{\Pr[M(x) = r]}{\Pr[M(x') = r]} = \exp\Big(\frac{\varepsilon (u(x, r) - u(x', r))}{2\Delta}\Big) \cdot \frac{\sum_{r'} \exp(\varepsilon u(x', r')/(2\Delta))}{\sum_{r'} \exp(\varepsilon u(x, r')/(2\Delta))} \le e^{\varepsilon/2} \cdot e^{\varepsilon/2}.

Theorem (monotone utility). If Δ≥Δu\Delta \ge \Delta u and uu is monotone under the neighbor relation, then the version with c=1c = 1 is ε\varepsilon-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 x∼x′x \sim x' with u(x,r)≤u(x′,r)≤u(x,r)+Δu(x, r) \le u(x', r) \le u(x, r) + \Delta for all rr. In the ratio for Pr⁡[M(x)=r]/Pr⁡[M(x′)=r]\Pr[M(x) = r] / \Pr[M(x') = r], the first factor is at most 1 and the second at most eεe^{\varepsilon}. In the ratio for the other order, the first factor is at most eεe^{\varepsilon} and the second at most 1. In both orders the product is at most eεe^{\varepsilon}.

Theorem (utility; Dwork-Roth Theorem 3.11 and Corollary 3.12). For every xx and t≥0t \ge 0, the output rr satisfies

Pr⁡[u(x,r)≤OPT(x)−cΔε(ln⁡m+t)]≤e−t.\Pr\Big[u(x, r) \le \mathrm{OPT}(x) - \frac{c\Delta}{\varepsilon}(\ln m + t)\Big] \le e^{-t}.

The proof: each bad candidate has weight at most exp⁡(ε(OPT−(cΔ/ε)(ln⁡m+t))/(cΔ))\exp(\varepsilon(\mathrm{OPT} - (c\Delta/\varepsilon)(\ln m + t))/(c\Delta)), there are at most mm of them, and the normalizer is at least the weight exp⁡(ε OPT/(cΔ))\exp(\varepsilon\,\mathrm{OPT}/(c\Delta)) of a best candidate. Dwork and Roth state it for c=2c = 2 with ln⁡(m/∣ROPT∣)\ln(m / |R_{\mathrm{OPT}}|) in place of ln⁡m\ln m, where ROPTR_{\mathrm{OPT}} 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 ∼\sim, a finite list R=(r1,…,rm)R = (r_1, \ldots, r_m) of candidates with m≥1m \ge 1, a utility uu, a number Δ≥Δu=max⁡rmax⁡x∼x′∣u(x,r)−u(x′,r)∣\Delta \ge \Delta u = \max_{r} \max_{x \sim x'} |u(x, r) - u(x', r)| with Δ>0\Delta > 0, and ε>0\varepsilon > 0. Let cc be the value of line L1. For a dataset xx write

sx(r)=εu(x,r)cΔ,Zx=∑r∈Resx(r),Px(r)=esx(r)Zx.s_x(r) = \frac{\varepsilon u(x, r)}{c\Delta}, \qquad Z_x = \sum_{r \in R} e^{s_x(r)}, \qquad P_x(r) = \frac{e^{s_x(r)}}{Z_x}.

Lemma 1 (the sampler). In exact arithmetic, EXPONENTIAL-MECHANISM returns rjr_j with probability Px(rj)P_x(r_j), and line L10 is reached with probability 0.

Proof. Lines L2 to L4 give wr=esx(r)−M=esx(r)/eMw_r = e^{s_x(r) - M} = e^{s_x(r)}/e^M, and line L5 gives W=Zx/eMW = Z_x / e^M. So wr/W=Px(r)w_r / W = P_x(r); the shift by MM does not change the ratios. Every wr>0w_r > 0, and wr≤1w_r \le 1 with equality for a candidate with the largest score, so no weight overflows. Let Cj=wr1+⋯+wrjC_j = w_{r_1} + \cdots + w_{r_j}, with C0=0C_0 = 0 and Cm=WC_m = W. After the jj-th pass of line L8, t=UW−Cjt = UW - C_j. So the loop returns rjr_j at the first jj with UW<CjUW < C_j, which is the jj with Cj−1≤UW<CjC_{j-1} \le UW < C_j. Since UU is uniform on [0,1)[0, 1), UWUW is uniform on [0,W)[0, W), and this event has probability (Cj−Cj−1)/W=wrj/W=Px(rj)(C_j - C_{j-1})/W = w_{r_j}/W = P_x(r_j). Since UW<W=CmUW < W = C_m, some j≤mj \le m returns, and line L10 is never reached. □\square

Theorem 1 (privacy with c=2c = 2). If c=2c = 2, then for all x∼x′x \sim x' and every set S⊆RS \subseteq R, Pr⁡[M(x)∈S]≤eεPr⁡[M(x′)∈S]\Pr[M(x) \in S] \le e^{\varepsilon}\Pr[M(x') \in S].

Proof. Fix x∼x′x \sim x'. For every rr, ∣u(x,r)−u(x′,r)∣≤Δu≤Δ|u(x, r) - u(x', r)| \le \Delta u \le \Delta, so ∣sx(r)−sx′(r)∣≤ε/2|s_x(r) - s_{x'}(r)| \le \varepsilon/2. Hence esx(r)≤eε/2esx′(r)e^{s_x(r)} \le e^{\varepsilon/2} e^{s_{x'}(r)} for every rr, and the sum over rr gives Zx′≤eε/2ZxZ_{x'} \le e^{\varepsilon/2} Z_x. So

Px(r)Px′(r)=esx(r)esx′(r)⋅Zx′Zx≤eε/2⋅eε/2=eε.\frac{P_x(r)}{P_{x'}(r)} = \frac{e^{s_x(r)}}{e^{s_{x'}(r)}} \cdot \frac{Z_{x'}}{Z_x} \le e^{\varepsilon/2} \cdot e^{\varepsilon/2} = e^{\varepsilon}.

The sum over r∈Sr \in S of Px(r)≤eεPx′(r)P_x(r) \le e^{\varepsilon} P_{x'}(r) gives the claim, and Lemma 1 says that PxP_x is the output distribution. The relation is symmetric, so the claim also holds with xx and x′x' swapped. □\square

Theorem 2 (privacy with c=1c = 1 for a monotone utility). Assume that for every pair x∼x′x \sim x', either u(x,r)≤u(x′,r)u(x, r) \le u(x', r) for all rr, or u(x,r)≥u(x′,r)u(x, r) \ge u(x', r) for all rr. If c=1c = 1, then for all x∼x′x \sim x' and every S⊆RS \subseteq R, Pr⁡[M(x)∈S]≤eεPr⁡[M(x′)∈S]\Pr[M(x) \in S] \le e^{\varepsilon}\Pr[M(x') \in S].

Proof. Fix x∼x′x \sim x'. By symmetry of the relation we may name the pair so that u(x,r)≤u(x′,r)u(x, r) \le u(x', r) for all rr, and we must prove the bound in both orders. With c=1c = 1, sx(r)≤sx′(r)≤sx(r)+εs_x(r) \le s_{x'}(r) \le s_x(r) + \varepsilon for every rr. Summing the exponentials over rr gives Zx≤Zx′≤eεZxZ_x \le Z_{x'} \le e^{\varepsilon} Z_x. Then

Px(r)Px′(r)=esx(r)−sx′(r)⏟≤1⋅Zx′Zx⏟≤eε≤eε,Px′(r)Px(r)=esx′(r)−sx(r)⏟≤eε⋅ZxZx′⏟≤1≤eε.\frac{P_x(r)}{P_{x'}(r)} = \underbrace{e^{s_x(r) - s_{x'}(r)}}_{\le 1} \cdot \underbrace{\frac{Z_{x'}}{Z_x}}_{\le e^{\varepsilon}} \le e^{\varepsilon}, \qquad \frac{P_{x'}(r)}{P_x(r)} = \underbrace{e^{s_{x'}(r) - s_x(r)}}_{\le e^{\varepsilon}} \cdot \underbrace{\frac{Z_x}{Z_{x'}}}_{\le 1} \le e^{\varepsilon}.

The sum over r∈Sr \in S gives the claim in both orders. □\square

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 R=(A,B)R = (A, B), uu the count, Δ=1\Delta = 1, ε=1\varepsilon = 1 and c=1c = 1, with the replace neighbors x=(A,A)x = (A, A) and x′=(A,B)x' = (A, B). The scores are (2,0)(2, 0) and (1,1)(1, 1), so Px(B)=1/(e2+1)=0.119203P_x(B) = 1/(e^2 + 1) = 0.119203 and Px′(B)=1/2P_{x'}(B) = 1/2. The log ratio is ln⁡((e2+1)/2)=1.433781>1\ln((e^2 + 1)/2) = 1.433781 > 1, so the version with c=1c = 1 is not 11-DP under replace. Both factors of the ratio move against BB here: its own score falls, and the normalizer grows.

Theorem 3 (utility). For every xx and t≥0t \ge 0, let OPT=max⁡ru(x,r)\mathrm{OPT} = \max_r u(x, r) and τ=OPT−(cΔ/ε)(ln⁡m+t)\tau = \mathrm{OPT} - (c\Delta/\varepsilon)(\ln m + t). Then Pr⁡[u(x,M(x))≤τ]≤e−t\Pr[u(x, M(x)) \le \tau] \le e^{-t}.

Proof. Let B={r:u(x,r)≤τ}B = \{r : u(x, r) \le \tau\}. For r∈Br \in B, sx(r)≤ετ/(cΔ)=ε OPT/(cΔ)−ln⁡m−ts_x(r) \le \varepsilon\tau/(c\Delta) = \varepsilon\,\mathrm{OPT}/(c\Delta) - \ln m - t. There are at most mm candidates in BB, so ∑r∈Besx(r)≤m⋅eε OPT/(cΔ)⋅e−ln⁡m−t=eε OPT/(cΔ)−t\sum_{r \in B} e^{s_x(r)} \le m \cdot e^{\varepsilon\,\mathrm{OPT}/(c\Delta)} \cdot e^{-\ln m - t} = e^{\varepsilon\,\mathrm{OPT}/(c\Delta) - t}. A candidate r∗r^* with u(x,r∗)=OPTu(x, r^*) = \mathrm{OPT} gives Zx≥esx(r∗)=eε OPT/(cΔ)Z_x \ge e^{s_x(r^*)} = e^{\varepsilon\,\mathrm{OPT}/(c\Delta)}. By Lemma 1, Pr⁡[M(x)∈B]=∑r∈Besx(r)/Zx≤e−t\Pr[M(x) \in B] = \sum_{r \in B} e^{s_x(r)} / Z_x \le e^{-t}. □\square

If the set ROPTR_{\mathrm{OPT}} of best candidates has more than one element, the bound on ZxZ_x improves by the factor ∣ROPT∣|R_{\mathrm{OPT}}|, and the same proof gives ln⁡(m/∣ROPT∣)\ln(m/|R_{\mathrm{OPT}}|) in place of ln⁡m\ln m, which is Dwork-Roth Theorem 3.11.

Lemma 2 (the Gumbel max trick). Let G1,…,GmG_1, \ldots, G_m be independent standard Gumbel variables, with Pr⁡[G≤g]=exp⁡(−e−g)\Pr[G \le g] = \exp(-e^{-g}). Then arg⁡max⁡j(sx(rj)+Gj)\arg\max_j (s_x(r_j) + G_j) has the distribution PxP_x.

Proof. Write sj=sx(rj)s_j = s_x(r_j). The index jj wins when Gi<sj+Gj−siG_i < s_j + G_j - s_i for all i≠ji \ne j; ties have probability 0. Given Gj=gG_j = g, this has probability ∏i≠jexp⁡(−e−(sj+g−si))=exp⁡(−e−g−sj(Z−esj))\prod_{i \ne j} \exp(-e^{-(s_j + g - s_i)}) = \exp(-e^{-g - s_j}(Z - e^{s_j})), with Z=∑iesiZ = \sum_i e^{s_i}. The density of GjG_j is e−gexp⁡(−e−g)e^{-g}\exp(-e^{-g}), so

Pr⁡[j wins]=∫−∞∞e−gexp⁡(−e−gZe−sj) dg=1Ze−sj=esjZ,\Pr[j \text{ wins}] = \int_{-\infty}^{\infty} e^{-g} \exp\big(-e^{-g} Z e^{-s_j}\big)\, dg = \frac{1}{Z e^{-s_j}} = \frac{e^{s_j}}{Z},

with the substitution v=e−gv = e^{-g}, which turns the integral into ∫0∞e−vZe−sj dv\int_0^\infty e^{-v Z e^{-s_j}}\,dv. □\square

Complexity

The model is the real RAM: an exponential, a uniform real number and an addition each cost one step. One evaluation of uu costs qq steps.

  • Time. Line L2 evaluates uu once for each of the mm candidates, in O(mq)O(m q) time. Lines L3 to L5 and the loop of lines L7 to L9 each take O(m)O(m) time. So the time is O(mq)O(m q) in the worst case.
  • Space. The scores and the weights take O(m)O(m) numbers. A version that computes each score twice, once for MM and WW and once in the loop, needs only O(1)O(1) extra space and O(mq)O(m q) time.

When mm 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 (ε,0)(\varepsilon, 0)-DP. The tests compute the exact output distribution on every dataset of at most 4 votes over 3 options, with ε=1\varepsilon = 1. The largest log ratio is 0.433 under add/remove and 0.775 under replace for c=2c = 2, and 0.977 under add/remove for c=1c = 1 (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 ln⁡m\ln m. The loss is O((Δ/ε)ln⁡m)O((\Delta/\varepsilon)\ln m) with high probability, and it does not depend on the size of the dataset. A utility that grows with nn, 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 μ\mu, with a density proportional to exp⁡(εu(x,r)/(2Δ))\exp(\varepsilon u(x, r)/(2\Delta)) with respect to μ\mu.
  • It contains the Laplace mechanism. On R=RR = \mathbb R with u(x,r)=−∣r−f(x)∣u(x, r) = -|r - f(x)| and Δ=Δ1f\Delta = \Delta_1 f, the output density is proportional to exp⁡(−ε∣r−f(x)∣/(cΔ))\exp(-\varepsilon |r - f(x)|/(c\Delta)). This utility is not monotone, so c=2c = 2 and the noise is Lap(2Δ/ε)\mathrm{Lap}(2\Delta/\varepsilon), twice the scale of the Laplace mechanism.
  • Closed under post-processing. Any map of the output that does not read xx keeps ε\varepsilon-DP, by the post-processing theorem.

Variants and improvements

  • Gumbel noise. Add an independent standard Gumbel sample to each score srs_r 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 ε/Δ\varepsilon/\Delta for a monotone utility and ε/(2Δ)\varepsilon/(2\Delta) 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 u(x,r)=−∣#{i:xi≤r}−n/2∣u(x, r) = -|\#\{i : x_i \le r\} - n/2| over a finite grid of values rr, 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 c=1c = 1 has a largest log ratio of 1.866 under replace in the tests, for ε=1\varepsilon = 1, so it is only about 2ε2\varepsilon-DP there. Use c=1c = 1 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 RR is built from the values in xx, such as the set of values that occur, then the presence of a candidate leaks a record. Fix RR in advance, for example as a grid.
  • The sensitivity of one candidate. Δ\Delta must bound the change of u(x,r)u(x, r) for every rr at the same time, and over all pairs of neighbors. A bound at the actual xx is local sensitivity and is not private.
  • Overflow. Without lines L3 and L4, exp⁡(sr)\exp(s_r) overflows for scores above about 709 in 64-bit floats. The tests run it with utilities up to 2×1062 \times 10^6.
  • 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.

dpkit.pyI0RawGitHub
# 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 ln⁡(∣R∣/∣ROPT∣)\ln(|R| / |R_{\mathrm{OPT}}|), 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

  1. 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
  2. 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)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example